Example usage for android.widget LinearLayout addView

List of usage examples for android.widget LinearLayout addView

Introduction

In this page you can find the example usage for android.widget LinearLayout addView.

Prototype

public void addView(View child) 

Source Link

Document

Adds a child view.

Usage

From source file:com.flipzu.flipzu.Player.java

private void displayComment(Hashtable<String, String> comment) {
    if (comment == null)
        return;//from  ww w. j  ava  2s.  c o m

    final LinearLayout com_layout = (LinearLayout) findViewById(R.id.comments_layout);
    TextView comment_tv = new TextView(Player.this);
    comment_tv.setText(comment.get("username") + ": " + comment.get("comment"), TextView.BufferType.SPANNABLE);
    comment_tv.setTextColor(Color.parseColor("#656565"));
    Spannable comment_span = (Spannable) comment_tv.getText();
    comment_span.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, comment_tv.getText().length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    comment_span.setSpan(new ForegroundColorSpan(Color.parseColor("#597490")), 0,
            comment.get("username").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    comment_tv.setText(comment_span);
    com_layout.addView(comment_tv);
}

From source file:jp.ne.sakura.kkkon.android.exceptionhandler.testapp.ExceptionHandlerReportApp.java

/** Called when the activity is first created. */
@Override/* w  w  w.  ja  v  a  2  s.  com*/
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        ExceptionHandler.initialize(context);
        if (ExceptionHandler.needReport()) {
            final String fileName = ExceptionHandler.getBugReportFileAbsolutePath();
            final File file = new File(fileName);
            final File fileZip;
            {
                String strFileZip = file.getAbsolutePath();
                {
                    int index = strFileZip.lastIndexOf('.');
                    if (0 < index) {
                        strFileZip = strFileZip.substring(0, index);
                        strFileZip += ".zip";
                    }
                }
                Log.d(TAG, strFileZip);
                fileZip = new File(strFileZip);
                if (fileZip.exists()) {
                    fileZip.delete();
                }
            }
            if (file.exists()) {
                Log.d(TAG, file.getAbsolutePath());
                InputStream inStream = null;
                ZipOutputStream outStream = null;
                try {
                    inStream = new FileInputStream(file);
                    String strFileName = file.getAbsolutePath();
                    {
                        int index = strFileName.lastIndexOf(File.separatorChar);
                        if (0 < index) {
                            strFileName = strFileName.substring(index + 1);
                        }
                    }
                    Log.d(TAG, strFileName);

                    outStream = new ZipOutputStream(new FileOutputStream(fileZip));
                    byte[] buff = new byte[8124];
                    {
                        ZipEntry entry = new ZipEntry(strFileName);
                        outStream.putNextEntry(entry);

                        int len = 0;
                        while (0 < (len = inStream.read(buff))) {
                            outStream.write(buff, 0, len);
                        }
                        outStream.closeEntry();
                    }
                    outStream.finish();
                    outStream.flush();

                } catch (IOException e) {
                    Log.e(TAG, "got exception", e);
                } finally {
                    if (null != outStream) {
                        try {
                            outStream.close();
                        } catch (Exception e) {
                        }
                    }
                    outStream = null;

                    if (null != inStream) {
                        try {
                            inStream.close();
                        } catch (Exception e) {
                        }
                    }
                    inStream = null;
                }
                Log.i(TAG, "zip created");
            }

            if (file.exists()) {
                // upload or send e-mail
                InputStream inStream = null;
                StringBuilder sb = new StringBuilder();
                try {
                    inStream = new FileInputStream(file);
                    byte[] buff = new byte[8124];
                    int readed = 0;
                    do {
                        readed = inStream.read(buff);
                        for (int i = 0; i < readed; i++) {
                            sb.append((char) buff[i]);
                        }
                    } while (readed >= 0);

                    final String str = sb.toString();
                    Log.i(TAG, str);
                } catch (IOException e) {
                    Log.e(TAG, "got exception", e);
                } finally {
                    if (null != inStream) {
                        try {
                            inStream.close();
                        } catch (Exception e) {
                        }
                    }
                    inStream = null;
                }

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                final Locale defaultLocale = Locale.getDefault();

                String title = "";
                String message = "";
                String positive = "";
                String negative = "";

                boolean needDefaultLang = true;
                if (null != defaultLocale) {
                    if (defaultLocale.equals(Locale.JAPANESE) || defaultLocale.equals(Locale.JAPAN)) {
                        title = "";
                        message = "?????????";
                        positive = "?";
                        negative = "";
                        needDefaultLang = false;
                    }
                }
                if (needDefaultLang) {
                    title = "ERROR";
                    message = "Got unexpected error. Do you want to send information of error.";
                    positive = "Send";
                    negative = "Cancel";
                }
                alertDialog.setTitle(title);
                alertDialog.setMessage(message);
                alertDialog.setPositiveButton(positive + " mail", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface di, int i) {
                        DefaultUploaderMailClient.upload(context, file,
                                new String[] { "diverKon+sakura@gmail.com" });
                    }
                });
                alertDialog.setNeutralButton(positive + " http", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface di, int i) {
                        DefaultUploaderWeb.upload(ExceptionHandlerReportApp.this, fileZip,
                                "http://kkkon.sakura.ne.jp/android/bug");
                    }
                });
                alertDialog.setNegativeButton(negative, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface di, int i) {
                        ExceptionHandler.clearReport();
                    }
                });
                alertDialog.show();
            }
            // TODO separate activity for crash report
            //DefaultCheckerAPK.checkAPK( this, null );
        }
        ExceptionHandler.registHandler();
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("ExceptionHandler");
    layout.addView(tv);

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    Button btn2 = new Button(this);
    btn2.setText("reinstall apk");
    btn2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            boolean foundApk = false;
            {
                final String apkPath = context.getPackageCodePath(); // API8
                Log.d(TAG, "PackageCodePath: " + apkPath);
                final File fileApk = new File(apkPath);
                if (fileApk.exists()) {
                    foundApk = true;

                    Intent promptInstall = new Intent(Intent.ACTION_VIEW);
                    promptInstall.setDataAndType(Uri.fromFile(fileApk),
                            "application/vnd.android.package-archive");
                    promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(promptInstall);
                }
            }

            if (false == foundApk) {
                for (int i = 0; i < 10; ++i) {
                    File fileApk = new File("/data/app/" + context.getPackageName() + "-" + i + ".apk");
                    Log.d(TAG, "check apk:" + fileApk.getAbsolutePath());
                    if (fileApk.exists()) {
                        Log.i(TAG, "apk found. path=" + fileApk.getAbsolutePath());
                        /*
                         * // require parmission
                        {
                        final String strCmd = "pm install -r " + fileApk.getAbsolutePath();
                        try
                        {
                            Runtime.getRuntime().exec( strCmd );
                        }
                        catch ( IOException e )
                        {
                            Log.e( TAG, "got exception", e );
                        }
                        }
                        */
                        Intent promptInstall = new Intent(Intent.ACTION_VIEW);
                        promptInstall.setDataAndType(Uri.fromFile(fileApk),
                                "application/vnd.android.package-archive");
                        promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(promptInstall);
                        break;
                    }
                }
            }
        }
    });
    layout.addView(btn2);

    Button btn3 = new Button(this);
    btn3.setText("check apk");
    btn3.setOnClickListener(new View.OnClickListener() {
        private boolean checkApk(final File fileApk, final ZipEntryFilter filter) {
            final boolean[] result = new boolean[1];
            result[0] = true;

            final Thread thread = new Thread(new Runnable() {

                @Override
                public void run() {
                    if (fileApk.exists()) {
                        ZipFile zipFile = null;
                        try {
                            zipFile = new ZipFile(fileApk);
                            List<ZipEntry> list = new ArrayList<ZipEntry>(zipFile.size());
                            for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) {
                                ZipEntry ent = e.nextElement();
                                Log.d(TAG, ent.getName());
                                Log.d(TAG, "" + ent.getSize());
                                final boolean accept = filter.accept(ent);
                                if (accept) {
                                    list.add(ent);
                                }
                            }

                            Log.d(TAG, Build.CPU_ABI); // API 4
                            Log.d(TAG, Build.CPU_ABI2); // API 8

                            final String[] abiArray = { Build.CPU_ABI // API 4
                                    , Build.CPU_ABI2 // API 8
                            };

                            String abiMatched = null;
                            {
                                boolean foundMatched = false;
                                for (final String abi : abiArray) {
                                    if (null == abi) {
                                        continue;
                                    }
                                    if (0 == abi.length()) {
                                        continue;
                                    }

                                    for (final ZipEntry entry : list) {
                                        Log.d(TAG, entry.getName());

                                        final String prefixABI = "lib/" + abi + "/";
                                        if (entry.getName().startsWith(prefixABI)) {
                                            abiMatched = abi;
                                            foundMatched = true;
                                            break;
                                        }
                                    }

                                    if (foundMatched) {
                                        break;
                                    }
                                }
                            }
                            Log.d(TAG, "matchedAbi=" + abiMatched);

                            if (null != abiMatched) {
                                boolean needReInstall = false;

                                for (final ZipEntry entry : list) {
                                    Log.d(TAG, entry.getName());

                                    final String prefixABI = "lib/" + abiMatched + "/";
                                    if (entry.getName().startsWith(prefixABI)) {
                                        final String jniName = entry.getName().substring(prefixABI.length());
                                        Log.d(TAG, "jni=" + jniName);

                                        final String strFileDst = context.getApplicationInfo().nativeLibraryDir
                                                + "/" + jniName;
                                        Log.d(TAG, strFileDst);
                                        final File fileDst = new File(strFileDst);
                                        if (!fileDst.exists()) {
                                            Log.w(TAG, "needReInstall: content missing " + strFileDst);
                                            needReInstall = true;
                                        } else {
                                            assert (entry.getSize() <= Integer.MAX_VALUE);
                                            if (fileDst.length() != entry.getSize()) {
                                                Log.w(TAG, "needReInstall: size broken " + strFileDst);
                                                needReInstall = true;
                                            } else {
                                                //org.apache.commons.io.IOUtils.contentEquals( zipFile.getInputStream( entry ), new FileInputStream(fileDst) );

                                                final int size = (int) entry.getSize();
                                                byte[] buffSrc = new byte[size];

                                                {
                                                    InputStream inStream = null;
                                                    try {
                                                        inStream = zipFile.getInputStream(entry);
                                                        int pos = 0;
                                                        {
                                                            while (pos < size) {
                                                                final int ret = inStream.read(buffSrc, pos,
                                                                        size - pos);
                                                                if (ret <= 0) {
                                                                    break;
                                                                }
                                                                pos += ret;
                                                            }
                                                        }
                                                    } catch (IOException e) {
                                                        Log.d(TAG, "got exception", e);
                                                    } finally {
                                                        if (null != inStream) {
                                                            try {
                                                                inStream.close();
                                                            } catch (Exception e) {
                                                            }
                                                        }
                                                    }
                                                }
                                                byte[] buffDst = new byte[(int) fileDst.length()];
                                                {
                                                    InputStream inStream = null;
                                                    try {
                                                        inStream = new FileInputStream(fileDst);
                                                        int pos = 0;
                                                        {
                                                            while (pos < size) {
                                                                final int ret = inStream.read(buffDst, pos,
                                                                        size - pos);
                                                                if (ret <= 0) {
                                                                    break;
                                                                }
                                                                pos += ret;
                                                            }
                                                        }
                                                    } catch (IOException e) {
                                                        Log.d(TAG, "got exception", e);
                                                    } finally {
                                                        if (null != inStream) {
                                                            try {
                                                                inStream.close();
                                                            } catch (Exception e) {
                                                            }
                                                        }
                                                    }
                                                }

                                                if (Arrays.equals(buffSrc, buffDst)) {
                                                    Log.d(TAG, " content equal " + strFileDst);
                                                    // OK
                                                } else {
                                                    Log.w(TAG, "needReInstall: content broken " + strFileDst);
                                                    needReInstall = true;
                                                }
                                            }

                                        }

                                    }
                                } // for ZipEntry

                                if (needReInstall) {
                                    // need call INSTALL APK
                                    Log.w(TAG, "needReInstall apk");
                                    result[0] = false;
                                } else {
                                    Log.d(TAG, "no need ReInstall apk");
                                }
                            }

                        } catch (IOException e) {
                            Log.d(TAG, "got exception", e);
                        } finally {
                            if (null != zipFile) {
                                try {
                                    zipFile.close();
                                } catch (Exception e) {
                                }
                            }
                        }
                    }
                }

            });
            thread.setName("check jni so");

            thread.start();
            /*
            while ( thread.isAlive() )
            {
            Log.d( TAG, "check thread.id=" + android.os.Process.myTid() + ",state=" + thread.getState() );
            if ( ! thread.isAlive() )
            {
                break;
            }
            AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this );
            final Locale defaultLocale = Locale.getDefault();
                    
            String title = "";
            String message = "";
            String positive = "";
            String negative = "";
                    
            boolean needDefaultLang = true;
            if ( null != defaultLocale )
            {
                if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) )
                {
                    title = "";
                    message = "???????";
                    positive = "?";
                    negative = "";
                    needDefaultLang = false;
                }
            }
            if ( needDefaultLang )
            {
                title = "INFO";
                message = "Now checking installation. Cancel check?";
                positive = "Wait";
                negative = "Cancel";
            }
            alertDialog.setTitle( title );
            alertDialog.setMessage( message );
            alertDialog.setPositiveButton( positive, null);
            alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() {
                    
                @Override
                public void onClick(DialogInterface di, int i) {
                    if ( thread.isAlive() )
                    {
                        Log.d( TAG, "request interrupt" );
                        thread.interrupt();
                    }
                    else
                    {
                        // nothing
                    }
                }
            } );
                    
            if ( ! thread.isAlive() )
            {
                break;
            }
                    
            alertDialog.show();
                    
            if ( ! Thread.State.RUNNABLE.equals(thread.getState()) )
            {
                break;
            }
                    
            }
            */

            try {
                thread.join();
            } catch (InterruptedException e) {
                Log.d(TAG, "got exception", e);
            }

            return result[0];
        }

        @Override
        public void onClick(View view) {
            boolean foundApk = false;
            {
                final String apkPath = context.getPackageCodePath(); // API8
                Log.d(TAG, "PackageCodePath: " + apkPath);
                final File fileApk = new File(apkPath);
                this.checkApk(fileApk, new ZipEntryFilter() {
                    @Override
                    public boolean accept(ZipEntry entry) {
                        if (entry.isDirectory()) {
                            return false;
                        }

                        final String filename = entry.getName();
                        if (filename.startsWith("lib/")) {
                            return true;
                        }

                        return false;
                    }
                });
            }

        }
    });
    layout.addView(btn3);

    Button btn4 = new Button(this);
    btn4.setText("print dir and path");
    btn4.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            {
                final File file = context.getCacheDir();
                Log.d(TAG, "Ctx.CacheDir=" + file.getAbsoluteFile());
            }
            {
                final File file = context.getExternalCacheDir(); // API 8
                if (null == file) {
                    // no permission
                    Log.d(TAG, "Ctx.ExternalCacheDir=");
                } else {
                    Log.d(TAG, "Ctx.ExternalCacheDir=" + file.getAbsolutePath());
                }
            }
            {
                final File file = context.getFilesDir();
                Log.d(TAG, "Ctx.FilesDir=" + file.getAbsolutePath());
            }
            {
                final String value = context.getPackageResourcePath();
                Log.d(TAG, "Ctx.PackageResourcePath=" + value);
            }
            {
                final String[] files = context.fileList();
                if (null == files) {
                    Log.d(TAG, "Ctx.fileList=" + files);
                } else {
                    for (final String filename : files) {
                        Log.d(TAG, "Ctx.fileList=" + filename);
                    }
                }
            }

            {
                final File file = Environment.getDataDirectory();
                Log.d(TAG, "Env.DataDirectory=" + file.getAbsolutePath());
            }
            {
                final File file = Environment.getDownloadCacheDirectory();
                Log.d(TAG, "Env.DownloadCacheDirectory=" + file.getAbsolutePath());
            }
            {
                final File file = Environment.getExternalStorageDirectory();
                Log.d(TAG, "Env.ExternalStorageDirectory=" + file.getAbsolutePath());
            }
            {
                final File file = Environment.getRootDirectory();
                Log.d(TAG, "Env.RootDirectory=" + file.getAbsolutePath());
            }
            {
                final ApplicationInfo appInfo = context.getApplicationInfo();
                Log.d(TAG, "AppInfo.dataDir=" + appInfo.dataDir);
                Log.d(TAG, "AppInfo.nativeLibraryDir=" + appInfo.nativeLibraryDir); // API 9
                Log.d(TAG, "AppInfo.publicSourceDir=" + appInfo.publicSourceDir);
                {
                    final String[] sharedLibraryFiles = appInfo.sharedLibraryFiles;
                    if (null == sharedLibraryFiles) {
                        Log.d(TAG, "AppInfo.sharedLibraryFiles=" + sharedLibraryFiles);
                    } else {
                        for (final String fileName : sharedLibraryFiles) {
                            Log.d(TAG, "AppInfo.sharedLibraryFiles=" + fileName);
                        }
                    }
                }
                Log.d(TAG, "AppInfo.sourceDir=" + appInfo.sourceDir);
            }
            {
                Log.d(TAG, "System.Properties start");
                final Properties properties = System.getProperties();
                if (null != properties) {
                    for (final Object key : properties.keySet()) {
                        String value = properties.getProperty((String) key);
                        Log.d(TAG, " key=" + key + ",value=" + value);
                    }
                }
                Log.d(TAG, "System.Properties end");
            }
            {
                Log.d(TAG, "System.getenv start");
                final Map<String, String> mapEnv = System.getenv();
                if (null != mapEnv) {
                    for (final Map.Entry<String, String> entry : mapEnv.entrySet()) {
                        final String key = entry.getKey();
                        final String value = entry.getValue();
                        Log.d(TAG, " key=" + key + ",value=" + value);
                    }
                }
                Log.d(TAG, "System.getenv end");
            }
        }
    });
    layout.addView(btn4);

    Button btn5 = new Button(this);
    btn5.setText("check INSTALL_NON_MARKET_APPS");
    btn5.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            SettingsCompat.initialize(context);
            if (SettingsCompat.isAllowedNonMarketApps()) {
                Log.d(TAG, "isAllowdNonMarketApps=true");
            } else {
                Log.d(TAG, "isAllowdNonMarketApps=false");
            }
        }
    });
    layout.addView(btn5);

    Button btn6 = new Button(this);
    btn6.setText("send email");
    btn6.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent mailto = new Intent();
            mailto.setAction(Intent.ACTION_SENDTO);
            mailto.setType("message/rfc822");
            mailto.setData(Uri.parse("mailto:"));
            mailto.putExtra(Intent.EXTRA_EMAIL, new String[] { "" });
            mailto.putExtra(Intent.EXTRA_SUBJECT, "[BugReport] " + context.getPackageName());
            mailto.putExtra(Intent.EXTRA_TEXT, "body text");
            //mailto.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
            //context.startActivity( mailto );
            Intent intent = Intent.createChooser(mailto, "Send Email");
            if (null != intent) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                try {
                    context.startActivity(intent);
                } catch (android.content.ActivityNotFoundException e) {
                    Log.d(TAG, "got Exception", e);
                }
            }
        }
    });
    layout.addView(btn6);

    Button btn7 = new Button(this);
    btn7.setText("upload http thread");
    btn7.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Log.d(TAG, "brd=" + Build.BRAND);
            Log.d(TAG, "prd=" + Build.PRODUCT);

            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
            Log.d(TAG, "fng=" + Build.FINGERPRINT);
            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

            final Thread thread = new Thread(new Runnable() {

                @Override
                public void run() {
                    Log.d(TAG, "upload thread tid=" + android.os.Process.myTid());
                    try {
                        HttpPost httpPost = new HttpPost("http://kkkon.sakura.ne.jp/android/bug");
                        //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                        httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        Log.d(TAG, "socket.timeout="
                                + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                        Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                new Integer(5 * 1000));
                        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                new Integer(5 * 1000));
                        Log.d(TAG, "socket.timeout="
                                + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                        Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                        // <uses-permission android:name="android.permission.INTERNET"/>
                        // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                        HttpResponse response = httpClient.execute(httpPost);
                        Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                    } catch (Exception e) {
                        Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                    }
                    Log.d(TAG, "upload finish");
                }
            });
            thread.setName("upload crash");

            thread.start();
            /*
            while ( thread.isAlive() )
            {
            Log.d( TAG, "thread tid=" + android.os.Process.myTid() + ",state=" + thread.getState() );
            if ( ! thread.isAlive() )
            {
                break;
            }
            AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this );
            final Locale defaultLocale = Locale.getDefault();
                    
            String title = "";
            String message = "";
            String positive = "";
            String negative = "";
                    
            boolean needDefaultLang = true;
            if ( null != defaultLocale )
            {
                if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) )
                {
                    title = "";
                    message = "???????";
                    positive = "?";
                    negative = "";
                    needDefaultLang = false;
                }
            }
            if ( needDefaultLang )
            {
                title = "INFO";
                message = "Now uploading error information. Cancel upload?";
                positive = "Wait";
                negative = "Cancel";
            }
            alertDialog.setTitle( title );
            alertDialog.setMessage( message );
            alertDialog.setPositiveButton( positive, null);
            alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() {
                    
                @Override
                public void onClick(DialogInterface di, int i) {
                    if ( thread.isAlive() )
                    {
                        Log.d( TAG, "request interrupt" );
                        thread.interrupt();
                    }
                    else
                    {
                        // nothing
                    }
                }
            } );
                    
            if ( ! thread.isAlive() )
            {
                break;
            }
                    
            alertDialog.show();
                    
            if ( ! Thread.State.RUNNABLE.equals(thread.getState()) )
            {
                break;
            }
                    
            }
            */

            /*
            try
            {
            thread.join(); // must call. leak handle...
            }
            catch ( InterruptedException e )
            {
            Log.d( TAG, "got Exception", e );
            }
            */
        }
    });
    layout.addView(btn7);

    Button btn8 = new Button(this);
    btn8.setText("upload http AsyncTask");
    btn8.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                @Override
                protected Boolean doInBackground(String... paramss) {
                    Boolean result = true;
                    Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                    try {
                        //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                        Log.d(TAG, "fng=" + Build.FINGERPRINT);
                        final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                        list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                        HttpPost httpPost = new HttpPost(paramss[0]);
                        //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                        httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        Log.d(TAG, "socket.timeout="
                                + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                        Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                new Integer(5 * 1000));
                        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                new Integer(5 * 1000));
                        Log.d(TAG, "socket.timeout="
                                + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                        Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                        // <uses-permission android:name="android.permission.INTERNET"/>
                        // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                        HttpResponse response = httpClient.execute(httpPost);
                        Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                    } catch (Exception e) {
                        Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                        result = false;
                    }
                    Log.d(TAG, "upload finish");
                    return result;
                }

            };

            asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
            asyncTask.isCancelled();
        }
    });
    layout.addView(btn8);

    Button btn9 = new Button(this);
    btn9.setText("call checkAPK");
    btn9.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final boolean result = DefaultCheckerAPK.checkAPK(ExceptionHandlerReportApp.this, null);
            Log.i(TAG, "checkAPK result=" + result);
        }
    });
    layout.addView(btn9);

    setContentView(layout);
}

From source file:com.example.sam.savemeapp.StatisticsFragment.java

/**
 * Sets up the initial legend with the contained categories shown
 * in the pie chart and bullet points with the corresponding colors.
 */// www  . j  a  va  2s  .c om
public void setUpPiechart() {
    pieChart.getDescription().setEnabled(false);
    Legend pieL = pieChart.getLegend();
    Log.d("stats", Float.toString(pieL.getEntries().length));
    startLegend = pieL;
    LegendEntry[] legends = pieL.getEntries();
    pieL.setEnabled(false);
    mLegend.removeAllViews();
    //The default legend consist of TextViews and ImageViews which contains a bullet point.
    //The legends are contained inside of a horizontal LinearLayout which is contained in a vertical LinearLayout.
    for (int t = 0; t < legends.length - 1; t++) {
        LegendEntry x = legends[t];
        LinearLayout hLayout = new LinearLayout(getContext());
        hLayout.setLayoutParams(params);
        TextView tv = new TextView(getContext());
        tv.setText(x.label);
        tv.setTextColor(x.formColor);
        tv.setTypeface(fontLight);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                getResources().getDimension(R.dimen.statistics_main_text_size));
        tv.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        LinearLayoutCompat.LayoutParams textViewParams = new LinearLayoutCompat.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        textViewParams.setMarginStart((int) getResources().getDimension(R.dimen.statistics_text_margin));
        tv.setLayoutParams(textViewParams);
        ImageView iv = new ImageView(getContext());
        Drawable dot = ContextCompat.getDrawable(getContext(), R.drawable.circle_legend);
        dot.setColorFilter(x.formColor, PorterDuff.Mode.SRC);
        iv.setImageDrawable(dot);
        iv.setLayoutParams(new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        hLayout.addView(iv);
        hLayout.addView(tv);
        mLegend.addView(hLayout);
    }

    designPiechart();

    pieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
        private int color;

        @Override
        public void onValueSelected(Entry e, Highlight h) {
            //it creates new legends with the information of the subcategories when a
            // category in the pi chart is clicked
            ArrayList<LegendEntry> list = new ArrayList<>();
            mLegend.removeAllViews();
            if (e.getData().equals(Color.parseColor("#00a0ae"))) {
                for (LegendEntry x : startLegend.getEntries()) {
                    if (x.label.equals("Food & Beverage")) {
                        color = x.formColor;
                    }
                }
                list.add(new LegendEntry("Food & Beverage: "
                        + u.categories.get("Food & Beverage").get("Food & Beverage") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry("Restaurant & Caf: "
                        + u.categories.get("Food & Beverage").get("Restaurant & Caf") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry(
                        "Supermarket: " + u.categories.get("Food & Beverage").get("Supermarket") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                mLegend.removeAllViews();
                //This category legends consist of the main category in this case "Food & Beverage" in the top of the legend
                //and the sub categories bellow. The name is also shown together with the amount spend in that category.
                for (LegendEntry x : list) {
                    TextView tv = new TextView(getContext());
                    if (x.equals(list.get(0))) {
                        tv.setTypeface(fontBlack);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                                getResources().getDimension(R.dimen.statistics_main_text_size));
                    } else {
                        tv.setTypeface(fontLight);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                                getResources().getDimension(R.dimen.statistics_text_size));
                    }
                    tv.setText(x.label);
                    tv.setTextColor(color);
                    tv.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                    mLegend.addView(tv);
                }
            } else if (e.getData().equals(Color.parseColor("#be3127"))) {
                for (LegendEntry x : startLegend.getEntries()) {
                    if (x.label.equals("Transportation")) {
                        color = x.formColor;
                    }
                }
                list.add(new LegendEntry("Transportation: "
                        + u.categories.get("Transportation").get("Transportation") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry("Public transport: "
                        + u.categories.get("Transportation").get("Public transport") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry(
                        "Taxi & Uber: " + u.categories.get("Transportation").get("Taxi & Uber") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry(
                        "Petrol: " + u.categories.get("Transportation").get("Petrol") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry(
                        "Maintenance: " + u.categories.get("Transportation").get("Maintenance") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                mLegend.removeAllViews();
                for (LegendEntry x : list) {
                    TextView tv = new TextView(getContext());
                    if (x.equals(list.get(0))) {
                        tv.setTypeface(fontBlack);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                                getResources().getDimension(R.dimen.statistics_main_text_size));
                    } else {
                        tv.setTypeface(fontLight);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                                getResources().getDimension(R.dimen.statistics_text_size));
                    }
                    tv.setText(x.label);
                    tv.setTextColor(color);
                    tv.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                    mLegend.addView(tv);
                }
            } else if (e.getData().equals(Color.parseColor("#7dc725"))) {
                for (LegendEntry x : startLegend.getEntries()) {
                    if (x.label.equals("Shopping")) {
                        color = x.formColor;
                    }
                }
                list.add(new LegendEntry(
                        "Shopping: " + u.categories.get("Shopping").get("Shopping") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry(
                        "Clothing: " + u.categories.get("Shopping").get("Clothing") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry(
                        "Electronics: " + u.categories.get("Shopping").get("Electronics") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry("Books: " + u.categories.get("Shopping").get("Books") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry("Gifts: " + u.categories.get("Shopping").get("Gifts") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry("Other: " + u.categories.get("Shopping").get("Other") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                mLegend.removeAllViews();
                for (LegendEntry x : list) {
                    TextView tv = new TextView(getContext());
                    if (x.equals(list.get(0))) {
                        tv.setTypeface(fontBlack);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                                getResources().getDimension(R.dimen.statistics_main_text_size));
                    } else {
                        tv.setTypeface(fontLight);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                                getResources().getDimension(R.dimen.statistics_text_size));
                    }
                    tv.setText(x.label);
                    tv.setTextColor(color);
                    tv.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                    mLegend.addView(tv);
                }
            } else if (e.getData().equals(Color.parseColor("#e88300"))) {
                for (LegendEntry x : startLegend.getEntries()) {
                    if (x.label.equals("Entertainment")) {
                        color = x.formColor;
                    }
                }
                list.add(new LegendEntry(
                        "Entertainment: " + u.categories.get("Entertainment").get("Entertainment") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry(
                        "Going out: " + u.categories.get("Entertainment").get("Going out") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry(
                        "Sports: " + u.categories.get("Entertainment").get("Sports") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                mLegend.removeAllViews();
                for (LegendEntry x : list) {
                    TextView tv = new TextView(getContext());
                    if (x.equals(list.get(0))) {
                        tv.setTypeface(fontBlack);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                                getResources().getDimension(R.dimen.statistics_main_text_size));
                    } else {
                        tv.setTypeface(fontLight);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                                getResources().getDimension(R.dimen.statistics_text_size));
                    }
                    tv.setText(x.label);
                    tv.setTextColor(color);
                    tv.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                    mLegend.addView(tv);
                }
            } else if (e.getData().equals(Color.parseColor("#dc006d"))) {
                for (LegendEntry x : startLegend.getEntries()) {
                    if (x.label.equals("Health")) {
                        color = x.formColor;
                    }
                }
                list.add(new LegendEntry("Health: " + u.categories.get("Health").get("Health") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry("Doctor: " + u.categories.get("Health").get("Doctor") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry("Pharmacy: " + u.categories.get("Health").get("Pharmacy") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                mLegend.removeAllViews();
                for (LegendEntry x : list) {
                    TextView tv = new TextView(getContext());
                    if (x.equals(list.get(0))) {
                        tv.setTypeface(fontBlack);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                                getResources().getDimension(R.dimen.statistics_main_text_size));
                    } else {
                        tv.setTypeface(fontLight);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                                getResources().getDimension(R.dimen.statistics_text_size));
                    }
                    tv.setText(x.label);
                    tv.setTextColor(color);
                    tv.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                    mLegend.addView(tv);
                }
            } else if (e.getData().equals(Color.parseColor("#1562a4"))) {
                for (LegendEntry x : startLegend.getEntries()) {
                    if (x.label.equals("Bills")) {
                        color = x.formColor;
                    }
                }
                list.add(new LegendEntry("Bills: " + u.categories.get("Bills").get("Bills") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry("Water: " + u.categories.get("Bills").get("Water") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry(
                        "Electricity: " + u.categories.get("Bills").get("Electricity") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry("Gas: " + u.categories.get("Bills").get("Gas") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry("Rent: " + u.categories.get("Bills").get("Rent") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry("Phone: " + u.categories.get("Bills").get("Phone") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(
                        new LegendEntry("Insurance: " + u.categories.get("Bills").get("Insurance") + u.currency,
                                Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry("TV: " + u.categories.get("Bills").get("TV") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                list.add(new LegendEntry("Internet: " + u.categories.get("Bills").get("Internet") + u.currency,
                        Legend.LegendForm.SQUARE, 7f, 7f, null, color));
                mLegend.removeAllViews();
                for (LegendEntry x : list) {
                    TextView tv = new TextView(getContext());
                    if (x.equals(list.get(0))) {
                        tv.setTypeface(fontBlack);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                                getResources().getDimension(R.dimen.statistics_main_text_size));
                    } else {
                        tv.setTypeface(fontLight);
                        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                                getResources().getDimension(R.dimen.statistics_text_size));
                    }
                    tv.setText(x.label);
                    tv.setTextColor(color);
                    tv.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                    mLegend.addView(tv);
                }
            }
        }

        @Override
        public void onNothingSelected() {
            //Sets up the default legend when nothing is selected
            pieChart = (PieChart) v.findViewById(R.id.piechart);
            pieChart.setUsePercentValues(true);
            LegendEntry[] legends = startLegend.getEntries();
            startLegend.setEnabled(false);
            mLegend.removeAllViews();
            for (LegendEntry x : legends) {
                LinearLayout hLayout = new LinearLayout(getContext());
                hLayout.setLayoutParams(params);
                TextView tv = new TextView(getContext());
                tv.setText(x.label);
                tv.setTextColor(x.formColor);
                tv.setTypeface(fontLight);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,
                        getResources().getDimension(R.dimen.statistics_main_text_size));
                tv.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                LinearLayoutCompat.LayoutParams textViewParams = new LinearLayoutCompat.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                textViewParams
                        .setMarginStart((int) getResources().getDimension(R.dimen.statistics_text_margin));
                tv.setLayoutParams(textViewParams);
                ImageView iv = new ImageView(getContext());
                Drawable dot = ContextCompat.getDrawable(getContext(), R.drawable.circle_legend);
                dot.setColorFilter(x.formColor, PorterDuff.Mode.SRC);
                iv.setImageDrawable(dot);
                iv.setLayoutParams(new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.MATCH_PARENT));
                hLayout.addView(iv);
                hLayout.addView(tv);
                mLegend.addView(hLayout);
            }
        }
    });
}

From source file:com.adarshahd.indianrailinfo.donate.PNRStat.java

private void showOfflinePNRStatus(String trainDetails, ArrayList<String> passnDetails) {
    LinearLayout ll = new LinearLayout(mActivity);

    TextView textViewTrnDtls = new TextView(mActivity);
    TextView textViewPsnDtls = new TextView(mActivity);
    TextView tvTrainDetails = new TextView(mActivity);
    TextView[] tvPassnDetails = new TextView[passnDetails.size()];

    textViewTrnDtls.setText("Train Details: " + mPNRNumber);
    textViewTrnDtls.setFocusable(true);//w w w.ja va 2  s  .c  om
    textViewPsnDtls.setText("Passenger Details");
    tvTrainDetails.setText(trainDetails);
    textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
    textViewPsnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
    tvTrainDetails.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Small);
    textViewTrnDtls.setPadding(10, 10, 10, 10);
    textViewPsnDtls.setPadding(10, 10, 10, 10);
    tvTrainDetails.setPadding(10, 10, 10, 10);

    tvTrainDetails.setBackgroundResource(R.drawable.card_background);
    textViewTrnDtls.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
    textViewPsnDtls.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
    ll.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.addView(textViewTrnDtls);

    ll.addView(tvTrainDetails);
    ll.addView(textViewPsnDtls);
    for (int i = 0; i < passnDetails.size(); ++i) {
        tvPassnDetails[i] = new TextView(mActivity);
        tvPassnDetails[i].setText(passnDetails.get(i));
        tvPassnDetails[i].setPadding(10, 10, 10, 10);
        tvPassnDetails[i].setBackgroundResource(R.drawable.card_background);
        tvPassnDetails[i].setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Medium);
        ll.addView(tvPassnDetails[i]);
    }
    mFrameLayout.removeAllViews();
    mFrameLayout.addView(ll);
}

From source file:com.hippo.ehviewer.ui.scene.GalleryDetailScene.java

@SuppressWarnings("deprecation")
private void bindTags(GalleryTagGroup[] tagGroups) {
    Context context = getContext2();
    LayoutInflater inflater = getLayoutInflater2();
    Resources resources = getResources2();
    if (null == context || null == inflater || null == resources || null == mTags || null == mNoTags) {
        return;//from  ww w.java  2  s  . c om
    }

    mTags.removeViews(1, mTags.getChildCount() - 1);
    if (tagGroups == null || tagGroups.length == 0) {
        mNoTags.setVisibility(View.VISIBLE);
        return;
    } else {
        mNoTags.setVisibility(View.GONE);
    }

    int colorTag = resources.getColor(R.color.colorPrimary);
    int colorName = resources.getColor(R.color.purple_a400);
    for (GalleryTagGroup tg : tagGroups) {
        LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.gallery_tag_group, mTags, false);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        mTags.addView(ll);

        TextView tgName = (TextView) inflater.inflate(R.layout.item_gallery_tag, ll, false);
        ll.addView(tgName);
        tgName.setText(tg.groupName);
        tgName.setBackgroundDrawable(new RoundSideRectDrawable(colorName));

        AutoWrapLayout awl = new AutoWrapLayout(context);
        ll.addView(awl, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        for (int j = 0, z = tg.size(); j < z; j++) {
            TextView tag = (TextView) inflater.inflate(R.layout.item_gallery_tag, awl, false);
            awl.addView(tag);
            String tagStr = tg.getTagAt(j);
            tag.setText(tagStr);
            tag.setBackgroundDrawable(new RoundSideRectDrawable(colorTag));
            tag.setTag(R.id.tag, tg.groupName + ":" + tagStr);
            tag.setOnClickListener(this);
            tag.setOnLongClickListener(this);
        }
    }
}

From source file:at.alladin.rmbt.android.adapter.result.RMBTResultPagerAdapter.java

public void addResultListItem(String title, String value, LinearLayout netLayout) {
    final float scale = activity.getResources().getDisplayMetrics().density;
    final int leftRightDiv = Helperfunctions.dpToPx(0, scale);
    final int topBottomDiv = Helperfunctions.dpToPx(0, scale);
    final int heightDiv = Helperfunctions.dpToPx(1, scale);

    LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final View measurementItemView = inflater.inflate(R.layout.classification_list_item, netLayout, false);

    final TextView itemTitle = (TextView) measurementItemView.findViewById(R.id.classification_item_title);
    itemTitle.setText(title);//from   w  ww .j  a  v a2 s.c om

    final ImageView itemClassification = (ImageView) measurementItemView
            .findViewById(R.id.classification_item_color);
    itemClassification.setImageResource(Helperfunctions.getClassificationColor(-1));

    itemClassification.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            activity.showHelp(R.string.url_help_result, false);
        }
    });

    final TextView itemValue = (TextView) measurementItemView.findViewById(R.id.classification_item_value);
    itemValue.setText(value);

    netLayout.addView(measurementItemView);

    final View divider = new View(activity);
    divider.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, heightDiv, 1));
    divider.setPadding(leftRightDiv, topBottomDiv, leftRightDiv, topBottomDiv);

    divider.setBackgroundResource(R.drawable.bg_trans_light_10);

    netLayout.addView(divider);

    netLayout.invalidate();
}

From source file:com.ubikod.capptain.android.sdk.reach.activity.CapptainPollActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    /* Init layout */
    super.onCreate(savedInstanceState);

    /* If no content, nothing to do, super class already called finish */
    if (mContent == null)
        return;//from   w  ww.j  a va2s .  c  om

    /* Render questions */
    LinearLayout questionsLayout = getView("questions");
    JSONArray questions = mContent.getQuestions();
    LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    try {
        for (int i = 0; i < questions.length(); i++) {
            /* Get question */
            JSONObject question = questions.getJSONObject(i);

            /* Inflate question layout */
            LinearLayout questionLayout = (LinearLayout) layoutInflater
                    .inflate(getLayoutId("capptain_poll_question"), null);

            /* Set question's title */
            TextView questionTitle = (TextView) questionLayout.findViewById(getId("question_title"));
            questionTitle.setText(question.getString("title"));

            /* Set choices */
            RadioGroup choicesView = (RadioGroup) questionLayout.findViewById(getId("choices"));
            choicesView.setTag(question);
            JSONArray choices = question.getJSONArray("choices");
            int choiceViewId = 0;
            for (int j = 0; j < choices.length(); j++) {
                /* Get choice */
                JSONObject choice = choices.getJSONObject(j);

                /* Inflate choice layout */
                RadioButton choiceView = (RadioButton) layoutInflater
                        .inflate(getLayoutId("capptain_poll_choice"), null);

                /* Each choice is a radio button */
                choiceView.setId(choiceViewId++);
                choiceView.setTag(choice.getString("id"));
                choiceView.setText(choice.getString("title"));
                choiceView.setChecked(choice.getBoolean("default"));
                choicesView.addView(choiceView);
            }

            /* Add to parent layouts */
            questionsLayout.addView(questionLayout);

            /* Watch state */
            mRadioGroups.add(choicesView);
            choicesView.setOnCheckedChangeListener(mRadioGroupListener);
        }
    } catch (JSONException jsone) {
        /* Won't happen */
    }

    /* Disable action if a choice is not selected */
    updateActionState();
}

From source file:com.partypoker.poker.engagement.reach.activity.EngagementPollActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    /* Init layout */
    super.onCreate(savedInstanceState);

    /* If no content, nothing to do, super class already called finish */
    if (mContent == null)
        return;//w  w  w  . java  2  s. c om

    /* Render questions */
    LinearLayout questionsLayout = getView("questions");
    JSONArray questions = mContent.getQuestions();
    LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    try {
        for (int i = 0; i < questions.length(); i++) {
            /* Get question */
            JSONObject question = questions.getJSONObject(i);

            /* Inflate question layout */
            LinearLayout questionLayout = (LinearLayout) layoutInflater
                    .inflate(getLayoutId("engagement_poll_question"), null);

            /* Set question's title */
            TextView questionTitle = (TextView) questionLayout.findViewById(getId("question_title"));
            questionTitle.setText(question.getString("title"));

            /* Set choices */
            RadioGroup choicesView = (RadioGroup) questionLayout.findViewById(getId("choices"));
            choicesView.setTag(question);
            JSONArray choices = question.getJSONArray("choices");
            int choiceViewId = 0;
            for (int j = 0; j < choices.length(); j++) {
                /* Get choice */
                JSONObject choice = choices.getJSONObject(j);

                /* Inflate choice layout */
                RadioButton choiceView = (RadioButton) layoutInflater
                        .inflate(getLayoutId("engagement_poll_choice"), null);

                /* Each choice is a radio button */
                choiceView.setId(choiceViewId++);
                choiceView.setTag(choice.getString("id"));
                choiceView.setText(choice.getString("title"));
                choiceView.setChecked(choice.optBoolean("isDefault"));
                choicesView.addView(choiceView);
            }

            /* Add to parent layouts */
            questionsLayout.addView(questionLayout);

            /* Watch state */
            mRadioGroups.add(choicesView);
            choicesView.setOnCheckedChangeListener(mRadioGroupListener);
        }
    } catch (JSONException jsone) {
        /* Drop on parsing error */
        mContent.dropContent(this);
        finish();
        return;
    }

    /* Disable action if a choice is not selected */
    updateActionState();
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MyToolsFragment.java

private void updateToolList(Set<Map.Entry<String, ArrayList<ToolEntry>>> tools,
        final LinearLayout toolContainer) {
    if (fiskInfoUtility.isNetworkAvailable(getActivity())) {
        List<ToolEntry> localTools = new ArrayList<>();
        final List<ToolEntry> unconfirmedRemovedTools = new ArrayList<>();
        final List<ToolEntry> synchedTools = new ArrayList<>();

        for (final Map.Entry<String, ArrayList<ToolEntry>> dateEntry : tools) {
            for (final ToolEntry toolEntry : dateEntry.getValue()) {
                if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED) {
                    continue;
                } else if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_RECEIVED) {
                    synchedTools.add(toolEntry);
                } else if (!(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED)) {
                    localTools.add(toolEntry);
                } else {
                    unconfirmedRemovedTools.add(toolEntry);
                }/*from  w  w w  .  j  av a 2s. c  o m*/
            }
        }

        barentswatchApi.setAccesToken(user.getToken());

        Response response = barentswatchApi.getApi().geoDataDownload("fishingfacility", "JSON");

        if (response == null) {
            Log.d(TAG, "RESPONSE == NULL");
        }

        byte[] toolData;
        try {
            toolData = FiskInfoUtility.toByteArray(response.getBody().in());
            JSONObject featureCollection = new JSONObject(new String(toolData));
            JSONArray jsonTools = featureCollection.getJSONArray("features");
            JSONArray matchedTools = new JSONArray();
            UserSettings settings = user.getSettings();

            for (int i = 0; i < jsonTools.length(); i++) {
                JSONObject tool = jsonTools.getJSONObject(i);
                boolean hasCopy = false;

                for (int j = 0; j < localTools.size(); j++) {
                    if (localTools.get(j).getToolId()
                            .equals(tool.getJSONObject("properties").getString("toolid"))) {
                        SimpleDateFormat sdfMilliSeconds = new SimpleDateFormat(
                                getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss),
                                Locale.getDefault());
                        SimpleDateFormat sdfMilliSecondsRemote = new SimpleDateFormat(
                                getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss),
                                Locale.getDefault());
                        SimpleDateFormat sdfRemote = new SimpleDateFormat(
                                getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss), Locale.getDefault());

                        sdfMilliSeconds.setTimeZone(TimeZone.getTimeZone("UTC"));
                        /* Timestamps from BW seem to be one hour earlier than UTC/GMT?  */
                        sdfMilliSecondsRemote.setTimeZone(TimeZone.getTimeZone("GMT-1"));
                        sdfRemote.setTimeZone(TimeZone.getTimeZone("GMT-1"));
                        Date localLastUpdatedDateTime;
                        Date localUpdatedBySourceDateTime;
                        Date serverUpdatedDateTime;
                        Date serverUpdatedBySourceDateTime = null;
                        try {
                            localLastUpdatedDateTime = sdfMilliSeconds
                                    .parse(localTools.get(j).getLastChangedDateTime());
                            localUpdatedBySourceDateTime = sdfMilliSeconds
                                    .parse(localTools.get(j).getLastChangedBySource());

                            serverUpdatedDateTime = tool.getJSONObject("properties")
                                    .getString("lastchangeddatetime").length() == getResources()
                                            .getInteger(R.integer.datetime_without_milliseconds_length)
                                                    ? sdfRemote.parse(tool.getJSONObject("properties")
                                                            .getString("lastchangeddatetime"))
                                                    : sdfMilliSecondsRemote
                                                            .parse(tool.getJSONObject("properties")
                                                                    .getString("lastchangeddatetime"));

                            if (tool.getJSONObject("properties").has("lastchangedbysource")) {
                                serverUpdatedBySourceDateTime = tool.getJSONObject("properties")
                                        .getString("lastchangedbysource").length() == getResources()
                                                .getInteger(R.integer.datetime_without_milliseconds_length)
                                                        ? sdfRemote.parse(tool.getJSONObject("properties")
                                                                .getString("lastchangedbysource"))
                                                        : sdfMilliSecondsRemote
                                                                .parse(tool.getJSONObject("properties")
                                                                        .getString("lastchangedbysource"));
                            }

                            if ((localLastUpdatedDateTime.equals(serverUpdatedDateTime)
                                    || localLastUpdatedDateTime.before(serverUpdatedDateTime))
                                    && serverUpdatedBySourceDateTime != null
                                    && (localUpdatedBySourceDateTime.equals(serverUpdatedBySourceDateTime)
                                            || localUpdatedBySourceDateTime
                                                    .before(serverUpdatedBySourceDateTime))) {
                                localTools.get(j).updateFromGeoJson(tool, getActivity());

                                localTools.get(j).setToolStatus(ToolEntryStatus.STATUS_RECEIVED);
                            } else if (serverUpdatedBySourceDateTime != null
                                    && localUpdatedBySourceDateTime.after(serverUpdatedBySourceDateTime)) {
                                // TODO: Do nothing, local changes should be reported.

                            } else {
                                // TODO: what gives?
                            }

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        localTools.remove(j);
                        j--;

                        hasCopy = true;
                        break;
                    }
                }

                for (int j = 0; j < unconfirmedRemovedTools.size(); j++) {
                    if (unconfirmedRemovedTools.get(j).getToolId()
                            .equals(tool.getJSONObject("properties").getString("toolid"))) {
                        hasCopy = true;
                        unconfirmedRemovedTools.remove(j);
                        j--;
                    }
                }

                for (int j = 0; j < synchedTools.size(); j++) {
                    if (synchedTools.get(j).getToolId()
                            .equals(tool.getJSONObject("properties").getString("toolid"))) {
                        hasCopy = true;
                        synchedTools.remove(j);
                        j--;
                    }
                }

                if (!hasCopy && settings != null) {
                    if ((!settings.getVesselName().isEmpty()
                            && (FiskInfoUtility.ReplaceRegionalCharacters(settings.getVesselName())
                                    .equalsIgnoreCase(tool.getJSONObject("properties").getString("vesselname"))
                                    || settings.getVesselName().equalsIgnoreCase(
                                            tool.getJSONObject("properties").getString("vesselname"))))
                            && ((!settings.getIrcs().isEmpty() && settings.getIrcs().toUpperCase()
                                    .equals(tool.getJSONObject("properties").getString("ircs")))
                                    || (!settings.getMmsi().isEmpty() && settings.getMmsi()
                                            .equals(tool.getJSONObject("properties").getString("mmsi")))
                                    || (!settings.getImo().isEmpty() && settings.getImo()
                                            .equals(tool.getJSONObject("properties").getString("imo"))))) {
                        matchedTools.put(tool);
                    }
                }
            }

            if (matchedTools.length() > 0) {
                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button addToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);
                final List<ToolConfirmationRow> matchedToolsList = new ArrayList<>();

                for (int i = 0; i < matchedTools.length(); i++) {
                    ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(),
                            matchedTools.getJSONObject(i));
                    linearLayoutToolContainer.addView(confirmationRow.getView());
                    matchedToolsList.add(confirmationRow);
                }

                addToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolConfirmationRow row : matchedToolsList) {
                            if (row.isChecked()) {
                                ToolEntry newTool = row.getToolEntry();
                                user.getToolLog().addTool(newTool, newTool.getSetupDateTime().substring(0, 10));
                                ToolLogRow newRow = new ToolLogRow(v.getContext(), newTool,
                                        utilityOnClickListeners.getToolEntryEditDialogOnClickListener(
                                                getActivity(), getFragmentManager(), mGpsLocationTracker,
                                                newTool, user));
                                row.getView().setTag(newTool.getToolId());
                                toolContainer.addView(newRow.getView());
                            }
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog));
                dialog.show();
            }

            if (unconfirmedRemovedTools.size() > 0) {
                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                TextView infoTextView = (TextView) dialog.findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                infoTextView.setText(R.string.removed_tools_information_text);
                archiveToolsButton.setText(R.string.ok);
                cancelButton.setVisibility(View.GONE);

                for (ToolEntry removedEntry : unconfirmedRemovedTools) {
                    ToolLogRow removedToolRow = new ToolLogRow(getActivity(), removedEntry, null);
                    removedToolRow.setToolNotificationImageViewVisibility(false);
                    removedToolRow.setEditToolImageViewVisibility(false);
                    linearLayoutToolContainer.addView(removedToolRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry removedEntry : unconfirmedRemovedTools) {
                            removedEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);

                            for (int i = 0; i < toolContainer.getChildCount(); i++) {
                                if (removedEntry.getToolId()
                                        .equals(toolContainer.getChildAt(i).getTag().toString())) {
                                    toolContainer.removeViewAt(i);
                                    break;
                                }
                            }
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                dialog.show();
            }

            if (synchedTools.size() > 0) {
                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                TextView infoTextView = (TextView) dialog.findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                infoTextView.setText(R.string.unexpected_tool_removal_info_text);
                archiveToolsButton.setText(R.string.archive);

                for (ToolEntry removedEntry : synchedTools) {
                    ToolLogRow removedToolRow = new ToolLogRow(getActivity(), removedEntry, null);
                    removedToolRow.setToolNotificationImageViewVisibility(false);
                    removedToolRow.setEditToolImageViewVisibility(false);
                    linearLayoutToolContainer.addView(removedToolRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry removedEntry : synchedTools) {
                            removedEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);

                            for (int i = 0; i < toolContainer.getChildCount(); i++) {
                                if (removedEntry.getToolId()
                                        .equals(toolContainer.getChildAt(i).getTag().toString())) {
                                    toolContainer.removeViewAt(i);
                                    break;
                                }
                            }
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog));
                dialog.show();
            }

            if (unconfirmedRemovedTools.size() > 0) {
                // TODO: If not found server side, tool is assumed to be removed. Inform user.

                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.reported_tools_removed_title);
                TextView informationTextView = (TextView) dialog
                        .findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                informationTextView.setText(getString(R.string.removed_tools_information_text));
                cancelButton.setVisibility(View.GONE);
                archiveToolsButton.setText(getString(R.string.ok));

                for (ToolEntry toolEntry : unconfirmedRemovedTools) {
                    ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), toolEntry);
                    linearLayoutToolContainer.addView(confirmationRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry toolEntry : unconfirmedRemovedTools) {
                            toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                dialog.show();
            }

            if (synchedTools.size() > 0) {
                //                    // TODO: Prompt user: Tool was confirmed, now is no longer at BW, remove or archive?

                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                TextView informationTextView = (TextView) dialog
                        .findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                informationTextView.setText(getString(R.string.unexpected_tool_removal_info_text));
                archiveToolsButton.setText(getString(R.string.ok));

                for (ToolEntry toolEntry : synchedTools) {
                    ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), toolEntry);
                    linearLayoutToolContainer.addView(confirmationRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry toolEntry : synchedTools) {
                            toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog));

                dialog.show();
            }

            user.writeToSharedPref(getActivity());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.google.example.eightbitartist.DrawingActivity.java

/**
 * Show a small view for each connected player with their picture, name, and score.
 *///  ww  w.j ava2 s. c  o  m
private void setUpPlayerViews() {
    // Remove all existing views (note that removing and re-adding all views is not very
    // efficient and you should not do it in your own application).
    LinearLayout playerViews = (LinearLayout) findViewById(R.id.playerViews);
    playerViews.removeAllViewsInLayout();

    // Sort the list to determine which player is the artist so we can highlight that view
    List<String> ids = new ArrayList<>();
    ids.addAll(mParticipants.keySet());
    Collections.sort(ids);
    int artistIndex = mMatchTurnNumber % ids.size();
    String artistId = ids.get(artistIndex);

    // Create a PlayerView for each participant
    for (DrawingParticipant participant : mParticipants.values()) {
        PlayerView playerView = new PlayerView(this);
        playerView.populateWithParticipant(participant);
        playerView.setIsArtist(participant.getPersistentId().equals(artistId));
        playerViews.addView(playerView);
    }
}