Example usage for android.widget ArrayAdapter notifyDataSetChanged

List of usage examples for android.widget ArrayAdapter notifyDataSetChanged

Introduction

In this page you can find the example usage for android.widget ArrayAdapter notifyDataSetChanged.

Prototype

@Override
    public void notifyDataSetChanged() 

Source Link

Usage

From source file:com.jtschohl.androidfirewall.MainActivity.java

/**
 * update spinner with changed profile names
 */// ww  w  .  j a  v a  2  s .c  om
public void updateSpinner() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    final List<String> profilestring = new ArrayList<String>();
    profilestring.add(prefs.getString("default", getString(R.string.defaultprofile)));
    profilestring.add(prefs.getString("profile1", getString(R.string.profile1)));
    profilestring.add(prefs.getString("profile2", getString(R.string.profile2)));
    profilestring.add(prefs.getString("profile3", getString(R.string.profile3)));
    profilestring.add(prefs.getString("profile4", getString(R.string.profile4)));
    profilestring.add(prefs.getString("profile5", getString(R.string.profile5)));
    profileposition = profilestring.toArray(new String[profilestring.size()]);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item,
            profileposition);
    adapter.notifyDataSetChanged();
    spinner.setAdapter(adapter);
    spinner.setSelection(prefs.getInt("itemPosition", 0));
}

From source file:com.hangulo.powercontact.ContactsListFragment.java

void setDistanceSpinnerAdapter() {
    // title must be changed by locale / ?? ? ?? ? .
    final int num_array_pref_range_distance_titles;
    final int num_array_pref_range_distance_values;

    Log.v(LOG_TAG, "setDistanceSpinnerAdapter distance");

    // set mile or meter by locale ?? ? ? ? .
    if (mCallback.getPowerContactSettings().getRealDistanceUnits() == Constants.DISTANCE_UNITS_METER) {
        num_array_pref_range_distance_titles = R.array.pref_range_distance_titles_meter;
        num_array_pref_range_distance_values = R.array.pref_range_distance_values_meter;
    } else {/*from  w w w  .j av a2s .  c  o m*/
        num_array_pref_range_distance_titles = R.array.pref_range_distance_titles_mile;
        num_array_pref_range_distance_values = R.array.pref_range_distance_values_mile;
    }

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
            num_array_pref_range_distance_titles, android.R.layout.simple_spinner_item); // R.layout.spinner_item);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    mSpinnerDistance.setAdapter(adapter);
    //  
    mSpinnerDistance.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            double distance = setSpinnerDistanceChanged(position, num_array_pref_range_distance_values); // change distance                 // ?.. ?? ..

            Log.v(LOG_TAG, "mSpinnerDistance/listener : loader restart distace:" + distance + "time"
                    + System.currentTimeMillis());

            mCallback.restartMainLoader(distance); // restart main loader  // ? .. ? ?   ?.    ? ?  ?.
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    String[] strArray = getResources().getStringArray(num_array_pref_range_distance_values);

    Double distance = getDistance(); // ?  .

    Log.v(LOG_TAG, "setDistanceSpinnerAdapter distance setSection" + distance);
    int i;
    for (i = 0; i < strArray.length; i++)
        if (Double.parseDouble(strArray[i]) == distance) {
            mSpinnerDistance.setSelection(i); // 2016.3.31 .
            // setSpinnerDistanceChanged(i, num_array_pref_range_distance_values); // change distance
            break;
        }

    adapter.notifyDataSetChanged(); // http://stackoverflow.com/questions/9443370/how-to-update-an-spinner-dynamically-in-android-correctly

}

From source file:org.uguess.android.sysinfo.SiragonManager.java

void refresh() {
    ArrayAdapter<PrefItem> adapter = (ArrayAdapter<PrefItem>) getListAdapter();

    adapter.setNotifyOnChange(false);//from w ww  .  j a v a 2 s  . c  om
    adapter.clear();

    for (Entry<String, PrefItem> ent : prefs.entrySet()) {
        adapter.add(ent.getValue());
    }

    adapter.notifyDataSetChanged();
}

From source file:com.gimranov.zandy.app.AttachmentActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    final String attachmentKey = b.getString("attachmentKey");
    final String itemKey = b.getString("itemKey");
    final String content = b.getString("content");
    final String mode = b.getString("mode");
    AlertDialog dialog;/*from  w w  w  . java  2 s . com*/
    switch (id) {
    case DIALOG_CONFIRM_NAVIGATE:
        dialog = new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.view_online_warning))
                .setPositiveButton(getResources().getString(R.string.view),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // The behavior for invalid URIs might be nasty, but
                                // we'll cross that bridge if we come to it.
                                try {
                                    Uri uri = Uri.parse(content);
                                    startActivity(new Intent(Intent.ACTION_VIEW).setData(uri));
                                } catch (ActivityNotFoundException e) {
                                    // There can be exceptions here; not sure what would prompt us to have
                                    // URIs that the browser can't load, but it apparently happens.
                                    Toast.makeText(getApplicationContext(), getResources()
                                            .getString(R.string.attachment_intent_failed_for_uri, content),
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                .setNeutralButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // do nothing
                            }
                        })
                .create();
        return dialog;
    case DIALOG_CONFIRM_DELETE:
        dialog = new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.attachment_delete_confirm))
                .setPositiveButton(getResources().getString(R.string.menu_delete),
                        new DialogInterface.OnClickListener() {
                            @SuppressWarnings("unchecked")
                            public void onClick(DialogInterface dialog, int whichButton) {
                                Attachment a = Attachment.load(attachmentKey, db);
                                a.delete(db);
                                ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
                                la.clear();
                                for (Attachment at : Attachment.forItem(Item.load(itemKey, db), db)) {
                                    la.add(at);
                                }
                            }
                        })
                .setNegativeButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // do nothing
                            }
                        })
                .create();
        return dialog;
    case DIALOG_NOTE:
        final EditText input = new EditText(this);
        input.setText(content, BufferType.EDITABLE);

        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.note)).setView(input).setPositiveButton(
                        getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                            @SuppressWarnings("unchecked")
                            public void onClick(DialogInterface dialog, int whichButton) {
                                Editable value = input.getText();
                                String fixed = value.toString().replaceAll("\n\n", "\n<br>");
                                if (mode != null && mode.equals("new")) {
                                    Log.d(TAG, "Attachment created with parent key: " + itemKey);
                                    Attachment att = new Attachment(getBaseContext(), "note", itemKey);
                                    att.setNoteText(fixed);
                                    att.dirty = APIRequest.API_NEW;
                                    att.save(db);
                                } else {
                                    Attachment att = Attachment.load(attachmentKey, db);
                                    att.setNoteText(fixed);
                                    att.dirty = APIRequest.API_DIRTY;
                                    att.save(db);
                                }
                                ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
                                la.clear();
                                for (Attachment a : Attachment.forItem(Item.load(itemKey, db), db)) {
                                    la.add(a);
                                }
                                la.notifyDataSetChanged();
                            }
                        })
                .setNeutralButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // do nothing
                            }
                        });
        // We only want the delete option when this isn't a new note
        if (mode == null || !"new".equals(mode)) {
            builder = builder.setNegativeButton(getResources().getString(R.string.menu_delete),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            Bundle b = new Bundle();
                            b.putString("attachmentKey", attachmentKey);
                            b.putString("itemKey", itemKey);
                            removeDialog(DIALOG_CONFIRM_DELETE);
                            AttachmentActivity.this.b = b;
                            showDialog(DIALOG_CONFIRM_DELETE);
                        }
                    });
        }
        dialog = builder.create();
        return dialog;
    case DIALOG_FILE_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog
                .setMessage(getResources().getString(R.string.attachment_downloading, b.getString("title")));
        mProgressDialog.setIndeterminate(true);
        return mProgressDialog;
    default:
        Log.e(TAG, "Invalid dialog requested");
        return null;
    }
}

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

private void showAddQuickSearchDialog(final List<QuickSearch> list, final ArrayAdapter<QuickSearch> adapter,
        final ListView listView, final TextView tip) {
    Context context = getContext2();
    final ListUrlBuilder urlBuilder = mUrlBuilder;
    if (null == context || null == urlBuilder) {
        return;//  w w w . ja v a2 s.  co  m
    }

    // Can't add image search as quick search
    if (ListUrlBuilder.MODE_IMAGE_SEARCH == urlBuilder.getMode()) {
        showTip(R.string.image_search_not_quick_search, LENGTH_SHORT);
        return;
    }

    // Check duplicate
    for (QuickSearch q : list) {
        if (urlBuilder.equalsQuickSearch(q)) {
            showTip(getString(R.string.duplicate_quick_search, q.name), LENGTH_SHORT);
            return;
        }
    }

    final EditTextDialogBuilder builder = new EditTextDialogBuilder(context,
            getSuitableTitleForUrlBuilder(context.getResources(), urlBuilder, false),
            getString(R.string.quick_search));
    builder.setTitle(R.string.add_quick_search_dialog_title);
    builder.setPositiveButton(android.R.string.ok, null);
    final AlertDialog dialog = builder.show();
    dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String text = builder.getText().trim();

            // Check name empty
            if (TextUtils.isEmpty(text)) {
                builder.setError(getString(R.string.name_is_empty));
                return;
            }

            // Check name duplicate
            for (QuickSearch q : list) {
                if (text.equals(q.name)) {
                    builder.setError(getString(R.string.duplicate_name));
                    return;
                }
            }

            builder.setError(null);
            dialog.dismiss();
            QuickSearch quickSearch = urlBuilder.toQuickSearch();
            quickSearch.name = text;
            EhDB.insertQuickSearch(quickSearch);
            list.add(quickSearch);
            adapter.notifyDataSetChanged();

            if (0 == list.size()) {
                tip.setVisibility(View.VISIBLE);
                listView.setVisibility(View.GONE);
            } else {
                tip.setVisibility(View.GONE);
                listView.setVisibility(View.VISIBLE);
            }
        }
    });
}

From source file:com.rvl.android.getnzb.LocalNZB.java

public void listLocalFiles() {

    Log.d(Tags.LOG, "- localnzb.listLocalFiles()");
    setContentView(R.layout.localnzb);// www . ja v  a2s .c  o  m
    SharedPreferences prefs = GetNZB.preferences;
    String preferredMethod = prefs.getString("preferredUploadMethod", "");
    TextView statusbar = (TextView) findViewById(R.id.hellaStatus);
    statusbar.setText("Local files. Click to upload to " + preferredMethod + ", long click for options:");
    Log.d(Tags.LOG, "Opening database.");
    Log.d(Tags.LOG, "Files dir: " + getFilesDir());
    LocalNZBMetadata.openDatabase();
    Cursor cur;

    // -- Bind the itemlist to the itemarray with the arrayadapter
    ArrayList<String> items = new ArrayList<String>();
    ArrayAdapter<String> localFilesArrayAdapter = new LocalNZBRowAdapter(this, items);

    ListView localFilesListView = (ListView) findViewById(R.id.localFileList);
    localFilesListView.setCacheColorHint(00000000);
    localFilesListView.setAdapter(localFilesArrayAdapter);

    registerForContextMenu(localFilesListView);

    localFilesListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
            String localFilesArray[] = fileList();
            SharedPreferences prefs = GetNZB.preferences;
            String preferredMethod = prefs.getString("preferredUploadMethod", "");

            if (preferredMethod.equals("HellaNZB")) {
                Log.d(Tags.LOG, "itemclik(): uploading with HellaNZB.");
                uploadLocalFileHellaNZB(localFilesArray[position]);
                return;
            }
            if (preferredMethod.equals("FTP")) {
                Log.d(Tags.LOG, "itemclick(): uploading with FTP.");
                uploadLocalFileFTP(localFilesArray[position]);
                return;
            }

        }
    });

    // Retrieve files from disc, retrieve metadata from DB,
    // combine this data and send it to the arrayadapter.
    Log.d(Tags.LOG, "Retrieving file metadata and building LocalNZB list.");
    String age = "";
    String size = "";
    String category = "";
    String fileinfo = "";
    String localFilesArray[] = fileList();
    for (int c = 0; c < localFilesArray.length; c++) {
        cur = LocalNZBMetadata.myDatabase.query("file", new String[] { "_id", "name" },
                "name = '" + localFilesArray[c] + "'", null, null, null, null);
        if (cur.moveToFirst()) {
            //if there is a hit, retrieve metadata
            int idIndex = cur.getColumnIndex("_id");
            int file_id = cur.getInt(idIndex);

            cur = LocalNZBMetadata.myDatabase.query("meta", new String[] { "age", "size", "category" },
                    "file_id ='" + file_id + "'", null, null, null, null);

            if (cur.moveToFirst()) {
                int ageIndex = cur.getColumnIndex("age");
                int sizeIndex = cur.getColumnIndex("size");
                int catIndex = cur.getColumnIndex("category");
                age = cur.getString(ageIndex);
                size = cur.getString(sizeIndex);
                category = cur.getString(catIndex);
            } else {
                // If there is no metadata for file set dummy metadata info.
                age = "???";
                size = "???";
                category = "???";
            }
        } else {
            // If there is no file info in database set dummy info.
            age = "???";
            size = "???";
            category = "???";
        }
        fileinfo = age + "#" + size + "#" + localFilesArray[c] + "#" + category;
        items.add(fileinfo);
    }
    Log.d(Tags.LOG, "Number of files in list: " + localFilesArray.length);
    localFilesArrayAdapter.notifyDataSetChanged();
    LocalNZBMetadata.close();
}

From source file:com.owncloud.android.ui.adapter.FileListListAdapter.java

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;/*from ww w.  j a v  a2 s  . co m*/
    if (view == null) {
        LayoutInflater inflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflator.inflate(R.layout.list_item, null);
    }

    if (mFiles != null && mFiles.size() > position) {
        OCFile file = mFiles.get(position);
        TextView fileName = (TextView) view.findViewById(R.id.Filename);
        String name = file.getFileName();
        if (dataSourceShareFile == null)
            dataSourceShareFile = new DbShareFile(mContext);

        Account account = AccountUtils.getCurrentOwnCloudAccount(mContext);
        String[] accountNames = account.name.split("@");

        if (accountNames.length > 2) {
            accountName = accountNames[0] + "@" + accountNames[1];
            url = accountNames[2];
        }
        Map<String, String> fileSharers = dataSourceShareFile.getUsersWhoSharedFilesWithMe(accountName);
        TextView sharer = (TextView) view.findViewById(R.id.sharer);
        ImageView shareButton = (ImageView) view.findViewById(R.id.shareItem);
        fileName.setText(name);
        ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);
        fileIcon.setImageResource(DisplayUtils.getResourceId(file.getMimetype()));
        ImageView localStateView = (ImageView) view.findViewById(R.id.imageView2);
        FileDownloaderBinder downloaderBinder = mTransferServiceGetter.getFileDownloaderBinder();
        FileUploaderBinder uploaderBinder = mTransferServiceGetter.getFileUploaderBinder();
        if (fileSharers.size() != 0 && (!file.equals("Shared") && file.getRemotePath().contains("Shared"))) {
            if (fileSharers.containsKey(name)) {
                sharer.setText(fileSharers.get(name));
                fileSharers.remove(name);
            } else {
                sharer.setText(" ");
            }
        } else {
            sharer.setText(" ");
        }

        if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file)) {
            localStateView.setImageResource(R.drawable.downloading_file_indicator);
            localStateView.setVisibility(View.VISIBLE);
        } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file)) {
            localStateView.setImageResource(R.drawable.uploading_file_indicator);
            localStateView.setVisibility(View.VISIBLE);
        } else if (file.isDown()) {
            localStateView.setImageResource(R.drawable.local_file_indicator);
            localStateView.setVisibility(View.VISIBLE);
        } else {
            localStateView.setVisibility(View.INVISIBLE);
        }

        TextView fileSizeV = (TextView) view.findViewById(R.id.file_size);
        TextView lastModV = (TextView) view.findViewById(R.id.last_mod);
        ImageView checkBoxV = (ImageView) view.findViewById(R.id.custom_checkbox);
        shareButton.setOnClickListener(new OnClickListener() {
            String shareStatusDisplay;
            int flagShare = 0;

            @Override
            public void onClick(View v) {
                final Dialog dialog = new Dialog(mContext);
                final OCFile fileToBeShared = (OCFile) getItem(position);
                final ArrayAdapter<String> shareWithFriends;
                final ArrayAdapter<String> shareAdapter;
                final String filePath;
                sharedWith = new ArrayList<String>();
                dataSource = new DbFriends(mContext);
                dataSourceShareFile = new DbShareFile(mContext);
                dialog.setContentView(R.layout.share_file_with);
                dialog.setTitle("Share");
                Account account = AccountUtils.getCurrentOwnCloudAccount(mContext);
                String[] accountNames = account.name.split("@");

                if (accountNames.length > 2) {
                    accountName = accountNames[0] + "@" + accountNames[1];
                    url = accountNames[2];
                }

                final AutoCompleteTextView textView = (AutoCompleteTextView) dialog
                        .findViewById(R.id.autocompleteshare);
                Button shareBtn = (Button) dialog.findViewById(R.id.ShareBtn);
                Button doneBtn = (Button) dialog.findViewById(R.id.ShareDoneBtn);
                final ListView listview = (ListView) dialog.findViewById(R.id.alreadySharedWithList);

                textView.setThreshold(2);
                final String itemType;

                filePath = "files" + String.valueOf(fileToBeShared.getRemotePath());
                final String fileName = fileToBeShared.getFileName();
                final String fileRemotePath = fileToBeShared.getRemotePath();
                if (dataSourceShareFile == null)
                    dataSourceShareFile = new DbShareFile(mContext);
                sharedWith = dataSourceShareFile.getUsersWithWhomIhaveSharedFile(fileName, fileRemotePath,
                        accountName, String.valueOf(1));
                shareAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1,
                        sharedWith);
                listview.setAdapter(shareAdapter);
                final String itemSource;
                if (fileToBeShared.isDirectory()) {
                    itemType = "folder";
                    int lastSlashInFolderPath = filePath.lastIndexOf('/');
                    itemSource = filePath.substring(0, lastSlashInFolderPath);
                } else {
                    itemType = "file";
                    itemSource = filePath;
                }

                //Permissions disabled with friends app
                ArrayList<String> friendList = dataSource.getFriendList(accountName);
                dataSource.close();
                shareWithFriends = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1,
                        friendList);
                textView.setAdapter(shareWithFriends);
                textView.setFocusableInTouchMode(true);
                dialog.show();
                textView.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

                    }
                });
                final Handler finishedHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        shareAdapter.notifyDataSetChanged();
                        Toast.makeText(mContext, shareStatusDisplay, Toast.LENGTH_SHORT).show();

                    }
                };
                shareBtn.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        final String shareWith = textView.getText().toString();

                        if (shareWith.equals("")) {
                            textView.setHint("Share With");
                            Toast.makeText(mContext,
                                    "Please enter the friends name with whom you want to share",
                                    Toast.LENGTH_SHORT).show();
                        } else if (sharedWith.contains(shareWith)) {
                            textView.setHint("Share With");
                            Toast.makeText(mContext, "You have shared the file with that person",
                                    Toast.LENGTH_SHORT).show();
                        } else {

                            textView.setText("");
                            Runnable runnable = new Runnable() {
                                @Override
                                public void run() {
                                    HttpPost post = new HttpPost(
                                            "http://" + url + "/owncloud/androidshare.php");
                                    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

                                    params.add(new BasicNameValuePair("itemType", itemType));
                                    params.add(new BasicNameValuePair("itemSource", itemSource));
                                    params.add(new BasicNameValuePair("shareType", shareType));
                                    params.add(new BasicNameValuePair("shareWith", shareWith));
                                    params.add(new BasicNameValuePair("permission", permissions));
                                    params.add(new BasicNameValuePair("uidOwner", accountName));
                                    HttpEntity entity;
                                    String shareSuccess = "false";
                                    try {
                                        entity = new UrlEncodedFormEntity(params, "utf-8");
                                        HttpClient client = new DefaultHttpClient();
                                        post.setEntity(entity);
                                        HttpResponse response = client.execute(post);

                                        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                                            HttpEntity entityresponse = response.getEntity();
                                            String jsonentity = EntityUtils.toString(entityresponse);
                                            JSONObject obj = new JSONObject(jsonentity);
                                            shareSuccess = obj.getString("SHARE_STATUS");
                                            flagShare = 1;
                                            if (shareSuccess.equals("true")) {
                                                dataSourceShareFile.putNewShares(fileName, fileRemotePath,
                                                        accountName, shareWith);
                                                sharedWith.add(shareWith);
                                                shareStatusDisplay = "File share succeeded";
                                            } else if (shareSuccess.equals("INVALID_FILE")) {
                                                shareStatusDisplay = "File you are trying to share does not exist";
                                            } else if (shareSuccess.equals("INVALID_SHARETYPE")) {
                                                shareStatusDisplay = "File Share type is invalid";
                                            } else {
                                                shareStatusDisplay = "Share did not succeed. Please check your internet connection";
                                            }

                                            finishedHandler.sendEmptyMessage(flagShare);

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

                                }
                            };
                            new Thread(runnable).start();

                        }

                        if (flagShare == 1) {
                        }

                    }

                });
                doneBtn.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        //dataSourceShareFile.close();
                    }
                });
            }

        });
        //dataSourceShareFile.close();
        if (!file.isDirectory()) {
            fileSizeV.setVisibility(View.VISIBLE);
            fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
            lastModV.setVisibility(View.VISIBLE);
            lastModV.setText(DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp()));
            // this if-else is needed even thoe fav icon is visible by default
            // because android reuses views in listview
            if (!file.keepInSync()) {
                view.findViewById(R.id.imageView3).setVisibility(View.GONE);
            } else {
                view.findViewById(R.id.imageView3).setVisibility(View.VISIBLE);
            }

            ListView parentList = (ListView) parent;
            if (parentList.getChoiceMode() == ListView.CHOICE_MODE_NONE) {
                checkBoxV.setVisibility(View.GONE);
            } else {
                if (parentList.isItemChecked(position)) {
                    checkBoxV.setImageResource(android.R.drawable.checkbox_on_background);
                } else {
                    checkBoxV.setImageResource(android.R.drawable.checkbox_off_background);
                }
                checkBoxV.setVisibility(View.VISIBLE);
            }

        } else {

            fileSizeV.setVisibility(View.VISIBLE);
            fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
            lastModV.setVisibility(View.VISIBLE);
            lastModV.setText(DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp()));
            checkBoxV.setVisibility(View.GONE);
            view.findViewById(R.id.imageView3).setVisibility(View.GONE);
        }
    }

    return view;
}

From source file:com.xrmaddness.offthegrid.ListActivity.java

public void view_contacts() {
    ListView listview = (ListView) findViewById(R.id.contact_list);
    ArrayAdapter<Spanned> contacts_adapter;
    ArrayList<Spanned> contacts_list;
    contacts_list = new ArrayList<Spanned>();

    final List<contact> contacts = db.contact_get_all();

    contacts_list.clear();/*  w  w  w  .  j a v  a  2 s  . co m*/

    for (int i = 0; i < contacts.size(); i++) {
        long time_lastact;
        Date lastact;
        Spanned view_span;
        contact contact = contacts.get(i);
        String view_html;
        long unread = 0;

        time_lastact = contact.time_lastact_get() * 1000;
        lastact = new java.util.Date(time_lastact);
        SimpleDateFormat dateformat = new SimpleDateFormat();

        String name_start = "";
        String name_end = "";

        if (contact.time_lastact_get() > contact.unread_get()) {
            name_start = "<b>";
            name_end = "</b>";

            unread = db.message_get_count_by_id(contact.id_get(), contact.unread_get());
        }

        view_html = "<font ";
        if (contact.type_get() == contact.TYPE_PERSON) {
            Log.d("list", "person");
            switch (contact.keystat_get()) {
            case com.xrmaddness.offthegrid.contact.KEYSTAT_NONE:
                Log.d("list", "keystat none");
                view_html += "color='#990000'";
                break;
            case com.xrmaddness.offthegrid.contact.KEYSTAT_RECEIVED:
                Log.d("list", "keystat received");
                view_html += "color='#cc6600'";
                break;
            case com.xrmaddness.offthegrid.contact.KEYSTAT_VERIFIED:
                Log.d("list", "keystat verified");
                view_html += "color='#004400'";
                break;
            }
        }
        view_html += ">";
        view_html += name_start + contact.name_get() + name_end + "<br><small>";
        if (contact.type_get() == contact.TYPE_GROUP) {
            String owner = contact.address_get();
            List<String> members = contact.members_get();

            for (int j = 0; j < members.size(); j++) {
                String member = members.get(j);
                if (member.equals(owner)) {
                    view_html += "<i>" + member + "</i> ";

                } else {
                    view_html += member + " ";
                }
            }
        } else {
            view_html += "<i>" + contact.address_get() + "</i> ";
        }
        view_html += "<br>";
        view_html += dateformat.format(lastact);
        view_html += "</small></font>";

        /* add number of unread messages */
        if (unread > 0) {
            view_html += "<small><font color='#00cc00'> (" + unread + ")</font></small>";
        }

        view_span = Html.fromHtml(view_html);

        contacts_list.add(view_span);
    }

    contacts_adapter = new ArrayAdapter<Spanned>(this, android.R.layout.simple_list_item_1, contacts_list);

    listview.setAdapter(contacts_adapter);

    contacts_adapter.notifyDataSetChanged();
    listview.setAdapter(contacts_adapter);

    listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
            final contact c = contacts.get(position);

            if (c.type_get() == contact.TYPE_GROUP) {
                contact_view(c);
            }
            if (c.type_get() == contact.TYPE_PERSON) {
                switch (c.keystat_get()) {
                case contact.KEYSTAT_NONE: {
                    Log.d("contact", "ask action");
                    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                    CharSequence[] items = { getString(R.string.action_send_key),
                            getString(R.string.action_remove) };
                    builder.setTitle(R.string.dialog_contact).setItems(items,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    Log.d("contact", "which: " + which);
                                    if (which == 0) {
                                        Log.d("contact", "send_key_dialg(c)");
                                        send_key_dialog(c);
                                    }
                                    if (which == 1) {
                                        Log.d("contact", "remove(c)");
                                        remove(c);
                                    }
                                }
                            });
                    builder.show();
                    break;
                }
                case contact.KEYSTAT_RECEIVED: {
                    Log.d("contact", "ask action");
                    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                    CharSequence[] items = { getString(R.string.action_verify),
                            getString(R.string.action_send_key), getString(R.string.action_remove) };
                    builder.setTitle(R.string.dialog_contact).setItems(items,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    Log.d("contact", "which: " + which);
                                    if (which == 0) {
                                        Log.d("contact", "verify_dialog(c)");
                                        verify_dialog(c);
                                    }
                                    if (which == 1) {
                                        Log.d("contact", "send_key_dialg(c)");
                                        send_key_dialog(c);
                                    }
                                    if (which == 2) {
                                        Log.d("contact", "remove(c)");
                                        remove(c);
                                    }
                                }
                            });
                    builder.show();
                    break;
                }
                case contact.KEYSTAT_VERIFIED: {
                    contact_view(c);

                }
                }
            }
        }
    });

    listview.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long id) {
            final contact c = contacts.get(position);

            if (c.type_get() == contact.TYPE_GROUP) {
                Log.d("contact", "ask action");
                AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                CharSequence[] items = { getString(R.string.action_set_member),
                        getString(R.string.action_set_name), getString(R.string.action_remove) };
                builder.setTitle(R.string.dialog_contact).setItems(items,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Log.d("contact", "which: " + which);
                                if (which == 0) {
                                    Log.d("group", "set member");
                                    set_member_dialog(c);
                                }
                                if (which == 1) {
                                    Log.d("group", "set name");
                                    group_name_dialog(c);
                                }
                                if (which == 2) {
                                    Log.d("group", "remove(c)");
                                    remove(c);
                                }
                            }
                        });
                builder.show();
                return true;

            }
            if (c.type_get() == contact.TYPE_PERSON) {
                switch (c.keystat_get()) {
                case contact.KEYSTAT_VERIFIED: {
                    Log.d("contact", "ask action");
                    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                    CharSequence[] items = { getString(R.string.action_send_key),
                            getString(R.string.action_fingerprint), getString(R.string.action_remove) };
                    builder.setTitle(R.string.dialog_contact).setItems(items,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    Log.d("contact", "which: " + which);
                                    if (which == 0) {
                                        Log.d("contact", "send_key_dialg(c)");
                                        send_key_dialog(c);
                                    }
                                    if (which == 1) {
                                        view_fingerprint_dialog(c);
                                    }
                                    if (which == 2) {
                                        Log.d("contact", "remove(c)");
                                        remove(c);
                                    }
                                }
                            });
                    builder.show();
                    return true;
                }
                }
            }
            return false;
        }
    });

}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void editDontWantToSee() {
    if (!SettingConstants.UPDATING_FILTER) {
        Set<String> currentExclusions = PrefUtils.getStringSetValue(R.string.I_DONT_WANT_TO_SEE_ENTRIES, null);

        final ArrayList<ExclusionEdit> mCurrentExclusionList = new ArrayList<TvBrowser.ExclusionEdit>();

        if (currentExclusions != null && !currentExclusions.isEmpty()) {
            for (String exclusion : currentExclusions) {
                mCurrentExclusionList.add(new ExclusionEdit(exclusion));
            }//ww w .  j  ava2s .  co m
        }

        Collections.sort(mCurrentExclusionList);

        final ArrayAdapter<ExclusionEdit> exclusionAdapter = new ArrayAdapter<TvBrowser.ExclusionEdit>(
                TvBrowser.this, android.R.layout.simple_list_item_1, mCurrentExclusionList);

        View view = getLayoutInflater().inflate(R.layout.dont_want_to_see_exclusion_edit_list,
                getParentViewGroup(), false);

        ListView list = (ListView) view.findViewById(R.id.dont_want_to_see_exclusion_list);

        list.setAdapter(exclusionAdapter);

        final Runnable cancel = new Runnable() {
            @Override
            public void run() {
            }
        };

        AdapterView.OnItemClickListener onClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final ExclusionEdit edit = exclusionAdapter.getItem(position);

                View editView = getLayoutInflater().inflate(R.layout.dont_want_to_see_edit,
                        getParentViewGroup(), false);

                final TextView exclusion = (TextView) editView.findViewById(R.id.dont_want_to_see_value);
                final CheckBox caseSensitive = (CheckBox) editView
                        .findViewById(R.id.dont_want_to_see_case_sensitve);

                exclusion.setText(edit.mExclusion);
                caseSensitive.setSelected(edit.mIsCaseSensitive);

                Runnable editPositive = new Runnable() {
                    @Override
                    public void run() {
                        if (exclusion.getText().toString().trim().length() > 0) {
                            edit.mExclusion = exclusion.getText().toString();
                            edit.mIsCaseSensitive = caseSensitive.isSelected();

                            exclusionAdapter.notifyDataSetChanged();
                        }
                    }
                };

                showAlertDialog(getString(R.string.action_dont_want_to_see), null, editView, null, editPositive,
                        null, cancel, false, false);
            }
        };

        list.setOnItemClickListener(onClickListener);
        list.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
                getMenuInflater().inflate(R.menu.don_want_to_see_context, menu);

                MenuItem item = menu.findItem(R.id.dont_want_to_see_delete);

                item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        ExclusionEdit edit = exclusionAdapter
                                .getItem(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position);
                        exclusionAdapter.remove(edit);
                        exclusionAdapter.notifyDataSetChanged();

                        return true;
                    }
                });
            }
        });

        Thread positive = new Thread() {
            @Override
            public void run() {
                SettingConstants.UPDATING_FILTER = true;

                final NotificationCompat.Builder builder = new NotificationCompat.Builder(TvBrowser.this);
                builder.setSmallIcon(R.drawable.ic_stat_notify);
                builder.setOngoing(true);
                builder.setContentTitle(getResources().getText(R.string.action_dont_want_to_see));
                builder.setContentText(
                        getResources().getText(R.string.dont_want_to_see_refresh_notification_text));

                final int notifyID = 2;

                final NotificationManager notification = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                notification.notify(notifyID, builder.build());

                updateProgressIcon(true);

                HashSet<String> newExclusions = new HashSet<String>();
                final ArrayList<DontWantToSeeExclusion> exclusionList = new ArrayList<DontWantToSeeExclusion>();

                for (ExclusionEdit edit : mCurrentExclusionList) {
                    String exclusion = edit.getExclusion();

                    newExclusions.add(exclusion);
                    exclusionList.add(new DontWantToSeeExclusion(exclusion));
                }

                new Thread() {
                    public void run() {
                        Cursor programs = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_DATA,
                                new String[] { TvBrowserContentProvider.KEY_ID,
                                        TvBrowserContentProvider.DATA_KEY_TITLE },
                                null, null, TvBrowserContentProvider.KEY_ID);
                        programs.moveToPosition(-1);

                        builder.setProgress(programs.getCount(), 0, true);
                        notification.notify(notifyID, builder.build());

                        ArrayList<ContentProviderOperation> updateValuesList = new ArrayList<ContentProviderOperation>();

                        int keyColumn = programs.getColumnIndex(TvBrowserContentProvider.KEY_ID);
                        int titleColumn = programs.getColumnIndex(TvBrowserContentProvider.DATA_KEY_TITLE);

                        DontWantToSeeExclusion[] exclusionArr = exclusionList
                                .toArray(new DontWantToSeeExclusion[exclusionList.size()]);

                        while (programs.moveToNext()) {
                            builder.setProgress(programs.getCount(), programs.getPosition(), false);
                            notification.notify(notifyID, builder.build());

                            String title = programs.getString(titleColumn);

                            boolean filter = UiUtils.filter(getApplicationContext(), title, exclusionArr);
                            long progID = programs.getLong(keyColumn);

                            ContentValues values = new ContentValues();
                            values.put(TvBrowserContentProvider.DATA_KEY_DONT_WANT_TO_SEE, filter ? 1 : 0);

                            ContentProviderOperation.Builder opBuilder = ContentProviderOperation.newUpdate(
                                    ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_DATA_UPDATE,
                                            progID));
                            opBuilder.withValues(values);

                            updateValuesList.add(opBuilder.build());
                        }

                        notification.cancel(notifyID);

                        programs.close();

                        if (!updateValuesList.isEmpty()) {
                            try {
                                getContentResolver().applyBatch(TvBrowserContentProvider.AUTHORITY,
                                        updateValuesList);
                                UiUtils.sendDontWantToSeeChangedBroadcast(getApplicationContext(), true);
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(),
                                                R.string.dont_want_to_see_sync_success, Toast.LENGTH_LONG)
                                                .show();
                                    }
                                });
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            } catch (OperationApplicationException e) {
                                e.printStackTrace();
                            }
                        }

                        updateProgressIcon(false);
                        SettingConstants.UPDATING_FILTER = false;
                    }
                }.start();

                Editor edit = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
                edit.putStringSet(getString(R.string.I_DONT_WANT_TO_SEE_ENTRIES), newExclusions);
                edit.commit();
            }
        };

        showAlertDialog(getString(R.string.action_dont_want_to_see_edit), null, view, null, positive, null,
                cancel, false, true);
    }
}