Example usage for android.widget ListView setAdapter

List of usage examples for android.widget ListView setAdapter

Introduction

In this page you can find the example usage for android.widget ListView setAdapter.

Prototype

@Override
public void setAdapter(ListAdapter adapter) 

Source Link

Document

Sets the data behind this ListView.

Usage

From source file:com.entertailion.android.launcher.Dialogs.java

/**
 * Change the order of the favorite rows.
 * /*ww w . j  a  v a2  s  .  c o  m*/
 * @param context
 */
public static void displayChangeRowOrder(final Launcher context) {
    final Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.row_list);

    final ListView listView = (ListView) dialog.findViewById(R.id.rowList);
    ArrayList<RowInfo> persistedRows = RowsTable.getRows(context);
    final ArrayList<RowInfo> rows = new ArrayList<RowInfo>();
    // Add in reverse order to match favorite rows order
    for (RowInfo rowInfo : persistedRows) {
        rows.add(0, rowInfo);
    }
    final RowAdapter rowAdapter = new RowAdapter(context, rows);
    listView.setAdapter(rowAdapter);
    listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            RowInfo rowInfo = (RowInfo) parent.getAdapter().getItem(position);
            if (rowInfo.isSelected()) {
                rowInfo.setSelected(false);

                // Persist the new row order
                try {
                    int counter = 0;
                    for (int i = rowAdapter.getCount() - 1; i >= 0; i--) {
                        RowInfo currentRowInfo = (RowInfo) parent.getAdapter().getItem(i);
                        RowsTable.updateRow(context, currentRowInfo.getId(), currentRowInfo.getTitle(), counter,
                                currentRowInfo.getType());
                        counter++;
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG, "displayChangeRowOrder", e);
                }
                Analytics.logEvent(Analytics.CHANGE_ROW_ORDER);
            } else {
                rowInfo.setSelected(true);
            }
            rowAdapter.notifyDataSetChanged();
        }

    });
    listView.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            // Swap the selected item in the list
            int selectedRowIndex = -1;
            for (int i = 0; i < rows.size(); i++) {
                RowInfo rowInfo = rows.get(i);
                if (rowInfo.isSelected()) {
                    selectedRowIndex = i;
                    break;
                }
            }
            if (selectedRowIndex != -1) {
                try {
                    Collections.swap(rows, position, selectedRowIndex);
                    rowAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    Log.e(LOG_TAG, "displayChangeRowOrder", e);
                }
            }
        }

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

    });
    listView.setDrawingCacheEnabled(true);
    listView.setOnKeyListener(onKeyListener);
    dialog.setOnDismissListener(new OnDismissListener() {

        @Override
        public void onDismiss(DialogInterface dialog) {
            context.showCover(false);
            context.reloadAllGalleries();
        }

    });
    Button okButton = (Button) dialog.findViewById(R.id.okButton);
    okButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            context.showCover(false);
            dialog.dismiss();
            context.reloadAllGalleries();
        }

    });
    context.showCover(true);
    dialog.show();
    Analytics.logEvent(Analytics.DIALOG_CHANGE_ROW_ORDER);
}

From source file:com.entertailion.android.launcher.Dialogs.java

/**
 * Display dialog to the user for the browser bookmarks. Allow the user to add a
 * browser bookmark to an existing row or a new row.
 * /*from  w w w  .ja va 2 s.com*/
 * @param context
 */
public static void displayAddBrowserBookmark(final Launcher context) {
    final Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.add_browser_bookmarks_list);

    final EditText nameEditText = (EditText) dialog.findViewById(R.id.rowName);
    final RadioButton currentRadioButton = (RadioButton) dialog.findViewById(R.id.currentRadio);
    currentRadioButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // hide the row name edit field if the current row radio button
            // is selected
            nameEditText.setVisibility(View.GONE);
        }

    });
    final RadioButton newRadioButton = (RadioButton) dialog.findViewById(R.id.newRadio);
    newRadioButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // show the row name edit field if the new radio button is
            // selected
            nameEditText.setVisibility(View.VISIBLE);
            nameEditText.requestFocus();
        }

    });

    ListView listView = (ListView) dialog.findViewById(R.id.list);
    final ArrayList<BookmarkInfo> bookmarks = loadBookmarks(context);
    Collections.sort(bookmarks, new Comparator<BookmarkInfo>() {

        @Override
        public int compare(BookmarkInfo lhs, BookmarkInfo rhs) {
            return lhs.getTitle().toLowerCase().compareTo(rhs.getTitle().toLowerCase());
        }

    });
    listView.setAdapter(new BookmarkAdapter(context, bookmarks));
    listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(final AdapterView<?> parent, final View view, final int position,
                final long id) {
            // run in thread since network logic needed to get bookmark icon
            new Thread(new Runnable() {
                public void run() {
                    // if the new row radio button is selected, the user must enter
                    // a name for the new row
                    String name = nameEditText.getText().toString().trim();
                    if (newRadioButton.isChecked() && name.length() == 0) {
                        nameEditText.requestFocus();
                        displayAlert(context, context.getString(R.string.dialog_new_row_name_alert));
                        return;
                    }
                    boolean currentRow = !newRadioButton.isChecked();
                    try {
                        BookmarkInfo bookmark = (BookmarkInfo) parent.getAdapter().getItem(position);
                        int rowId = 0;
                        int rowPosition = 0;
                        if (currentRow) {
                            rowId = context.getCurrentGalleryId();
                            ArrayList<ItemInfo> items = ItemsTable.getItems(context, rowId);
                            rowPosition = items.size(); // in last
                            // position
                            // for selected
                            // row
                        } else {
                            rowId = (int) RowsTable.insertRow(context, name, 0, RowInfo.FAVORITE_TYPE);
                            rowPosition = 0;
                        }
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(bookmark.getUrl()));

                        Uri uri = Uri.parse(bookmark.getUrl());
                        Log.d(LOG_TAG, "host=" + uri.getScheme() + "://" + uri.getHost());
                        String icon = Utils.getWebSiteIcon(context, "http://" + uri.getHost());
                        Log.d(LOG_TAG, "icon1=" + icon);
                        if (icon == null) {
                            // try base host address
                            int count = StringUtils.countMatches(uri.getHost(), ".");
                            if (count > 1) {
                                int index = uri.getHost().indexOf('.');
                                String baseHost = uri.getHost().substring(index + 1);
                                icon = Utils.getWebSiteIcon(context, "http://" + baseHost);
                                Log.d(LOG_TAG, "icon2=" + icon);
                            }
                        }

                        ItemsTable.insertItem(context, rowId, rowPosition, bookmark.getTitle(), intent, icon,
                                DatabaseHelper.SHORTCUT_TYPE);
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "displayAddBrowserBookmark", e);
                    }

                    // need to do this on UI thread
                    context.getHandler().post(new Runnable() {
                        public void run() {
                            context.showCover(false);
                            dialog.dismiss();
                            context.reloadAllGalleries();
                        }
                    });

                    if (currentRow) {
                        Analytics.logEvent(Analytics.ADD_BROWSER_BOOKMARK);
                    } else {
                        Analytics.logEvent(Analytics.ADD_BROWSER_BOOKMARK_WITH_ROW);
                    }

                }
            }).start();
        }
    });
    listView.setDrawingCacheEnabled(true);
    listView.setOnKeyListener(onKeyListener);
    dialog.setOnDismissListener(new OnDismissListener() {

        @Override
        public void onDismiss(DialogInterface dialog) {
            context.showCover(false);
        }

    });
    context.showCover(true);
    dialog.show();
    Analytics.logEvent(Analytics.DIALOG_ADD_BROWSER_BOOKMARK);
}

From source file:com.fastbootmobile.encore.app.fragments.WelcomeFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Step specifics
    if (mStep == 2) {
        View root = getView();/*from  www.ja va2 s  . c  om*/
        if (root != null) {
            root.findViewById(R.id.btnSkip).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                    dialog.setTitle(R.string.welcome_skip_dialog_title);
                    dialog.setMessage(R.string.welcome_skip_dialog_body);
                    dialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finishWizard();
                        }
                    });
                    dialog.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                }
            });

            root.findViewById(R.id.btnBrowse).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ProviderDownloadDialog.newInstance(false).show(getFragmentManager(), "Download");
                }
            });
        }
    } else if (mStep == 3) {
        // Step 3: Configure plugins
        ListView lv = (ListView) view.findViewById(R.id.lvProviders);
        List<ProviderConnection> allProvs = PluginsLookup.getDefault().getAvailableProviders();
        final List<ProviderConnection> provs = new ArrayList<>();

        for (ProviderConnection prov : allProvs) {
            if (prov.getConfigurationActivity() != null
                    && !TextUtils.isEmpty(prov.getConfigurationActivity())) {
                provs.add(prov);
            }
        }

        mStep3Adapter = new ProvidersAdapter(provs);
        mStep3Adapter.setWhite(true);
        mStep3Adapter.setWashOutConfigure(true);
        lv.setAdapter(mStep3Adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ProviderConnection connection = provs.get(position);
                Intent intent = new Intent();
                intent.setPackage(connection.getPackage());
                intent.setClassName(connection.getPackage(), connection.getConfigurationActivity());
                mConfiguringProvider = connection;
                try {
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(getActivity(), R.string.toast_retry_plugin_not_ready, Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });
    }
}

From source file:com.buddi.client.dfu.DfuActivity.java

private void openFileChooser() {
    final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType(mFileTypeTmp == DfuService.TYPE_AUTO ? DfuService.MIME_TYPE_ZIP : DfuService.MIME_TYPE_HEX);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        // file browser has been found on the device
        startActivityForResult(intent, SELECT_FILE_REQ);
    } else {//from   w ww.j  a v  a2 s  .c o  m
        // there is no any file browser app, let's try to download one
        final View customView = getLayoutInflater().inflate(R.layout.app_file_browser, null);
        final ListView appsList = (ListView) customView.findViewById(android.R.id.list);
        appsList.setAdapter(new FileBrowserAppsAdapter(this));
        appsList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        appsList.setItemChecked(0, true);
        new AlertDialog.Builder(this).setTitle(R.string.dfu_alert_no_filebrowser_title).setView(customView)
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        final int pos = appsList.getCheckedItemPosition();
                        if (pos >= 0) {
                            final String query = getResources()
                                    .getStringArray(R.array.dfu_app_file_browser_action)[pos];
                            final Intent storeIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(query));
                            startActivity(storeIntent);
                        }
                    }
                }).show();
    }
}

From source file:com.musevisions.android.SudokuSolver.SudokuLoaderActivity.java

private void updateView(JSONArray results) {
    ListView lv = (ListView) findViewById(R.id.listView);

    /* Fill list with all json files */
    ArrayList<PuzzleHolder> list = new ArrayList<PuzzleHolder>();
    for (int i = 0; i < results.length(); i++) {
        try {/*w  ww . j av  a 2  s .  c  o m*/
            JSONObject obj = results.getJSONObject(i);
            JSONArray names = obj.names();
            String name = names.getString(0);
            JSONArray array = obj.getJSONArray(name);
            int puzzle[] = JSONHelper.toIntArray(array);
            if (puzzle != null)
                list.add(new PuzzleHolder(name, puzzle));
            //Log.v(TAG, "File: " + name);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    lv.setAdapter(new ListArrayAdapter(this, list));
}

From source file:com.example.mediasync3.DownloadMusic.java

@Override
protected void onPostExecute(Boolean result) {
    mDialog.dismiss();/*from   w w  w  .j  a v  a 2 s. c  o m*/

    if (pos == -2) {
        Spinner listSpin = (Spinner) rootView.findViewById(R.id.spinner1);
        listSpin.setAdapter(adapterList);
        listSpin.setEnabled(true);

    } else {

        ListView lv = (ListView) rootView.findViewById(R.id.listView1);
        ArrayList<String> dir = new ArrayList<String>();

        //File sdCardRoot = Environment.getExternalStorageDirectory();
        final File MusicDir = new File(LOCAL_MUSIC_DIR);

        for (File f : MusicDir.listFiles()) {
            if (f.isFile())
                dir.add(f.getName());
            // Do your stuff 
        }
        String[] localnames = dir.toArray(new String[dir.size()]);

        ArrayAdapter<String> ad = new ArrayAdapter<String>(mFrag.getActivity(),
                android.R.layout.simple_list_item_1, localnames);
        lv.setAdapter(ad);

        //TextView tv = (TextView) rootView.findViewById(R.id.textView1);
        //tv.setText(fnames[pos]);

        if (result) {

            showToast(mErrorMsg);
        } else {
            // Couldn't download it, so show an error
            showToast(mErrorMsg);
        }
    }
}

From source file:com.cerema.cloud2.ui.fragment.ShareFileFragment.java

private void updateListOfUserGroups() {
    // Update list of users/groups
    // TODO Refactoring: create a new {@link ShareUserListAdapter} instance with every call should not be needed
    mUserGroupsAdapter = new ShareUserListAdapter(getActivity(), R.layout.share_user_item, mPrivateShares,
            this);

    // Show data// w ww .ja v  a 2 s  . co  m
    TextView noShares = (TextView) getView().findViewById(R.id.shareNoUsers);
    ListView usersList = (ListView) getView().findViewById(R.id.shareUsersList);

    if (mPrivateShares.size() > 0) {
        noShares.setVisibility(View.GONE);
        usersList.setVisibility(View.VISIBLE);
        usersList.setAdapter(mUserGroupsAdapter);
        setListViewHeightBasedOnChildren(usersList);
    } else {
        noShares.setVisibility(View.VISIBLE);
        usersList.setVisibility(View.GONE);
    }

    // Set Scroll to initial position
    ScrollView scrollView = (ScrollView) getView().findViewById(R.id.shareScroll);
    scrollView.scrollTo(0, 0);
}

From source file:net.primeranks.fs_viewer.fs_replay.EntryPointActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.entry_point);

    ListView listView = getListView();
    listView.setOnItemClickListener(this);

    // Add a back to top button on the bottom       - Create the item
    backToTop_footer = (Button) getLayoutInflater().inflate(R.layout.user_footer, null);
    backToTop_footer.setCompoundDrawablesWithIntrinsicBounds(
            getResources().getDrawable(android.R.drawable.ic_menu_upload), null, null, null);
    backToTop_footer.setVisibility(View.INVISIBLE); // While empty do not show it
    headerUser = getLayoutInflater().inflate(R.layout.user_header, null);
    listView.addFooterView(backToTop_footer, null, true); // Add it to the bottom
    listView.addHeaderView(headerUser, null, false);

    userList = new ArrayList<User>(); // Start with an empty one
    this.userAdapter = new UserAdapter(this, userList);
    listView.setAdapter(this.userAdapter);
    listView.setItemsCanFocus(false);/*from  w ww. j  a v a  2 s  .  com*/

    connectionReceiver = new ConnectionChangedBroadcastReceiver();
    registerReceiver(connectionReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}

From source file:babybear.akbquiz.ConfigActivity.java

/**
 * /*ww  w . ja v  a  2s .com*/
 */
private void loadPlaylistEditor() {

    musicList = queryMusics();
    playlistList = loadPlaylist();

    PlaylistAdapter playlistAdapter = new PlaylistAdapter(this, playlistList, new OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = Integer.decode((String) v.getTag());
            onModifing = position;
            cfgflipper.showNext();
            ((TextView) findViewById(R.id.current)).setText(getString(R.string.config_bgm_onmodifing,
                    (onModifing + 1), playlistList.get(onModifing).TITLE));
            ((Button) findViewById(R.id.config_playlist_remove)).setText(R.string.remove);
        }
    });
    playlistView = (ListView) findViewById(R.id.playlist);
    playlistView.setAdapter(playlistAdapter);

    PlaylistAdapter musiclistAdapter = new PlaylistAdapter(this, musicList, new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            int position = Integer.parseInt((String) arg0.getTag());
            Log.d("", "set " + onModifing + " in Playlist with " + position + " in Musiclist");
            Music temp = musicList.get(position);
            // playlistAdapter.;
            if (onModifing == playlistList.size()) {
                playlistList.add(temp);
            } else {
                playlistList.set(onModifing, temp);
            }
            PlaylistAdapter adapter = (PlaylistAdapter) playlistView.getAdapter();
            adapter.remove(adapter.getItem(onModifing));
            adapter.insert(temp, onModifing);
            savePlaylist();

            isPlaylistChanged = true;
            cfgflipper.showPrevious();
        }

    });
    ListView musiclistView = (ListView) findViewById(R.id.musiclist);
    musiclistView.setAdapter(musiclistAdapter);

    ((Button) findViewById(R.id.config_playlist_add)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            int position = playlistList.size();
            onModifing = position;
            cfgflipper.showNext();
            ((TextView) findViewById(R.id.current)).setText(R.string.config_bgm_add);
            ((Button) findViewById(R.id.config_playlist_remove)).setText(android.R.string.cancel);
        }

    });

    ((Button) findViewById(R.id.config_playlist_remove)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (onModifing != playlistList.size()) {

                playlistList.remove(onModifing);

                // PlaylistAdapter adapter = (PlaylistAdapter)
                // playlistView
                // .getAdapter();
                // adapter.remove(adapter.getItem(onModifing));
                savePlaylist();

                isPlaylistChanged = true;
            }
            cfgflipper.showPrevious();
        }

    });

}

From source file:com.example.android.smssample.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Find some views
    mSetDefaultSmsLayout = (RelativeLayout) findViewById(R.id.set_default_sms_layout);
    mSendSmsEditText = (EditText) findViewById(R.id.send_sms_edittext);
    ListView listView = (ListView) findViewById(android.R.id.list);
    listView.setEmptyView(findViewById(android.R.id.empty));
    mSendSmsButton = (Button) findViewById(R.id.send_sms_button);
    mSendSmsButton.setOnClickListener(new OnClickListener() {
        @Override/*  w  w  w.  j  av a  2  s . c  om*/
        public void onClick(View view) {
            sendSms(mSendSmsEditText.getText().toString());
        }
    });

    // Create adapter and set it to our ListView
    final String[] fromFields = new String[] { SmsQuery.PROJECTION[SmsQuery.ADDRESS],
            SmsQuery.PROJECTION[SmsQuery.BODY] };
    final int[] toViews = new int[] { android.R.id.text1, android.R.id.text2 };
    mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, null, fromFields, toViews, 0);
    listView.setAdapter(mAdapter);

    // Placeholder to process incoming SEND/SENDTO intents
    String intentAction = getIntent() == null ? null : getIntent().getAction();
    if (!TextUtils.isEmpty(intentAction)
            && (Intent.ACTION_SENDTO.equals(intentAction) || Intent.ACTION_SEND.equals(intentAction))) {
        // TODO: Handle incoming SEND and SENDTO intents by pre-populating UI components
        Toast.makeText(this, "Handle SEND and SENDTO intents: " + getIntent().getDataString(),
                Toast.LENGTH_SHORT).show();
    }

    // Simple query to show the most recent SMS messages in the inbox
    getSupportLoaderManager().initLoader(SmsQuery.TOKEN, null, this);
}