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.example.android.gft.NumbersFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.word_list, container, false);

    // Create and setup the {@link AudioManager} to request audio focus
    mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);

    // Create a list of words
    final ArrayList<Word> words = new ArrayList<Word>();
    words.add(//from  ww  w . j a  v a  2  s  . c o  m
            new Word(R.string.number_one, R.string.miwok_number_one, R.drawable.number_one, R.raw.number_one));
    words.add(
            new Word(R.string.number_two, R.string.miwok_number_two, R.drawable.number_two, R.raw.number_two));
    words.add(new Word(R.string.number_three, R.string.miwok_number_three, R.drawable.number_three,
            R.raw.number_three));
    words.add(new Word(R.string.number_four, R.string.miwok_number_four, R.drawable.number_four,
            R.raw.number_four));
    words.add(new Word(R.string.number_five, R.string.miwok_number_five, R.drawable.number_five,
            R.raw.number_five));
    words.add(
            new Word(R.string.number_six, R.string.miwok_number_six, R.drawable.number_six, R.raw.number_six));
    words.add(new Word(R.string.number_seven, R.string.miwok_number_seven, R.drawable.number_seven,
            R.raw.number_seven));
    words.add(new Word(R.string.number_eight, R.string.miwok_number_eight, R.drawable.number_eight,
            R.raw.number_eight));
    words.add(new Word(R.string.number_nine, R.string.miwok_number_nine, R.drawable.number_nine,
            R.raw.number_nine));
    words.add(
            new Word(R.string.number_ten, R.string.miwok_number_ten, R.drawable.number_ten, R.raw.number_ten));

    // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
    // adapter knows how to create list items for each item in the list.
    WordAdapter adapter = new WordAdapter(getActivity(), words, R.color.category_numbers);

    // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
    // There should be a {@link ListView} with the view ID called list, which is declared in the
    // word_list.xml layout file.
    ListView listView = (ListView) rootView.findViewById(R.id.list);

    // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
    // {@link ListView} will display list items for each {@link Word} in the list.
    listView.setAdapter(adapter);

    // Set a click listener to play the audio when the list item is clicked on
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            // Release the media player if it currently exists because we are about to
            // play a different sound file
            releaseMediaPlayer();

            // Get the {@link Word} object at the given position the user clicked on
            Word word = words.get(position);

            // Request audio focus so in order to play the audio file. The app needs to play a
            // short audio file, so we will request audio focus with a short amount of time
            // with AUDIOFOCUS_GAIN_TRANSIENT.
            int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                // We have audio focus now.

                // Create and setup the {@link MediaPlayer} for the audio resource associated
                // with the current word
                mMediaPlayer = MediaPlayer.create(getActivity(), word.getAudioResourceId());

                // Start the audio file
                mMediaPlayer.start();

                // Setup a listener on the media player, so that we can stop and release the
                // media player once the sound has finished playing.
                mMediaPlayer.setOnCompletionListener(mCompletionListener);
            }
        }
    });

    return rootView;
}

From source file:com.example.android.quakereport.EarthquakeActivity.java

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

    // Find a reference to the ListView in the layout
    ListView earthquakeListView = (ListView) findViewById(R.id.list);

    // Create a new adapter that takes an empty list (for now) of earthquakes as input
    mQuakeAdapter = new QuakeAdapter(getApplicationContext(), new ArrayList<Quake>());

    // Set the adapter on the ListView
    // so the list can be populated in the user interface
    earthquakeListView.setAdapter(mQuakeAdapter);

    // Set onclick listener
    earthquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override/*from   www .  ja va  2  s. com*/
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // Get the quake object at the given position the user clicked on
            Quake quake = mQuakeAdapter.getItem(position);

            String url = quake.getUrl();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            startActivity(intent);
        }
    });

    getSupportLoaderManager().initLoader(1, null, this);
    Log.v(LOG_TAG, "getSupportLoaderManager().initLoader executing!");

    mEmptyStateTextView = (TextView) findViewById(R.id.empty);
    earthquakeListView.setEmptyView(mEmptyStateTextView);
}

From source file:com.brq.wallet.activity.modern.AddressBookFragment.java

private void updateUiMine() {
    List<Entry> entries = new ArrayList<Entry>();
    for (WalletAccount account : Utils.sortAccounts(_mbwManager.getWalletManager(false).getActiveAccounts(),
            _mbwManager.getMetadataStorage())) {
        String name = _mbwManager.getMetadataStorage().getLabelByAccount(account.getId());
        Drawable drawableForAccount = Utils.getDrawableForAccount(account, true, getResources());
        Optional<Address> receivingAddress = account.getReceivingAddress();
        if (receivingAddress.isPresent()) {
            entries.add(new AddressBookManager.IconEntry(receivingAddress.get(), name, drawableForAccount));
        }/* ww  w.  ja  v a 2 s. c  o  m*/
    }
    if (entries.isEmpty()) {
        findViewById(R.id.tvNoRecords).setVisibility(View.VISIBLE);
        findViewById(R.id.lvForeignAddresses).setVisibility(View.GONE);
    } else {
        findViewById(R.id.tvNoRecords).setVisibility(View.GONE);
        findViewById(R.id.lvForeignAddresses).setVisibility(View.VISIBLE);
        ListView list = (ListView) findViewById(R.id.lvForeignAddresses);
        list.setAdapter(new AddressBookAdapter(getActivity(), R.layout.address_book_my_address_row, entries));
    }
}

From source file:com.artur.softwareproject.BluetoothConnectionList.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_bluetooth_connection);

    ListView bluetoothList;
    bluetoothList = (ListView) findViewById(R.id.bluetoothList);

    ListAdapter = new BluetoothConnectionListAdapter(this, bluetoothAddress, bluetoothName, bDevices);

    bluetoothList.setAdapter(ListAdapter);

    BluetoothManager bluetoothManager;//from   w w w. ja v a  2  s .  co  m
    bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

    bluetoothAdapter = bluetoothManager.getAdapter();

    mHandler = new Handler();

    File topLevelDir, jsonDir, objDir;

    //Creating the directory structure for the app.
    topLevelDir = new File(Environment.getExternalStorageDirectory() + "/ViSensor");

    jsonDir = new File(Environment.getExternalStorageDirectory() + "/ViSensor/Json");

    objDir = new File(Environment.getExternalStorageDirectory() + "/ViSensor/Obj");

    if (!topLevelDir.exists()) {
        if (!topLevelDir.mkdir()) {
            Log.d(TAG, "Creating top level directory failed.");
        }

        if (!jsonDir.exists()) {
            if (!jsonDir.mkdir()) {
                Log.d(TAG, "Creating json directory failed.");
            }
        }

        if (!objDir.exists()) {
            if (!objDir.mkdir()) {
                Log.d(TAG, "Creating obj directory failed.");
            }
        }
    } else if (!jsonDir.exists()) {
        if (!jsonDir.mkdir()) {
            Log.d(TAG, "Creating json directory failed.");
        }

        if (!objDir.exists()) {
            if (!objDir.mkdir()) {
                Log.d(TAG, "Creating obj directory failed.");
            }
        }
    } else if (!objDir.exists()) {
        if (!objDir.mkdir()) {
            Log.d(TAG, "Creating obj directory failed.");
        }
    }

    if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

        final int REQUEST_ENABLE_BT = 1;

        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    int permissionCheckLocation = ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION);

    int permissionCheckWrite = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permissionCheckLocation != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, 0);
    }

    if (permissionCheckWrite != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
    }

    scanLeDevice(true);
}

From source file:com.brq.wallet.activity.modern.AddressBookFragment.java

private void updateUiForeign() {
    Map<Address, String> rawentries = _mbwManager.getMetadataStorage().getAllAddressLabels();
    List<Entry> entries = new ArrayList<Entry>();
    for (Map.Entry<Address, String> e : rawentries.entrySet()) {
        entries.add(new Entry(e.getKey(), e.getValue()));
    }/* w w w  .  j a  v a  2 s.  c o m*/
    entries = Utils.sortAddressbookEntries(entries);
    if (entries.isEmpty()) {
        findViewById(R.id.tvNoRecords).setVisibility(View.VISIBLE);
        findViewById(R.id.lvForeignAddresses).setVisibility(View.GONE);
    } else {
        findViewById(R.id.tvNoRecords).setVisibility(View.GONE);
        findViewById(R.id.lvForeignAddresses).setVisibility(View.VISIBLE);
        ListView foreignList = (ListView) findViewById(R.id.lvForeignAddresses);
        foreignList
                .setAdapter(new AddressBookAdapter(getActivity(), R.layout.address_book_foreign_row, entries));
    }
}

From source file:com.google.sample.beaconservice.MainActivityFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    final ProgressBar progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
    progressBar.setProgress(0);// ww w. j a  va2 s . c om
    progressBar.getProgressDrawable().setColorFilter(Color.GREEN, PorterDuff.Mode.MULTIPLY);

    scanButton = (Button) rootView.findViewById(R.id.scanButton);
    scanButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Utils.setEnabledViews(false, scanButton);
            arrayAdapter.clear();
            scanner.startScan(SCAN_FILTERS, SCAN_SETTINGS, scanCallback);
            Log.i(TAG, "starting scan");
            client = new ProximityBeaconImpl(getActivity(), accountNameView.getText().toString());
            CountDownTimer countDownTimer = new CountDownTimer(SCAN_TIME_MILLIS, 100) {
                @Override
                public void onTick(long millisUntilFinished) {
                    double i = (1 - millisUntilFinished / (double) SCAN_TIME_MILLIS) * 100;
                    progressBar.setProgress((int) i);
                }

                @Override
                public void onFinish() {
                    progressBar.setProgress(100);
                }
            };
            countDownTimer.start();

            Runnable stopScanning = new Runnable() {
                @Override
                public void run() {
                    scanner.stopScan(scanCallback);
                    Log.i(TAG, "stopped scan");
                    Utils.setEnabledViews(true, scanButton);
                }
            };
            handler.postDelayed(stopScanning, SCAN_TIME_MILLIS);
        }
    });

    accountNameView = (TextView) rootView.findViewById(R.id.accountName);
    accountNameView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pickUserAccount();
        }
    });

    // Set the account name from the shared prefs if we ever set it before.
    String accountName = sharedPreferences.getString("accountName", "");
    if (!accountName.isEmpty()) {
        accountNameView.setText(accountName);
    } else {
        pickUserAccount();
    }

    ListView listView = (ListView) rootView.findViewById(R.id.listView);
    listView.setAdapter(arrayAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Beacon beacon = arrayAdapter.getItem(position);
            if (beacon.status.equals(Beacon.NOT_AUTHORIZED)) {
                new AlertDialog.Builder(getActivity()).setTitle("Not Authorized")
                        .setMessage("You don't have permission to view the details of this beacon")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();
                return;
            }
            if (beacon.status.equals(Beacon.STATUS_UNSPECIFIED)) {
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putString("accountName", accountNameView.getText().toString());
            bundle.putParcelable("beacon", arrayAdapter.getItem(position));
            ManageBeaconFragment fragment = new ManageBeaconFragment();
            fragment.setArguments(bundle);
            getFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack(TAG)
                    .commit();
        }
    });
    return rootView;
}

From source file:com.tdispatch.passenger.fragment.SearchAddressFragment.java

@Override
protected void onPostCreateView() {

    ImageView iv = (ImageView) mFragmentView.findViewById(R.id.icon);
    EditText et = (EditText) mFragmentView.findViewById(R.id.address);

    int imgId = R.drawable.ic_launcher;
    int hintId = R.string.address_search_generic_hint;
    switch (mType) {
    case SearchActivity.TYPE_PICKUP:
        imgId = R.drawable.map_marker_pickup;
        hintId = R.string.address_search_pickup_hint;
        break;//ww  w . j  ava2s  .c  o  m
    case SearchActivity.TYPE_DROPOFF:
        imgId = R.drawable.map_marker_dropoff;
        hintId = R.string.address_search_dropoff_hint;
        break;
    }
    iv.setImageResource(imgId);

    et.setText((mAddress != null) ? mAddress.getAddress() : "");
    et.setHint(hintId);

    et.setOnEditorActionListener(mOnEditorActionListener);
    et.addTextChangedListener(mTextWatcher);

    WebnetTools.setVisibility(mFragmentView, R.id.button_voice_search,
            mVoiceSearchAvailable ? View.VISIBLE : View.GONE);

    int[] ids = { R.id.button_voice_search, R.id.button_clear };
    for (int id : ids) {
        View v = mFragmentView.findViewById(id);
        if (v != null) {
            v.setOnClickListener(mOnClickListener);
        }
    }

    WebnetTools.setVisibility(mFragmentView, R.id.button_clear, View.GONE);

    ListView lv = (ListView) mFragmentView.findViewById(R.id.list);
    mAdapter = new ListAdapter(mParentActivity, 0, mItems);
    lv.setAdapter(mAdapter);
}

From source file:com.example.db.messagewall.activity.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        mDrawerLayout.openDrawer(GravityCompat.START);
        break;/*ww w  .j  a  v  a  2s .c  om*/
    case R.id.action_about:
        startActivity(new Intent(MainActivity.this, AboutActivity.class));
        break;
    case R.id.action_feedback:
        Intent intent = new Intent(MainActivity.this, CustomActivity.class);
        startActivity(intent);
        break;
    case R.id.action_settheme:
        final MaterialDialog materialDialog = new MaterialDialog(MainActivity.this);
        View view = LayoutInflater.from(this).inflate(R.layout.color_picker, null);
        ListView listView = (ListView) view.findViewById(R.id.listview);
        final ColorPickerAdapter colorPickerAdapter = new ColorPickerAdapter(MainActivity.this);
        listView.setAdapter(colorPickerAdapter);
        materialDialog.setView(view);
        materialDialog.setCanceledOnTouchOutside(true);
        materialDialog.setNegativeButton("Cancel", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                materialDialog.dismiss();
            }
        }).setPositiveButton("Ok", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (colorPickerAdapter.Flag) {
                    ThemeHelper.setTheme(MainActivity.this, colorPickerAdapter.getThemeId());
                    reload();
                    materialDialog.dismiss();
                } else {
                    materialDialog.dismiss();
                }
            }
        });
        materialDialog.show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.ProfessorPopTart.alternateouyastore.MainActivity.java

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

    GameList = new ArrayList<String>();
    GameListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, GameList);
    final ListView myListView = (ListView) findViewById(R.id.appsLBX);
    final TextView myGameName = (TextView) findViewById(R.id.gameName);
    myListView.setAdapter(GameListAdapter);
    myListView.setTextFilterEnabled(true);

    //assign onclick event to getListBTN
    Button myGetListBTN = (Button) findViewById(R.id.getListBTN);
    myGetListBTN.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            populateList();//from   ww w . j a  v a  2 s . com
        }
    });

    //assign onclick event to downloadGameBTN
    Button myDownloadBTN = (Button) findViewById(R.id.donwloadBTN);
    myDownloadBTN.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            buildDownloadRequest(myGameName.getText().toString());
        }
    });

    //assign onSelected event to appsLBX
    myListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            String selectedFromList = (myListView.getItemAtPosition(i).toString());
            displayImage(getImgUrl(selectedFromList));
            myGameName.setText(selectedFromList);
        }

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

        }
    });
}

From source file:com.atguigu.android.android_pulltorefresh.PullToRefreshListFragmentActivity.java

/** Called when the activity is first created. */
@Override/*from   w w  w .j  a  v  a  2 s . c o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ptr_list_fragment);

    tv_title = (TextView) findViewById(R.id.tv_title);
    tv_title.setText("PullToRefreshListFragment");

    //getSupportFragmentManager().findFragmentById(id);Fragment
    mPullRefreshListFragment = (PullToRefreshListFragment) getSupportFragmentManager()
            .findFragmentById(R.id.frag_ptr_list);

    // Get PullToRefreshListView from Fragment
    mPullRefreshListView = mPullRefreshListFragment.getPullToRefreshListView();

    // Set a listener to be invoked when the list should be refreshed.
    //?
    mPullRefreshListView.setOnRefreshListener(this);

    // You can also just use mPullRefreshListFragment.getListView()
    ListView listview = mPullRefreshListView.getRefreshableView();

    mListItems = new LinkedList<String>();
    //?
    mListItems.addAll(Arrays.asList(mStrings));
    mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mListItems);

    // You can also just use setListAdapter(mAdapter) or
    // mPullRefreshListView.setAdapter(mAdapter)
    listview.setAdapter(mAdapter);

    mPullRefreshListFragment.setListShown(true);
}