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:au.com.wallaceit.reddinator.SubredditSelectActivity.java

private void showMultiEditDialog(final String multiPath) {
    JSONObject multiObj = global.getSubredditManager().getMultiData(multiPath);

    @SuppressLint("InflateParams")
    LinearLayout dialogView = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_multi_edit, null); // passing null okay for dialog
    final Button saveButton = (Button) dialogView.findViewById(R.id.multi_save_button);
    final Button renameButton = (Button) dialogView.findViewById(R.id.multi_rename_button);
    multiName = (TextView) dialogView.findViewById(R.id.multi_pname);
    final EditText displayName = (EditText) dialogView.findViewById(R.id.multi_name);
    final EditText description = (EditText) dialogView.findViewById(R.id.multi_description);
    final EditText color = (EditText) dialogView.findViewById(R.id.multi_color);
    final Spinner icon = (Spinner) dialogView.findViewById(R.id.multi_icon);
    final Spinner visibility = (Spinner) dialogView.findViewById(R.id.multi_visibility);
    final Spinner weighting = (Spinner) dialogView.findViewById(R.id.multi_weighting);

    ArrayAdapter<CharSequence> iconAdapter = ArrayAdapter.createFromResource(SubredditSelectActivity.this,
            R.array.multi_icons, android.R.layout.simple_spinner_item);
    iconAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    icon.setAdapter(iconAdapter);//from w  w w.j a v  a  2 s  .c om
    ArrayAdapter<CharSequence> visibilityAdapter = ArrayAdapter.createFromResource(SubredditSelectActivity.this,
            R.array.multi_visibility, android.R.layout.simple_spinner_item);
    visibilityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    visibility.setAdapter(visibilityAdapter);
    ArrayAdapter<CharSequence> weightsAdapter = ArrayAdapter.createFromResource(SubredditSelectActivity.this,
            R.array.multi_weights, android.R.layout.simple_spinner_item);
    weightsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    weighting.setAdapter(weightsAdapter);

    try {
        multiName.setText(multiObj.getString("name"));
        displayName.setText(multiObj.getString("display_name"));
        description.setText(multiObj.getString("description_md"));
        color.setText(multiObj.getString("key_color"));
        String iconName = multiObj.getString("icon_name");
        icon.setSelection(iconAdapter.getPosition(iconName.equals("") ? "none" : iconName));
        visibility.setSelection(iconAdapter.getPosition(multiObj.getString("visibility")));
        weighting.setSelection(iconAdapter.getPosition(multiObj.getString("weighting_scheme")));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    ViewPager pager = (ViewPager) dialogView.findViewById(R.id.multi_pager);
    LinearLayout tabsWidget = (LinearLayout) dialogView.findViewById(R.id.multi_tab_widget);
    pager.setAdapter(new SimpleTabsAdapter(new String[] { "Subreddits", "Settings" },
            new int[] { R.id.multi_subreddits, R.id.multi_settings }, SubredditSelectActivity.this,
            dialogView));
    SimpleTabsWidget simpleTabsWidget = new SimpleTabsWidget(SubredditSelectActivity.this, tabsWidget);
    simpleTabsWidget.setViewPager(pager);
    ThemeManager.Theme theme = global.mThemeManager.getActiveTheme("appthemepref");
    int headerColor = Color.parseColor(theme.getValue("header_color"));
    int headerText = Color.parseColor(theme.getValue("header_text"));
    simpleTabsWidget.setBackgroundColor(headerColor);
    simpleTabsWidget.setTextColor(headerText);
    simpleTabsWidget.setInidicatorColor(Color.parseColor(theme.getValue("tab_indicator")));

    ListView subList = (ListView) dialogView.findViewById(R.id.multi_subredditList);
    multiSubsAdapter = new SubsListAdapter(SubredditSelectActivity.this, multiPath);
    subList.setAdapter(multiSubsAdapter);
    renameButton.getBackground().setColorFilter(headerColor, PorterDuff.Mode.MULTIPLY);
    renameButton.setTextColor(headerText);
    renameButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showMultiRenameDialog(multiPath);
        }
    });

    saveButton.getBackground().setColorFilter(headerColor, PorterDuff.Mode.MULTIPLY);
    saveButton.setTextColor(headerText);
    saveButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            System.out.println("Save multi");
            JSONObject multiObj = new JSONObject();
            try {
                multiObj.put("decription_md", description.getText().toString());
                multiObj.put("display_name", displayName.getText().toString());
                multiObj.put("icon_name", icon.getSelectedItem().toString().equals("none") ? ""
                        : icon.getSelectedItem().toString());
                multiObj.put("key_color", color.getText().toString());
                multiObj.put("subreddits",
                        global.getSubredditManager().getMultiData(multiPath).getJSONArray("subreddits"));
                multiObj.put("visibility", visibility.getSelectedItem().toString());
                multiObj.put("weighting_scheme", weighting.getSelectedItem().toString());

                new SubscriptionEditTask(SubscriptionEditTask.ACTION_MULTI_EDIT).execute(multiPath, multiObj);

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

    AlertDialog.Builder builder = new AlertDialog.Builder(SubredditSelectActivity.this);

    multiDialog = builder.setView(dialogView).show();
}

From source file:edu.csh.coursebrowser.SchoolActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_course_browser);
    ListView lv = (ListView) this.findViewById(R.id.schools);
    this.setTitle("Course Browser");

    map_items = new HashMap<String, School>();
    map = new ArrayList<String>();
    this.sp = getPreferences(MODE_WORLD_READABLE);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map);
    this.setTitle("Course Browser");

    if (!sp.contains("firstRun")) {
        SharedPreferences.Editor e = sp.edit();
        e.putBoolean("firstRun", false);
        e.commit();/*from   w w  w.  ja v a  2 s . c o m*/
        Intent intent = new Intent(SchoolActivity.this, AboutActivity.class);
        startActivity(intent);
    }

    addItem(new School("01", "Saunder's College of Business"));
    addItem(new School("03", "College of Engineering"));
    addItem(new School("05", "College of Liberal Arts"));
    addItem(new School("06", "Applied Science & Technology"));
    addItem(new School("08", "NTID"));
    addItem(new School("10", "College of Science"));
    addItem(new School("11", "Wellness"));
    addItem(new School("17", "Academic Services"));
    addItem(new School("20", "Imaging Arts and Sciences"));
    addItem(new School("30", "Interdisciplinary Studies"));
    addItem(new School("40", "GCCIS"));
    addItem(new School("50", "Institute for Sustainability"));

    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            String s = ((TextView) arg1).getText().toString();
            final School school = map_items.get(s);
            new AsyncTask<String, String, String>() {
                ProgressDialog p;

                protected void onPreExecute() {
                    p = new ProgressDialog(SchoolActivity.this);
                    p.setTitle("Fetching Info");
                    p.setMessage("Contacting Server...");
                    p.setCancelable(false);
                    p.show();
                }

                protected String doInBackground(String... school) {
                    String params = "action=getDepartments&school=" + school[0] + "&quarter=20123";
                    Log.v("Params", params);
                    URL url;
                    String back = "";
                    try {
                        url = new URL("http://iota.csh.rit" + ".edu/schedule/js/browseAjax.php");

                        URLConnection conn = url.openConnection();
                        conn.setDoOutput(true);
                        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                        writer.write(params);
                        writer.flush();
                        String line;
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(conn.getInputStream()));

                        while ((line = reader.readLine()) != null) {
                            Log.v("Back:", line);
                            back += line;
                        }
                        writer.close();
                        reader.close();
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        return null;
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        return null;
                    }
                    return back;
                }

                protected void onPostExecute(String s) {
                    if (s == null || s == "") {
                        new AlertError(SchoolActivity.this, "IO Error!").show();
                        return;
                    }

                    try {
                        JSONObject jso = new JSONObject(s);
                        JSONArray jsa = new JSONArray(jso.getString("departments"));
                        ArrayList<Department> depts = new ArrayList<Department>();
                        for (int i = 0; i < jsa.length(); ++i) {
                            JSONObject obj = new JSONObject(jsa.get(i).toString());
                            depts.add(new Department(obj.getString("title"), obj.getString("id"),
                                    obj.getString("code")));
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        new AlertError(SchoolActivity.this, "Invalid JSON From Server").show();
                        p.dismiss();
                        return;
                    }

                    Intent intent = new Intent(SchoolActivity.this, DepartmentActivity.class);
                    intent.putExtra("from", school.deptName);
                    intent.putExtra("args", s);
                    intent.putExtra("qCode", sp.getString("quarter", "20122"));
                    startActivity(intent);
                    p.dismiss();
                }
            }.execute(school.deptNum);
        }

    });

}

From source file:com.example.maciej.mytask.MainActivity.java

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

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.activity_main);

    Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);/*from  ww  w .ja  v  a  2  s  .  co  m*/

    createNotification();

    mDateTimeTextView = (TextView) findViewById(R.id.dateTimeTextView);
    //      final Button addTaskBtn = (Button) findViewById(R.id.addTaskBtn);
    final ListView listview = (ListView) findViewById(R.id.taskListview);
    //      final CheckedTextView listitem = (CheckedTextView) findViewById(R.id.checkedTextView1);
    mNameList = new ArrayList<String>();
    mDescriptionList = new ArrayList<String>();
    mDateList = new ArrayList<String>();

    String savedNameList = getSharedPreferences(PREFS_TASKS, MODE_PRIVATE).getString(KEY_NAME_LIST, null);
    if (savedNameList != null) {
        String[] name_items = savedNameList.split(",");
        mNameList = new ArrayList<String>(Arrays.asList(name_items));
    }

    String savedDescriptionList = getSharedPreferences(PREFS_TASKS, MODE_PRIVATE)
            .getString(KEY_DESCRIPTION_LIST, null);
    if (savedDescriptionList != null) {
        String[] description_items = savedDescriptionList.split(",");
        mDescriptionList = new ArrayList<String>(Arrays.asList(description_items));
    }

    String savedDateList = getSharedPreferences(PREFS_TASKS, MODE_PRIVATE).getString(KEY_DATE_LIST, null);
    if (savedDateList != null) {
        String[] date_items = savedDateList.split(",");
        mDateList = new ArrayList<String>(Arrays.asList(date_items));
    }

    mAdapter = new ArrayAdapter<String>(this, R.layout.list_item, mNameList);
    listview.setAdapter(mAdapter);
    listview.setItemsCanFocus(false);
    listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            CheckedTextView item = (CheckedTextView) view;
            if (item.isChecked()) {
                Toast.makeText(getApplicationContext(), getString(R.string.checked), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), getString(R.string.unchecked), Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });

    listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            descriptionClicked(view);
            return true;
        }
    });

    mTickReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                mDateTimeTextView.setText(getCurrentTimeStamp());
            }
        }
    };

}

From source file:com.inmobi.ultrapush.AnalyzeActivity.java

public PopupWindow popupMenuCreate(String[] popUpContents, int resId) {

    // initialize a pop up window type
    PopupWindow popupWindow = new PopupWindow(this);

    // the drop down list is a list view
    ListView listView = new ListView(this);

    // set our adapter and pass our pop up window contents
    ArrayAdapter<String> aa = popupMenuAdapter(popUpContents);
    listView.setAdapter(aa);

    // set the item click listener
    listView.setOnItemClickListener(this);

    listView.setTag(resId); // button res ID, so we can trace back which button is pressed

    // get max text width
    Paint mTestPaint = new Paint();
    mTestPaint.setTextSize(listItemTextSize);
    float w = 0;// w ww. ja  v  a 2 s  .  co  m
    float wi; // max text width in pixel
    for (int i = 0; i < popUpContents.length; i++) {
        String sts[] = popUpContents[i].split("::");
        String st = sts[0];
        if (sts.length == 2 && sts[1].equals("0")) {
            mTestPaint.setTextSize(listItemTitleTextSize);
            wi = mTestPaint.measureText(st);
            mTestPaint.setTextSize(listItemTextSize);
        } else {
            wi = mTestPaint.measureText(st);
        }
        if (w < wi) {
            w = wi;
        }
    }

    // left and right padding, at least +7, or the whole app will stop respond, don't know why
    w = w + 20 * DPRatio;
    if (w < 60) {
        w = 60;
    }

    // some other visual settings
    popupWindow.setFocusable(true);
    popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
    // Set window width according to max text width
    popupWindow.setWidth((int) w);
    // also set button width
    ((Button) findViewById(resId)).setWidth((int) (w + 4 * DPRatio));
    // Set the text on button in updatePreferenceSaved()

    // set the list view as pop up window content
    popupWindow.setContentView(listView);

    return popupWindow;
}

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

public void getCars(final Location location) {
    final String url = API.carsNearby + "/" + location.getLatitude() + "/" + location.getLongitude();

    try {/*from w  w  w.  j  av a 2  s.  com*/
        final API.doRequest task = new API.doRequest(new API.doRequest.TaskListener() {
            @Override
            public void postExecute(JSONArray result) throws JSONException {
                JSONObject serverResponse = result.getJSONObject(result.length() - 1);
                int statusCode = serverResponse.getInt("statusCode");

                result.remove(result.length() - 1);

                final FragmentActivity activity = getActivity();
                if (activity == null) {
                    return;
                }
                final ActionBar supportActionBar = ((AppCompatActivity) activity).getSupportActionBar();
                if (statusCode == 200) {
                    final View view = getView();
                    if (view == null) {
                        return;
                    }
                    final ListView listView = (ListView) view.findViewById(R.id.listView);

                    final ArrayList<CarData> carsArray = new ArrayList<CarData>();

                    for (int i = 0; i < result.length(); i++) {
                        final CarData tempCarData = new CarData(result.getJSONObject(i));
                        carsArray.add(tempCarData);

                        final LatLng carLocation = new LatLng(tempCarData.lat, tempCarData.lng);
                        mMap.addMarker(new MarkerOptions().position(carLocation).title(tempCarData.title)
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.models)));
                    }

                    Collections.sort(carsArray, new Comparator<CarData>() {
                        @Override
                        public int compare(CarData lhs, CarData rhs) {
                            return lhs.distance - rhs.distance;
                        }
                    });

                    final CarDataAdapter adapter = new CarDataAdapter(activity.getApplicationContext(),
                            carsArray);
                    listView.setAdapter(adapter);

                    final ArrayList<CarData> finalCarsArray = carsArray;

                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
                            final Intent carDetails = new Intent(view.getContext(), CarDetails.class);

                            final Bundle bundle = new Bundle();
                            bundle.putSerializable("carData", finalCarsArray.get(position));
                            carDetails.putExtras(bundle);

                            startActivity(carDetails);
                        }
                    });

                    if (carsArray.size() == 0) {
                        final Toast toast = Toast.makeText(activity.getApplicationContext(),
                                "No car available in this area. Location information may be incorrect. Make sure GPS or Wifi is effective and try again. Or, Free Plan limitation, ask administrator to delete registered cars.",
                                Toast.LENGTH_LONG);
                        toast.show();
                        supportActionBar.setTitle("No car available.");
                    } else {
                        final String title = (carsArray.size() == 1) ? "1 car found."
                                : carsArray.size() + " cars found.";
                        supportActionBar.setTitle(title);
                    }

                    Log.i("Car Data", result.toString());
                } else if (statusCode == 500) {
                    final Toast toast = Toast.makeText(activity.getApplicationContext(),
                            "A server internal error received. Ask your administrator.", Toast.LENGTH_LONG);
                    toast.show();
                    supportActionBar.setTitle("Error: Server internal error.");
                } else {
                    final Toast toast = Toast.makeText(activity.getApplicationContext(),
                            "Error: Unable to connect to server.", Toast.LENGTH_LONG);
                    toast.show();
                    supportActionBar.setTitle("Error: Not connected to server.");
                }
            }
        });

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

From source file:com.coincollection.MainActivity.java

/**
 * Finishes setting up the view once the database has been opened.
 *//*from   w  w w  .  jav a  2  s  .  c o m*/
private void finishViewSetup() {

    // Called from the InitTask after the database has been successfully
    // opened for the first time.  Now we can be fairly sure that future
    // open's won't trigger an ANR issue.

    if (BuildConfig.DEBUG) {
        Log.v("mainActivity", "finishViewSetup");
    }

    // Instantiate the DatabaseAdapter
    mDbAdapter = new DatabaseAdapter(this);

    // Populate mCollectionListEntries with the data from the database
    updateCollectionListFromDatabase();

    // Instantiate the FrontAdapter
    mListAdapter = new FrontAdapter(mContext, mCollectionListEntries, mNumberOfCollections);

    ListView lv = (ListView) findViewById(R.id.main_activity_listview);

    lv.setAdapter(mListAdapter);

    // TODO Not sure what this does?
    lv.setTextFilterEnabled(true); // Typing narrows down the list

    // For when we use fragments, listen to the backstack so we can transition back here from
    // the fragment

    getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        public void onBackStackChanged() {

            if (0 == getSupportFragmentManager().getBackStackEntryCount()) {

                // We are back at this activity, so restore the ActionBar
                getSupportActionBar().setTitle(mRes.getString(R.string.app_name));
                getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                getSupportActionBar().setHomeButtonEnabled(false);

                // The collections may have been re-ordered, so update them here.
                updateCollectionListFromDatabase();

                // Change it out with the new list
                mListAdapter.items = mCollectionListEntries;
                mListAdapter.numberOfCollections = mNumberOfCollections;
                mListAdapter.notifyDataSetChanged();
            }
        }
    });

    // Now set the onItemClickListener to perform a certain action based on what's clicked
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // See whether it was one of the special list entries (Add collection, delete
            // collection, etc.)
            if (position >= mNumberOfCollections) {

                int newPosition = position - mNumberOfCollections;
                Intent intent;

                switch (newPosition) {
                case ADD_COLLECTION:
                    intent = new Intent(mContext, CoinPageCreator.class);
                    startActivity(intent);
                    break;
                case REMOVE_COLLECTION:

                    if (mNumberOfCollections == 0) {
                        Toast.makeText(mContext, mRes.getString(R.string.no_collections), Toast.LENGTH_SHORT)
                                .show();
                        break;
                    }
                    // Thanks!
                    // http://stackoverflow.com/questions/2397106/listview-in-alertdialog
                    CharSequence[] names = new CharSequence[mNumberOfCollections];
                    for (int i = 0; i < mNumberOfCollections; i++) {
                        names[i] = mCollectionListEntries.get(i).getName();
                    }

                    AlertDialog.Builder delete_builder = new AlertDialog.Builder(mContext);
                    delete_builder.setTitle(mRes.getString(R.string.select_collection_delete));
                    delete_builder.setItems(names, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int item) {
                            showDeleteConfirmation(mCollectionListEntries.get(item).getName());
                        }
                    });
                    AlertDialog alert = delete_builder.create();
                    alert.show();
                    break;
                case IMPORT_COLLECTIONS:
                    handleImportCollectionsPart1();
                    break;
                case EXPORT_COLLECTIONS:
                    handleExportCollectionsPart1();
                    break;
                case REORDER_COLLECTIONS:

                    if (mNumberOfCollections == 0) {
                        Toast.makeText(mContext, mRes.getString(R.string.no_collections), Toast.LENGTH_SHORT)
                                .show();
                        break;
                    }

                    // Get a list that excludes the spacers
                    List<CollectionListInfo> tmp = mCollectionListEntries.subList(0, mNumberOfCollections);
                    ArrayList<CollectionListInfo> collections = new ArrayList<>(tmp);

                    ReorderCollections fragment = new ReorderCollections();
                    fragment.setCollectionList(collections);

                    // Show the fragment used for reordering collections
                    getSupportFragmentManager().beginTransaction()
                            .add(R.id.main_activity_frame, fragment, "ReorderFragment").addToBackStack(null)
                            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();

                    // Setup the actionbar for the reorder page
                    // TODO Check for NULL
                    getSupportActionBar().setTitle(mRes.getString(R.string.reorder_collection));
                    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                    getSupportActionBar().setHomeButtonEnabled(true);

                    break;
                case ABOUT:

                    LayoutInflater inflater = (LayoutInflater) mContext
                            .getSystemService(LAYOUT_INFLATER_SERVICE);
                    View layout = inflater.inflate(R.layout.info_popup,
                            (ViewGroup) findViewById(R.id.info_layout_root));

                    AlertDialog.Builder info_builder = new AlertDialog.Builder(mContext);
                    info_builder.setView(layout);

                    TextView tv = (TextView) layout.findViewById(R.id.info_textview);
                    tv.setText(buildInfoText());

                    AlertDialog alertDialog = info_builder.create();
                    alertDialog.show();
                    break;
                }

                return;
            }
            // If it gets here, the user has selected a collection

            Intent intent = new Intent(mContext, CollectionPage.class);

            CollectionListInfo listEntry = mCollectionListEntries.get(position);

            intent.putExtra(CollectionPage.COLLECTION_NAME, listEntry.getName());
            intent.putExtra(CollectionPage.COLLECTION_TYPE_INDEX, listEntry.getCollectionTypeIndex());

            startActivity(intent);
        }
    });
}

From source file:terse.a1.TerseActivity.java

private void viewPath9display(String path, LayoutParams widgetParams) {
    String explain;//from   www . java 2 s. co  m
    if (terp_error != null) {
        explain = "terp_error = " + terp_error;
    } else {
        try {
            terp.say("Sending to terp: %s", path);
            final Dict d = terp.handleUrl(path, taQuery);
            explain = "DEFAULT EXPLANATION:\n\n" + d.toString();

            Str TYPE = d.cls.terp.newStr("type");
            Str VALUE = d.cls.terp.newStr("value");
            Str TITLE = d.cls.terp.newStr("title");
            Str type = (Str) d.dict.get(TYPE);
            Ur value = d.dict.get(VALUE);
            Ur title = d.dict.get(TITLE);

            // {
            // double ticks = Static.floatAt(d, "ticks", -1);
            // double nanos = Static.floatAt(d, "nanos", -1);
            // Toast.makeText(
            // getApplicationContext(),
            // Static.fmt("%d ticks, %.3f secs", (long) ticks,
            // (double) nanos / 1e9), Toast.LENGTH_SHORT)
            // .show();
            // }

            if (type.str.equals("list") && value instanceof Vec) {
                final ArrayList<Ur> v = ((Vec) value).vec;
                final ArrayList<String> labels = new ArrayList<String>();
                final ArrayList<String> links = new ArrayList<String>();
                for (int i = 0; i < v.size(); i++) {
                    Ur item = v.get(i);
                    String label = item instanceof Str ? ((Str) item).str : item.toString();
                    if (item instanceof Vec && ((Vec) item).vec.size() == 2) {
                        // OLD STYLE
                        label = ((Vec) item).vec.get(0).toString();
                        Matcher m = LINK_P.matcher(label);
                        if (m.lookingAt()) {
                            label = m.group(2) + " " + m.group(3);
                        }
                        label += "    [" + ((Vec) item).vec.get(1).toString().length() + "]";
                        links.add(null); // Use old style, not links.
                    } else {
                        // NEW STYLE
                        label = item.toString();
                        if (label.charAt(0) == '/') {
                            String link = Terp.WHITE_PLUS.split(label, 2)[0];
                            links.add(link);
                        } else {
                            links.add("");
                        }
                    }
                    labels.add(label);
                }
                if (labels.size() != links.size())
                    terp.toss("lables#%d links#%d", labels.size(), links.size());

                ListView listv = new ListView(this);
                listv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, labels));
                listv.setLayoutParams(widgetParams);
                listv.setTextFilterEnabled(true);

                listv.setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        // When clicked, show a toast with the TextView text
                        // Toast.makeText(getApplicationContext(),
                        // ((TextView) view).getText(),
                        // Toast.LENGTH_SHORT).show();
                        String toast_text = ((TextView) view).getText().toString();
                        // if (v.get(position) instanceof Vec) {
                        if (links.get(position) == null) {
                            // OLD STYLE
                            Vec pair = (Vec) v.get(position);
                            if (pair.vec.size() == 2) {
                                if (pair.vec.get(0) instanceof Str) {
                                    String[] words = ((Str) pair.vec.get(0)).str.split("\\|");
                                    Log.i("TT-WORDS", terp.arrayToString(words));
                                    toast_text += "\n\n" + Static.arrayToString(words);
                                    if (words[1].equals("link")) {
                                        Uri uri = new Uri.Builder().scheme("terse").path(words[2]).build();
                                        Intent intent = new Intent("android.intent.action.MAIN", uri);
                                        intent.setClass(getApplicationContext(), TerseActivity.class);

                                        startActivity(intent);
                                    }
                                }
                            }
                        } else {
                            // NEW STYLE
                            terp.say("NEW STYLE LIST SELECT #%d link=<%s> label=<%s>", position,
                                    links.get(position), labels.get(position));
                            if (links.get(position).length() > 0) {
                                Uri uri = new Uri.Builder().scheme("terse").path(links.get(position)).build();
                                Intent intent = new Intent("android.intent.action.MAIN", uri);
                                intent.setClass(getApplicationContext(), TerseActivity.class);

                                startActivity(intent);
                            }
                        }
                        // }
                        // Toast.makeText(getApplicationContext(),
                        // ((TextView) view).getText(),
                        // Toast.LENGTH_SHORT).show();
                    }
                });
                setContentView(listv);
                return;
            } else if (type.str.equals("edit") && value instanceof Str) {
                final EditText ed = new EditText(this);

                ed.setText(taSaveMe == null ? value.toString() : taSaveMe);

                ed.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE
                        | InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
                ed.setLayoutParams(widgetParams);
                // ed.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
                ed.setTextAppearance(this, R.style.teletype);
                ed.setBackgroundColor(Color.BLACK);
                ed.setGravity(Gravity.TOP);
                ed.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
                ed.setVerticalFadingEdgeEnabled(true);
                ed.setVerticalScrollBarEnabled(true);
                ed.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // If the event is a key-down event on the "enter"
                        // button
                        // if ((event.getAction() == KeyEvent.ACTION_DOWN)
                        // &&
                        // (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        // // Perform action on key press
                        // Toast.makeText(TerseActivity.this, ed.getText(),
                        // Toast.LENGTH_SHORT).show();
                        // return true;
                        // }
                        return false;
                    }
                });

                Button btn = new Button(this);
                btn.setText("Save");
                btn.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        // Perform action on clicks
                        String text = ed.getText().toString();
                        text = Parser.charSubsts(text);
                        Toast.makeText(TerseActivity.this, text, Toast.LENGTH_SHORT).show();
                        String action = stringAt(d, "action");
                        String query = "";

                        String f1 = stringAt(d, "field1");
                        String v1 = stringAt(d, "value1");
                        String f2 = stringAt(d, "field2");
                        String v2 = stringAt(d, "value2");
                        f1 = (f1 == null) ? "f1null" : f1;
                        v1 = (v1 == null) ? "v1null" : v1;
                        f2 = (f2 == null) ? "f2null" : f2;
                        v2 = (v2 == null) ? "v2null" : v2;

                        startTerseActivity(action, query, stringAt(d, "field1"), stringAt(d, "value1"),
                                stringAt(d, "field2"), stringAt(d, "value2"), "text", text);
                    }
                });

                LinearLayout linear = new LinearLayout(this);
                linear.setOrientation(LinearLayout.VERTICAL);
                linear.addView(btn);
                linear.addView(ed);
                setContentView(linear);
                return;

            } else if (type.str.equals("draw") && value instanceof Vec) {
                Vec v = ((Vec) value);
                DrawView dv = new DrawView(this, v.vec, d);
                dv.setLayoutParams(widgetParams);
                setContentView(dv);
                return;
            } else if (type.str.equals("live")) {
                Blk blk = value.mustBlk();
                Blk event = Static.urAt(d, "event").asBlk();
                TerseSurfView tsv = new TerseSurfView(this, blk, event);
                setContentView(tsv);
                return;
            } else if (type.str.equals("fnord")) {
                Blk blk = value.mustBlk();
                Blk event = Static.urAt(d, "event").asBlk();
                FnordView fnord = new FnordView(this, blk, event);
                setContentView(fnord);
                return;
            } else if (type.str.equals("world") && value instanceof Str) {
                String newWorld = value.toString();
                if (Terp.WORLD_P.matcher(newWorld).matches()) {
                    world = newWorld;
                    resetTerp();
                    explain = Static.fmt("Switching to world <%s>\nUse menu to go Home.", world);
                    Toast.makeText(getApplicationContext(), explain, Toast.LENGTH_LONG).show();
                } else {
                    terp.toss("Bad world syntax (must be 3 letters then 0 to 3 digits: <%s>", newWorld);
                }
                // Fall thru for explainv.setText(explain).
            } else if (type.str.equals("text")) {
                explain = "<<< " + title + " >>>\n\n" + value.toString();
                // Fall thru for explainv.setText(explain).
            } else if (type.str.equals("html")) {
                final WebView webview = new WebView(this);
                // webview.loadData(value.toString(), "text/html", null);
                webview.loadDataWithBaseURL("terse://terse", value.toString(), "text/html", "UTF-8", null);
                webview.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        // terp.say("WebView UrlLoading: url=%s", url);
                        URI uri = URI.create("" + url);
                        // terp.say("WebView UrlLoading: URI=%s", uri);
                        terp.say("WebView UrlLoading: getPath=%s", uri.getPath());
                        terp.say("WebView UrlLoading: getQuery=%s", uri.getQuery());

                        // Toast.makeText(getApplicationContext(),
                        // uri.toASCIIString(), Toast.LENGTH_SHORT)
                        // .show();
                        // webview.invalidate();
                        //
                        // TextView quick = new
                        // TextView(TerseActivity.this);
                        // quick.setText(uri.toASCIIString());
                        // quick.setBackgroundColor(Color.BLACK);
                        // quick.setTextColor(Color.WHITE);
                        // setContentView(quick);

                        startTerseActivity(uri.getPath(), uri.getQuery());

                        return true;
                    }
                });

                // webview.setWebChromeClient(new WebChromeClient());
                webview.getSettings().setBuiltInZoomControls(true);
                // webview.getSettings().setJavaScriptEnabled(true);
                webview.getSettings().setDefaultFontSize(18);
                webview.getSettings().setNeedInitialFocus(true);
                webview.getSettings().setSupportZoom(true);
                webview.getSettings().setSaveFormData(true);
                setContentView(webview);

                // ScrollView scrollv = new ScrollView(this);
                // scrollv.addView(webview);
                // setContentView(scrollv);
                return;
            } else {
                explain = "Unknown page type: " + type.str + " with vaule type: " + value.cls
                        + "\n\n##############\n\n";
                explain += value.toString();
                // Fall thru for explainv.setText(explain).
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            explain = Static.describe(ex);
        }
    }

    TextView explainv = new TextView(this);
    explainv.setText(explain);
    explainv.setBackgroundColor(Color.BLACK);
    explainv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
    explainv.setTextColor(Color.YELLOW);

    SetContentViewWithHomeButtonAndScroll(explainv);
}

From source file:com.sft.blackcatapp.SearchCoachActivity.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//from www. ja v  a 2 s  .  c o  m
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                OpenCityVO selectCity = openCityList.get(position);
                System.out.println(selectCity.getName());
                cityname = selectCity.getName().replace("", "");
                licensetype = "";
                coachname = "";
                ordertype = "0";
                index = 1;
                obtainCaoch();
                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.example.hbranciforte.trafficclient.History.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_history);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String token = telephonyManager.getDeviceId().toString();
    //HttpPost httppostreq = new HttpPost("http://10.0.2.2:3000/parkings??notification_token=".concat(token));
    ListView listView = (ListView) findViewById(R.id.historyable);

    try {// ww  w  . j  a  va2s  . co m
        HttpClient client = new DefaultHttpClient();
        String getURL = "http://45.55.79.197/parkings?notification_token=".concat(token);
        //String getURL = "http://10.0.2.2:3000/parkings?notification_token=".concat(token);
        HttpGet get = new HttpGet(getURL);
        HttpResponse responseGet = client.execute(get);
        HttpEntity resEntityGet = responseGet.getEntity();
        if (resEntityGet != null) {
            String response = EntityUtils.toString(resEntityGet);
            data = new JSONArray(response);

            String[] values = new String[data.length()];
            for (int i = 0; i < this.data.length(); i++) {
                JSONObject parking = new JSONObject(data.get(i).toString());
                JSONObject zone = new JSONObject(parking.getString("zone"));
                JSONObject car = new JSONObject(parking.getString("car"));
                String temp = "Patente: ".concat(car.getString("license_plate")).concat("\n");
                temp = temp.concat("Zona: ").concat(zone.getString("name")).concat("-")
                        .concat(Integer.toString(zone.getInt("number")).concat("\n"));
                temp = temp.concat("Estado: ").concat(parking.getString("status")).concat("\n");
                values[i] = temp.concat("Valido hasta: ").concat(parking.getString("formated_expires_at"));

            }
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                    android.R.id.text1, values);
            listView.setAdapter(adapter);
        }
    } catch (Exception e) {
        Log.e("Error Parsing:", e.getMessage());
    }

}

From source file:com.abewy.android.apps.klyph.app.MainActivity.java

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

    /*/*from   w w w .j  a va2 s  . c  o m*/
     * if (KlyphSession.getSessionUserName() != null)
     * {
     * loggedIn = true;
     * setTitle(KlyphSession.getSessionUserName());
     * }
     * else
     * {
     * if (KlyphFlags.IS_PRO_VERSION == true)
     * setTitle(R.string.app_pro_name);
     * else
     * setTitle(R.string.app_name);
     * }
     */
    setTitle("");

    if (Session.getActiveSession() == null || KlyphSession.getSessionUserId() == null
            || (Session.getActiveSession() != null && Session.getActiveSession().isOpened() == false)) {
        getActionBar().hide();
        getFragmentManager().beginTransaction().add(R.id.main, new LoginFragment(), FRAGMENT_TAG).commit();
    }

    // notificationsFragment.setHasOptionsMenu(false);
    adContainer = (ViewGroup) findViewById(R.id.ad);

    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    drawerToggle = new ActionBarDrawerToggle(this, drawer, AttrUtil.getResourceId(this, R.attr.drawerIcon),
            R.string.open, R.string.close) {
        @Override
        public void onDrawerOpened(View view) {
            Log.d("MainActivity.onCreate(...).new ActionBarDrawerToggle() {...}", "onDrawerOpened: ");
            super.onDrawerOpened(view);

            Fragment fragment = getFragmentManager().findFragmentByTag(FRAGMENT_TAG);

            if (drawer.isDrawerOpen(Gravity.RIGHT)) {
                // drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN, Gravity.RIGHT);

                if (notificationsFragment != null) {
                    notificationsFragment.setHasOptionsMenu(true);
                    notificationsFragment.onOpenPane();
                }

                if (fragment != null)
                    fragment.setHasOptionsMenu(false);
            } else if (drawer.isDrawerOpen(Gravity.LEFT)) {

                if (notificationsFragment != null) {
                    notificationsFragment.setHasOptionsMenu(false);
                }

                if (fragment != null)
                    fragment.setHasOptionsMenu(true);
            }

            invalidateOptionsMenu();
        }

        @Override
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);

            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT);

            if (!drawer.isDrawerOpen(Gravity.RIGHT)) {
                if (notificationsFragment != null)
                    notificationsFragment.setHasOptionsMenu(false);

                Fragment fragment = getFragmentManager().findFragmentByTag(FRAGMENT_TAG);

                if (fragment != null)
                    fragment.setHasOptionsMenu(true);
            }
            invalidateOptionsMenu();
        }
    };

    drawer.setDrawerListener(drawerToggle);

    final List<String> labels = KlyphPreferences.getLeftDrawerMenuLabels();
    classes = new ArrayList<String>(KlyphPreferences.getLeftDrawerMenuClasses());
    classes.add("com.abewy.android.apps.klyph.fragment.UserTimeline");
    navAdapter = new DrawerLayoutAdapter(getActionBar().getThemedContext(), R.layout.item_drawer_layout,
            labels);

    final ListView navList = (ListView) findViewById(R.id.drawer);

    // Setting drawers max width
    int maxWidth = getResources().getDimensionPixelSize(R.dimen.max_drawer_layout_width);

    int w = Math.min(KlyphDevice.getDeviceWidth(), KlyphDevice.getDeviceHeight())
            - getResources().getDimensionPixelSize(R.dimen.dip_64);

    int finalWidth = Math.min(maxWidth, w);

    LayoutParams params = ((View) navList.getParent()).getLayoutParams();
    params.width = finalWidth;
    ((View) navList.getParent()).setLayoutParams(params);

    final View notificationContainer = findViewById(R.id.notifications_container);
    params = notificationContainer.getLayoutParams();
    params.width = finalWidth;
    notificationContainer.setLayoutParams(params);

    // End max width
    navList.setFadingEdgeLength(0);
    navList.setVerticalFadingEdgeEnabled(false);
    navList.setAdapter(navAdapter);

    navList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int pos, long id) {
            updateContent(pos);
            drawer.closeDrawer(Gravity.LEFT);
        }
    });

    // Try to use more data here. ANDROID_ID is a single point of attack.
    // String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);

    // Library calls this when it's done.
    // mLicenseCheckerCallback = new MyLicenseCheckerCallback();

    // Construct the LicenseChecker with a policy.
    // mChecker = new LicenseChecker(this, new ServerManagedPolicy(this, new AESObfuscator(SALT, getPackageName(), deviceId)), BASE64_PUBLIC_KEY);

    // mChecker.checkAccess(mLicenseCheckerCallback)

    // Facebook HashKey
    if (KlyphFlags.LOG_FACEBOOK_HASH)
        FacebookUtil.logHash(this);

    // Hierarchy View Connector
    if (KlyphFlags.ENABLE_HIERACHY_VIEW_CONNECTOR)
        HierachyViewUtil.connectHierarchyView(this);
}