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.afwsamples.testdpc.policy.PolicyManagementFragment.java

/**
 * Shows a list of primary user apps in a dialog.
 *
 * @param dialogTitle the title to show for the dialog
 * @param callback will be called with the list apps that the user has selected when he closes
 *        the dialog. The callback is not fired if the user cancels.
 *///from  www.  ja  v a 2 s . c om
private void showManageLockTaskListPrompt(int dialogTitle, final ManageLockTaskListCallback callback) {
    if (getActivity() == null || getActivity().isFinishing()) {
        return;
    }
    Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
    launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    final List<ResolveInfo> primaryUserAppList = mPackageManager.queryIntentActivities(launcherIntent, 0);
    if (primaryUserAppList.isEmpty()) {
        showToast(R.string.no_primary_app_available);
    } else {
        Collections.sort(primaryUserAppList, new ResolveInfo.DisplayNameComparator(mPackageManager));
        final LockTaskAppInfoArrayAdapter appInfoArrayAdapter = new LockTaskAppInfoArrayAdapter(getActivity(),
                R.id.pkg_name, primaryUserAppList);
        ListView listView = new ListView(getActivity());
        listView.setAdapter(appInfoArrayAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                appInfoArrayAdapter.onItemClick(parent, view, position, id);
            }
        });

        new AlertDialog.Builder(getActivity()).setTitle(getString(dialogTitle)).setView(listView)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String[] lockTaskEnabledArray = appInfoArrayAdapter.getLockTaskList();
                        callback.onPositiveButtonClicked(lockTaskEnabledArray);
                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }
}

From source file:com.fabioarias.ui.Store.java

/**
 * This method is called to initiate the view components and to apply
 * listeners to view components.//from  w  w w  . ja v  a2  s  . c o  m
 * 
 * @param v
 *            the container view
 */
private void setupViewComponents(View v) {
    ListView grid = (ListView) v.findViewById(R.id.list);
    Button checkout = (Button) v.findViewById(R.id.checkout);
    Button cancelar = (Button) v.findViewById(R.id.cancelar);
    ImageButton scanInvoice = (ImageButton) v.findViewById(R.id.scanButton_1);
    ImageButton scanVendor = (ImageButton) v.findViewById(R.id.scanButton_2);
    scanVendor.setVisibility(View.INVISIBLE);
    ImageButton scanCashier = (ImageButton) v.findViewById(R.id.scanButton_3);
    scanCashier.setVisibility(View.INVISIBLE);
    codigoVendedor = (EditText) v.findViewById(R.id.codigoVendedor);
    codigoVendedor.setVisibility(View.INVISIBLE);
    codigoCajero = (EditText) v.findViewById(R.id.codigoCajero);
    codigoCajero.setVisibility(View.INVISIBLE);
    numeroBoleta = (EditText) v.findViewById(R.id.numeroBoleta);
    if (((MainActivity) getActivity()).getFactura() != null) {
        numeroBoleta.setText(((MainActivity) getActivity()).getFactura().getNumero());
    }
    if (((MainActivity) getActivity()).getStore_codigo_vendedor() != null) {
        codigoVendedor.setText(((MainActivity) getActivity()).getStore_codigo_vendedor());

    }
    if (((MainActivity) getActivity()).getStore_codigo_cajero() != null) {
        codigoCajero.setText(((MainActivity) getActivity()).getStore_codigo_cajero());
    }
    setTouchNClick(cancelar);
    setTouchNClick(checkout);
    setTouchNClick(scanInvoice);
    setTouchNClick(scanVendor);
    setTouchNClick(scanCashier);
    grid.setAdapter(new StoreAdapter(((MainActivity) getActivity()).getCart()));
}

From source file:carsharing.starter.automotive.iot.ibm.com.mobilestarterapp.Profile.Profile.java

private void getDriverStats() {
    final String url = API.driverStats;

    try {/*from   www .j  a va 2s . c o m*/
        final API.doRequest task = new API.doRequest(new API.doRequest.TaskListener() {
            @Override
            public void postExecute(JSONArray result) throws JSONException {
                result.remove(result.length() - 1);

                final ListView listView = (ListView) view.findViewById(R.id.listView);

                final ArrayList<DriverStatistics> stats = new ArrayList<DriverStatistics>();

                for (int i = 0; i < result.length(); i++) {
                    final DriverStatistics tempDriverStatistics = new DriverStatistics(result.getJSONObject(i));
                    stats.add(tempDriverStatistics);
                }

                final FragmentActivity activity = getActivity();
                if (activity == null) {
                    return;
                }
                final ActionBar supportActionBar = ((AppCompatActivity) activity).getSupportActionBar();
                if (stats.size() > 0) {
                    stat = stats.get(0);
                    behaviors = stat.scoring.getScoringBehaviors();

                    Collections.sort(behaviors, new Comparator<ScoringBehavior>() {
                        @Override
                        public int compare(ScoringBehavior b1, ScoringBehavior b2) {
                            return b2.count - b1.count;
                        }
                    });

                    timesOfDay = stat.timeRange;
                    timesOfDay.toDictionary();

                    roadTypes = stat.roadType;
                    roadTypes.toDictionary();

                    trafficConditions = stat.speedPattern;
                    trafficConditions.toDictionary();

                    supportActionBar.setTitle("Your score is " + Math.round(stat.scoring.score) + "% for "
                            + Math.round(stat.totalDistance / 16.09344) / 100 + " miles.");

                    final ProfileDataAdapter adapter = new ProfileDataAdapter(activity.getApplicationContext(),
                            stats, behaviors, timesOfDay, trafficConditions, roadTypes);
                    listView.setAdapter(adapter);
                } else {
                    supportActionBar.setTitle("You have no analyzed trips.");
                }

                Log.i("Profile Data", result.toString());
            }
        });

        task.execute(url, "GET").get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

From source file:com.dpcsoftware.mn.CategoryStats.java

public void renderGraph() {
    SQLiteDatabase db = DatabaseHelper.quickDb(this, 0);
    if (date == null)
        date = Calendar.getInstance().getTime();

    String queryModifier = "";
    if (isByMonth)
        queryModifier = " AND strftime('%Y-%m'," + Db.Table1.TABLE_NAME + "." + Db.Table1.COLUMN_DATAT + ") = '"
                + app.dateToDb("yyyy-MM", date) + "'";

    Cursor c = db.rawQuery("SELECT " + Db.Table2.TABLE_NAME + "." + Db.Table2._ID + "," + Db.Table2.TABLE_NAME
            + "." + Db.Table2.COLUMN_NCAT + "," + Db.Table2.TABLE_NAME + "." + Db.Table2.COLUMN_CORCAT + ","
            + "SUM(" + Db.Table1.TABLE_NAME + "." + Db.Table1.COLUMN_VALORT + ")" + " FROM "
            + Db.Table1.TABLE_NAME + "," + Db.Table2.TABLE_NAME + " WHERE " + Db.Table1.TABLE_NAME + "."
            + Db.Table1.COLUMN_IDCAT + " = " + Db.Table2.TABLE_NAME + "." + Db.Table2._ID + " AND "
            + Db.Table1.TABLE_NAME + "." + Db.Table1.COLUMN_IDGRUPO + " = " + app.activeGroupId + queryModifier
            + " GROUP BY " + Db.Table1.TABLE_NAME + "." + Db.Table1.COLUMN_IDCAT + " ORDER BY "
            + Db.Table2.COLUMN_NCAT, null);

    float[] values = new float[c.getCount()];
    int[] colors = new int[c.getCount()];
    float total = 0;

    while (c.moveToNext()) {
        values[c.getPosition()] = c.getFloat(3);
        colors[c.getPosition()] = c.getInt(2);
        total += c.getFloat(3);/*from w  w w  . j  av  a 2 s  .c  om*/
    }

    BarChart v = new BarChart(this, values, colors);
    v.setPadding(10, 10, 10, 10);
    FrameLayout graphLayout = ((FrameLayout) findViewById(R.id.FrameLayout1));
    if (graphLayout.getChildCount() == 1)
        graphLayout.removeViewAt(0);
    graphLayout.addView(v);

    ListView lv = ((ListView) findViewById(R.id.listView1));
    ((TextView) footer.findViewById(R.id.textView2)).setText(app.printMoney(total));

    int days = 1;
    if (!isByMonth) {
        SimpleDateFormat dateF = new SimpleDateFormat("yyyy-MM-dd");
        dateF.setTimeZone(TimeZone.getDefault());

        Cursor cTemp = db.rawQuery("SELECT " + Db.Table1.COLUMN_DATAT + " FROM " + Db.Table1.TABLE_NAME
                + " WHERE " + Db.Table1.COLUMN_IDGRUPO + " = " + app.activeGroupId + " ORDER BY "
                + Db.Table1.COLUMN_DATAT + " DESC", null);
        try {
            cTemp.moveToFirst();
            Date date2 = dateF.parse(cTemp.getString(0));
            cTemp.moveToLast();
            Date date1 = dateF.parse(cTemp.getString(0));

            days = (int) Math.ceil((date2.getTime() - date1.getTime()) / (1000.0 * 24 * 60 * 60)) + 1;

            App.Log("" + days);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        Calendar now = Calendar.getInstance();
        if (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH)
                && cal.get(Calendar.YEAR) == now.get(Calendar.YEAR))
            days = now.get(Calendar.DAY_OF_MONTH);
        else
            days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    ((TextView) footer2.findViewById(R.id.textView2)).setText(app.printMoney(total / days));

    ((TextView) findViewById(R.id.textViewMonth)).setText(app.dateToUser("MMMM / yyyy", date));

    if (adapter == null) {
        adapter = new CategoryStatsAdapter(this, c, total);
        lv.setAdapter(adapter);
    } else {
        adapter.changeCursor(c, total);
        adapter.notifyDataSetChanged();
    }
}

From source file:com.sft.blackcatapp.EnrollSchoolActivity.java

private void showOpenCityPopupWindow(View parent) {
    if (openCityPopupWindow == null) {
        LinearLayout popWindowLayout = (LinearLayout) View.inflate(mContext, R.layout.pop_window, null);
        popWindowLayout.removeAllViews();
        // LinearLayout popWindowLayout = new LinearLayout(mContext);
        popWindowLayout.setOrientation(LinearLayout.VERTICAL);
        ListView OpenCityListView = new ListView(mContext);
        OpenCityListView.setDividerHeight(0);
        OpenCityListView.setCacheColorHint(android.R.color.transparent);
        OpenCityListView.setOnItemClickListener(new OnItemClickListener() {

            @Override/* www.  ja  v a 2  s .com*/
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                OpenCityVO selectCity = openCityList.get(position);
                System.out.println(selectCity.getName());
                cityname = selectCity.getName();
                licensetype = "";
                schoolname = "";
                ordertype = "";
                index = 1;
                obtainNearBySchool();
                openCityPopupWindow.dismiss();
                openCityPopupWindow = null;
            }
        });
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        popWindowLayout.addView(OpenCityListView, param);
        OpenCityAdapter openCityAdapter = new OpenCityAdapter(mContext, openCityList);
        OpenCityListView.setAdapter(openCityAdapter);

        openCityPopupWindow = new PopupWindow(popWindowLayout, 130, LayoutParams.WRAP_CONTENT);
    }
    openCityPopupWindow.setFocusable(true);
    openCityPopupWindow.setOutsideTouchable(true);
    // Back???
    openCityPopupWindow.setBackgroundDrawable(new BitmapDrawable());

    openCityPopupWindow.showAsDropDown(parent);
}

From source file:com.cerema.cloud2.ui.activity.Uploader.java

private void populateDirectoryList() {
    setContentView(R.layout.uploader_layout);

    ListView mListView = (ListView) findViewById(android.R.id.list);

    String current_dir = mParents.peek();
    if (current_dir.equals("")) {
        getSupportActionBar().setTitle(getString(R.string.default_display_name_for_root_folder));
    } else {/*from ww  w.ja  v a  2 s.co m*/
        getSupportActionBar().setTitle(current_dir);
    }
    boolean notRoot = (mParents.size() > 1);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(notRoot);
    actionBar.setHomeButtonEnabled(notRoot);

    String full_path = generatePath(mParents);

    Log_OC.d(TAG, "Populating view with content of : " + full_path);

    mFile = getStorageManager().getFileByPath(full_path);
    if (mFile != null) {
        // TODO Enable when "On Device" is recovered ?
        Vector<OCFile> files = getStorageManager().getFolderContent(mFile/*, false*/);
        List<HashMap<String, OCFile>> data = new LinkedList<HashMap<String, OCFile>>();
        for (OCFile f : files) {
            HashMap<String, OCFile> h = new HashMap<String, OCFile>();
            h.put("dirname", f);
            data.add(h);
        }

        UploaderAdapter sa = new UploaderAdapter(this, data, R.layout.uploader_list_item_layout,
                new String[] { "dirname" }, new int[] { R.id.filename }, getStorageManager(), getAccount());

        mListView.setAdapter(sa);
        Button btnChooseFolder = (Button) findViewById(R.id.uploader_choose_folder);
        btnChooseFolder.setOnClickListener(this);

        Button btnNewFolder = (Button) findViewById(R.id.uploader_cancel);
        btnNewFolder.setOnClickListener(this);

        mListView.setOnItemClickListener(this);
    }
}

From source file:cl.smartcities.isci.transportinspector.adapters.dialogAdapters.IncomingBusesAdapter.java

private void setEventsList(int pRow, ArrayList<Bus> pBus, int pShowing) {
    /* get row view */
    ListView listView = this.alertDialog.getListView();
    View v = listView.getChildAt(pRow - listView.getFirstVisiblePosition());
    if (v == null)
        return;/*from w  ww  .  j  av a2s. co  m*/
    /* get title elements */
    Button backButton = (Button) this.alertDialog.findViewById(R.id.back_button);
    TextView titleCode = (TextView) this.alertDialog.findViewById(R.id.bus_stop_code);
    TextView titleName = (TextView) this.alertDialog.findViewById(R.id.bus_stop_title);
    AppCompatImageView visibilityIcon = (AppCompatImageView) this.alertDialog
            .findViewById(R.id.visibility_icon);

    final String busStopCode = ((TextView) this.alertDialog.findViewById(R.id.bus_stop_code)).getText()
            .toString();
    final String busStopTitle = ((TextView) this.alertDialog.findViewById(R.id.bus_stop_title)).getText()
            .toString();
    /* decides which bus was being shown */
    int busIndex = pShowing - 1;
    /* shows the event list of the corresponding bus if there's at least one */
    if (pBus.get(busIndex).getAmountOfReports() > 0) {
        String code = pBus.get(busIndex).getService();
        String title = pBus.get(busIndex).getLicensePlate();
        titleCode.setText(code);
        titleName.setText(title);
        /* set back button to the list bus view */
        backButton.setVisibility(View.VISIBLE);
        visibilityIcon.setVisibility(View.GONE);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setBusesList(busStopCode, busStopTitle);
            }
        });
        EventAdapter adapter = new EventAdapter(this.context, code, title, "Bus",
                pBus.get(busIndex).getEvents());
        adapter.setDialog(this.alertDialog);
        listView.setAdapter(adapter);
    }
}

From source file:bus_vn.gena.bus_vn.com.bus_vn.tabs.Tab_list_bus_stop.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Context context = getActivity();
    DbOpenHelper dbOpenHelper = new DbOpenHelper(context);
    SQLiteDatabase db;/*from w w w.  ja  va 2s.  c o  m*/
    db = dbOpenHelper.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.clear();
    String st;
    st = "";
    st = "SELECT bus_stop_table.Name FROM bus_stop_path_table INNER JOIN bus_stop_table ON  bus_stop_path_table.Bus_stop_id=bus_stop_table.id ";
    st = st + "INNER JOIN bus_path_table ON  bus_stop_path_table.Bus_path_id=bus_path_table.id ";
    st = st + " WHERE bus_stop_path_table.Bus_path_id='" + busPathId + "'";
    st = st + " AND bus_stop_path_table.Type_day_id='" + typeDay + "'";
    Cursor c = db.rawQuery(st, null);

    while (c.moveToNext()) {
        String st2 = "";
        st2 = c.getString(0);
        results.add(st2);
    }
    //  ??
    ListView lvMain = (ListView) getView().findViewById(R.id.listView1);
    lvMain.setDivider(null);//   ? ListView
    //?? ?
    String[] values = results.toArray(new String[results.size()]);

    // custom adapter ? listview
    //? ClickListener ? listview
    lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        // ?
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //?  ?
            String busStop = (String) parent.getItemAtPosition(position);
            String busStopId = "";
            Context context = getActivity();
            DbOpenHelper dbOpenHelper = new DbOpenHelper(context);
            SQLiteDatabase db;
            db = dbOpenHelper.getWritableDatabase();
            ContentValues cv = new ContentValues();
            cv.clear();

            String st = "";
            st = "SELECT bus_stop_table.id FROM bus_stop_table ";
            st = st + " WHERE bus_stop_table.Name='" + busStop + "'";
            Cursor c = db.rawQuery(st, null);
            while (c.moveToNext()) {
                busStopId = c.getString(0);
            }
            Intent intent = new Intent(getActivity(), List_bus_time.class);
            intent.putExtra("busPathId", busPathId);
            intent.putExtra("busStopId", busStopId);
            intent.putExtra("typeDay", typeDay);
            //?  ? ?  
            startActivity(intent);
            //     
            // overridePendingTransition(R.anim.slide_left_in, R.anim.slide_left_out);**/
        }
    });
    ListviewArrayAdapter adapter = new ListviewArrayAdapter(getActivity(), values, values.length - 1);
    //     listview
    lvMain.setAdapter(adapter);
}

From source file:jp.mau.twappremover.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    _apps = new ArrayList<LinkedApp>();
    _handler = new Handler();
    _imageLoader = new ImageLoader(Volley.newRequestQueue(this), new BitmapCache());

    _id = (EditText) findViewById(R.id.activity_main_form_id);
    _pass = (EditText) findViewById(R.id.activity_main_form_pass);
    ListView list = (ListView) findViewById(R.id.activity_main_list);
    list.setOnItemClickListener(new OnItemClickListener() {
        @Override/*from  w  w w . j  a v  a 2s.  c  o  m*/
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
            final PopupView dialog = new PopupView(MainActivity.this);
            dialog.setDialog()
                    .setLabels(getString(R.string.activity_main_dlgtitle_revoke),
                            getString(R.string.activity_main_dlgmsg_revoke, _apps.get(position).name))
                    .setCancelable(true).setNegativeBtn(getString(R.string.activity_main_dlgbtn_revoke_cancel),
                            new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dialog.dismiss();
                                }
                            })
                    .setPositiveBtn(getString(R.string.activity_main_dlgbtn_revoke_conf),
                            new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dialog.dismiss();
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            revokeApp(_apps.get(position));
                                        }
                                    }).start();
                                }
                            })
                    .show();
        }
    });
    setButton();

    _appadapter = new AppAdapter(this);
    list.setAdapter(_appadapter);

    _client = new DefaultHttpClient();
    HttpParams params = _client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 60 * 1000);
    HttpConnectionParams.setSoTimeout(params, 60 * 1000);
    _client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

}

From source file:com.maskyn.fileeditorpro.activity.MainActivity.java

/**
 * Setup the navigation drawer//from   w ww. j a  v a2 s  .c om
 */
private void setupNavigationDrawer() {
    mDrawerLayout = (CustomDrawerLayout) findViewById(R.id.drawer_layout);
    /* Action Bar
    final ActionBar ab = toolbar;
    ab.setDisplayHomeAsUpEnabled(true);
    ab.setHomeButtonEnabled(true);*/
    /* Navigation drawer */
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.nome_app_turbo_editor,
            R.string.nome_app_turbo_editor) {

        @Override
        public void onDrawerOpened(View drawerView) {
            supportInvalidateOptionsMenu();
            try {
                closeKeyBoard();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onDrawerClosed(View view) {
            supportInvalidateOptionsMenu();
        }
    };
    /* link the mDrawerToggle to the Drawer Layout */
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    //mDrawerLayout.setFocusableInTouchMode(false);

    ListView listView = (ListView) findViewById(android.R.id.list);
    listView.setEmptyView(findViewById(android.R.id.empty));
    greatUris = new LinkedList<>();
    arrayAdapter = new AdapterDrawer(this, greatUris, this);
    listView.setAdapter(arrayAdapter);
    listView.setOnItemClickListener(this);
}