Android name value pairs from an ArrayList - android

In the following code I am able to retrieve the _id value of each record and display it along with the text in a ListView but when I select an item from the list the returned value is 0 to N dependent on how the results are laid out in the list.
How can I get the _id value, I guess as a named value pair so that when 0 or 1… is selected it outputs the _id field and not 0 or 1… for my OnItemClickListener
This is my method, it’s messy, once I get it working I’ll try to refine it!
private void GetCoordinates(double currentLatitude, double currentLongitude) {
List<String> ar = new ArrayList<String>();
dbBookHelper = new DatabaseHelper(this);
ourCursor = dbBookHelper.getCoordinates();
int counta = 0;
ourCursor.moveToFirst();
do {
id = ourCursor.getInt(ourCursor.getColumnIndex("_id"));
BeachName = ourCursor.getString(ourCursor.getColumnIndex("BeachName"));
beachLatitude = ourCursor.getDouble(ourCursor.getColumnIndex("latitude"));
beachLongitude = ourCursor.getDouble(ourCursor.getColumnIndex("longitude"));
distence = ConvertDistance(beachLatitude, beachLongitude);
if (distence <= 5) {
ar.add(id + " " + BeachName + " - " + distence + "Kms");
counta++;
}
} while (ourCursor.moveToNext());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.row2, R.id.beachListText, ar);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(onListClick);
Toast.makeText(getBaseContext(), "There are " + String.valueOf(counta) + " beaches within a 5km radius!", Toast.LENGTH_LONG).show();
}
And this is my OnItemClickListener method
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Toast.makeText(getBaseContext(), String.valueOf(id) + " selected", Toast.LENGTH_LONG).show();
}
};
Any help would be greatly appreciated,
Cheers,
Mike.
Edit: Thanks guys, I was hoping for a slicker way too!
But I now have a second array holding just the id values with,
ar1.add(String.valueOf(id));
So the positions are the same, but how do I get them into the OnItemClickListener? I guess somewhere in here???
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.row2, R.id.beachListText, ar);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(onListClick);

The basic problem is the ArrayAdapter does not know anything about the Cursor or rowId. I think you have 2 choices. The first is to manage the mapping of array position to rowId yourself. For example, create a second array to map the ArrayList position to the rowId, and do a simple lookup in the listener.
If that is not appropriate for some reason then you could create a custom adapter with knowledge of the Cursor, by extending CursorAdapter. It involves over-riding 2 methods newView() and bindView() to allocate and populate the views (with your custom string) that will be displayed in each row. It also provides filtering hooks that would allow you to implement the < 5KM filter you need.
I haven't gone through this particular case myself, but did recently have to extend an ArrayAdapter to implement a SectionIndexer for a very long list. While it was a valuable exercise, I think in your case a custom adapter is possibly overkill. A second array look-up may be simpler and more appropriate.
1) Make your new array a class member so it is accessible in the listener
ArrayList<Long> mIdArr = null;
2) Create this in a similar way to your String array
mIdArr = new ArrayList<Long>();
3) Store the rowId at the same point you add to your String array
ar.add(id + " " + BeachName + " - " + distence + "Kms");
mIdArr.add(new Long(id));
4) Retrieve the Id in your listener like this
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Long rowId = mIdArr.get(position);
Toast.makeText(getBaseContext(), String.valueOf(rowId) + " selected", Toast.LENGTH_LONG).show();
}
};

Related

Show data with hidden ID with android

I have JSONArray with several JSONObjects and each JSONObject contains Name and ID. How can I show only the name and leave the ID hidden. I need to be able to get the ID afterwards by knowing which row was pressed. I don't care how to show it, with list view, table, grid or whatever. This is how I get the data from the JSONArray:
for (int i = 0; i < ans.length(); i++) {
int id = Integer.parseInt(ans.getJSONObject(i).getString("UserID"));
String disName = ans.getJSONObject(i).getString("DisplayName");
adapter.add(disName + " - " + id);
}
Thank you in advance
After the first answer I created a Class name DisNameID containing diaplyName and ID and the toString is return displayName. The listView on this activity is called "frndLst". This is the code that should fill the listview:
ListView lstFrnd = (ListView) findViewById(R.id.frndLst);
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this, android.R.layout.XXX, listItems);
for (int i = 0; i < ans.length(); i++) {
int id = integer.parseInt(ans.getJSONObject(i).getString("UserID"));
String disName = ans.getJSONObject(i).getString("DisplayName");
DisNameID dis = new DisNameID(disName, id);
adapter.add(disName + " - " + id);
}
Now I have 2 new questions: How to change the adapter to hold my new class - DisNameID? What to write instead of the XXX on the new adapter constructor?
Create Holder object, override toString:
class Holder {
private String name;
private String id;
//getters and setters;
public String toString(){ return name };
}
Then add such objects to your adapter. This way, the name will be displayed, but you can get Holder objects from your adapter using this method and use the id.

Showing an ArrayList content on a Toast

I have a listView and I want to print the arrrayList which contains the selected items.
I can show the choice that I choose every time. i.e. if I select a choice, I can print it in a toast (I mark it in my code as a comment), but I want to print the whole choices together.
Any help please?
Thanks..
If I understand correctly, you want to display the contents of your arrayList in a Toast.
Like donfuxx said, you need to create your arrayList outside of your onclicklistener.
As the user clicks an item, it will be added to your arrayList.
Then loop over the list to fill a string called allItems, then show allItems in a toast.
ArrayList<String> checked = new ArrayList<String>();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String listItem = (String) listView.getItemAtPosition(position);
if(!checked.contains(listItem)){ //optional: avoids duplicate Strings in your list
checked.add((position+1), listItem);
}
String allItems = ""; //used to display in the toast
for(String str : checked){
allItems = allItems + "\n" + str; //adds a new line between items
}
Toast.makeText(getApplicationContext(),allItems, Toast.LENGTH_LONG).show();
}
});
Well you have the right concept, jsut wrong execution here is the part you missed out on:`
ArrayList<String> checked = new ArrayList<String>();
checked.add((position+1), listItem);
Toast.makeText(getApplicationContext(),checked.get((position+1)), Toast.LENGTH_LONG).show();`
You have to get the position of the element in the ArrayList which you require to fetch, hence
checked.get(array position of element here)
If you want to show every item that is in the ArrayList you can use a simple loop and add them to a string like this:
...
checked.add((position+1), listItem);
String tempString = "";
for(int x = 0; x < checked.length(); x++) {
tempString = tempString + ", " + checked.get(x);
}
tempString = tempString.substring(2);
Toast.makeText(getApplicationContext(),tempString, Toast.LENGTH_LONG).show();
EDIT modified it a bit to only put commas between items

Get spacial content of selected item in listview in android

I am new with android programing and I have a problem with list view
In my app I have to read data from database (name,ID,year) and then add them to listview after that user must select one of
the items and in a new activity again I read data from db and list some of the other Items based on user's selection
Ol at this time In my first activity I read data and add them to listview..To select I must define a listener..right?
I define it like this code
enter code here #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_book);
String SDcardPath = Environment.getExternalStorageDirectory().getPath();
String DbPath = SDcardPath + "/Tosca/" + "persian_poem.db";
ListView list = (ListView) findViewById(R.id.list_poet_name);
try {
db = SQLiteDatabase.openDatabase(DbPath,null,SQLiteDatabase.CREATE_IF_NECESSARY);
getData();
db.close();
}
catch (SQLiteException e) {
Toast.makeText(this, e.getMessage(), 1).show();
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
ListView list = (ListView) findViewById(R.id.list_poet_name);
Log.i(TAG, "Listview get Item Pos");
Peot_ID.putString ("Peot_ID", (String) list.getItemAtPosition(position));
Intent Book_list_intent = new Intent (Read.this,Book_list.class);
Book_list_intent.putExtras(Peot_ID);
startActivity(Book_list_intent);
}
});
}
private void getData() {
try {
//txtMsg.append("\n");
// obtain a list of from DB
String TABLE_NAME = "classicpoems__poet_contents";
String COLUMN_ID = "poet_id";
String _ID = "_id";
String COLUMN_NAME = "poet_name";
String COLUMN_CENTURY = "century_start";
String [] columns ={_ID,COLUMN_ID,COLUMN_NAME,COLUMN_CENTURY};
Cursor c = db.query(TABLE_NAME,columns,null, null, null, null, COLUMN_ID);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, c,
new String[] {COLUMN_NAME,COLUMN_CENTURY}, new int[] {android.R.id.text1,android.R.id.text2}, 0);
ListView list = (ListView) findViewById(R.id.list_poet_name);
list.setAdapter(adapter);
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), 1).show();
}
}
But here I have a problem..I want to send data of peot_id (Its deffrent from _id column in db) to next activity..Bt I mentioned that
with this code I can get whole row of selected item and I just want part of it(peot_id ) can you help me how to get just Peot_ID from selected
list item?
and I have another question..
As you see in my code I must refer to one spasial listview several times..each time I defined it by this code
enter code hereListView list = (ListView) findViewById(R.id.list_poet_name);
How can I define this listviwe one time and use it in several places in my code?sth like a public variable or sth like that
Thanks for your help.
As you see in my code I must refer to one spasial listview several
times..each time I defined it by this code
No. Just create one global ListView variable list and simply you can access to it from everywhere in your Activity. There is no need to declaring and initialising ListView again in OnItemClick() method.
I want to send data of peot_id (Its deffrent from _id column in db) to
next activity..Bt I mentioned that with this code I can get whole row
of selected item and I just want part of it(peot_id ) can you help me
how to get just Peot_ID from selected list item?
You are using Android's defined basic layout
android.R.layout.simple_list_item_2
I suggest you to create own XML file for row and then simply get whole View from ListView and from View you can get only ID.
Example:
listrow.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:background="#drawable/addresses_list_selector"
>
<TextView
android:id="#+id/id_column"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/name_column"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/id_column"
/>
<TextView
android:id="#+id/century_column"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/name_column"
/>
</RelativeLayout>
Then an usage with CursorAdapter:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listrow, c,
new String[] {COLUMN_ID, COLUMN_NAME, COLUMN_CENTURY},
new int[] {R.id.id_column, R.id.name_column, R.id.century_column}, 0);
And then for getting ID from row:
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
TextView id = (TextView) v.findViewById(R.id.id_column);
if (id != null) {
String idString = id.getText().toString();
}
}
Note:
If you still want to use android's predefined layout, you need to pass into String[] from ID_COLUMN and then access to ID from row via row.findViewById(<id>);
String[] from = {ID_COLUMN, NAME_COLUMN};
int[] to = {android.R.id.text1, android.R.id.text2};
TextView id = v.findViewById(android.R.id.android.R.id.text1);
String idString = id.getText().toString();
You do query like this to get a Particular column record alone :
Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_DESIGNATION}, KEY_ROWID + "=" + yourPrimaryKey, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
I personally prefer to use onListItemclick() method like that
//do not forget to override - very important
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//TODO what you what you have here the vars position - position of the selected item in list
// and also the id so you can easy trace what selection done the user
// you can play with this
}

Sorting the contents of ArrayAdapter or ArrayList

I am working on android project and am making using of a ListView that retrieves data from the SQLite database.
I am making a dataset using an ArrayList and then adding this ArrayList into an ArrayAdapter.
When the data is being retrieved from the database, I am telling SQLite to do the sorting so everything is in alphabetical order when it is added into the ListView. At certain times, the information will be added dynamically to to the ListView without it requiring to re-fetch everythin from the database again. However, I want to keep everything in alphabetical order.
How would I do this, do I sort the DataSet and then call the notifyDataSet Changes or do I do the sort directly on the ArrayAdapter. I've looked into performing the sort on the ArrayAdapter but this wants an argument that uses a Comparator but not sure what this is and can't find any working examples that may be of any help for what I want to achieve.
Below is the code that populates the array and sets the list adapter
ArrayList<Spanned> passwords = managePasswordList.getPasswordList();
if (passwords != null && passwords.size() > 0)
{
passwordArrayAdapter = new ArrayAdapter<Spanned>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_activated_1, passwords);
setListAdapter(passwordArrayAdapter);
myListView.setTextFilterEnabled(true);
txtNoRecords.setVisibility(View.GONE);
}
else
{
txtNoRecords.setVisibility(View.VISIBLE);
}
I am then adding data to the dataset and refreshing the list view using the following
String company = Encryption.decrypt(passwords.get(i).company);
String username = Encryption.decrypt(passwords.get(i).username);
details = Html.fromHtml(company + "<br />" + "<small><font color=\"#767676\">" + username + "</b></small>");
passwords.add(details);
passwordArrayAdapter.notifyDataSetChanged();
Thanks for any help you can provide.
UPDATE 1
I've tried doing what Nick Bradbury suggested but I am having a problem with the comparator. I have the following code but I don't know where to go from here.
SQLiteDatabase myDb = null;
Cursor cursor = null;
ArrayList<Spanned> passwords = new ArrayList<Spanned>();
try
{
myDb = context.openOrCreateDatabase("PasswordManager", Context.MODE_PRIVATE, null);
cursor = myDb.rawQuery("SELECT * FROM password ASC", null);
while (cursor.moveToNext())
{
final String company = Encryption.decrypt(cursor.getString(2));
final String username = Encryption.decrypt(cursor.getString(4));
Spanned details = Html.fromHtml(company + "<br />" + "<small><font color=\"#767676\">" + username + "</b></small>");
passwords.add(details);
Collections.sort(passwords, new Comparator<Spanned>() {
public int compare(Spanned lhs, Spanned rhs) {
return 0;
}
});
}
}
catch (SQLiteException ex)
{
common.showBasicAlertDialog("Unfortunately something has gone wrong.\n\nWe will fix this as soon as we can", false);
Log.e("Database Error", ex.toString());
return null;
}
In the return statement I have no idea what to do, I've tried return lhs.compareTo but the lhs and rhs variables don't have the compareTo function so I have not got a clue what to do.
Here's a simple example of sorting an ArrayList using Comparator. In this example, the ArrayList is defined as:
public class StatusList extends ArrayList<Status>
A sort routine for this ArrayList could look like this:
public void sort() {
Collections.sort(this, new Comparator<Status>() {
#Override
public int compare(Status item1, Status item2) {
return item2.getDate().compareTo(item1.getDate());
}
});
}
Replace <Status> with whatever object your ArrayList contains, then change the comparison to compare the values of the object you wish to sort by.

Populating a spinner with specific entries from an array

I am working on an application for Android. For this I am making an Activity in which you select your country and then a spot in that country. I have one spinner that contains a list of all available countries. Now, what I want it to do is get the country that has been selected, then filter a list of spots that I have for the items that start with the country that has been selected. Then it should put the spots for the selected country into a different spinner. Just for clarity, the list of countries is just a list of countries, and the list of spots looks like:
Country1 - Spot1
Country1 - Spot2
Country2 - Spot1
Country2 - Spot2
And so on.
This is what I thought the code should work like:
Get selected country from spinner 1.
Make a new ArrayList containing the spots.
Make a second empty ArrayList.
For each entry of the ArrayList containing the spots, check if it starts with the selected country.
If so, add it to the second ArrayList.
Once this is all done, make an ArrayAdapter with the second ArrayList.
Set this ArrayAdapter for spinner 2.
I tried to achieve this with the following code:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selectedCountry = parent.getItemAtPosition(pos).toString();
ArrayList<CharSequence> arraylist = new ArrayList<CharSequence>();
arraylist.addAll(R.array.spots_array);
ArrayList<CharSequence> arraylist2 = new ArrayList<CharSequence>();
for (i=0; i<arraylist.size(); i++) {
String delimiter = " - ";
if ((arraylist(i).split(delimiter)).equals(selectedCountry)) {
arraylist2.add(arraylist(i).string.substring(string.lastIndexOf('-') + 1));
}
}
ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter.createFromResource(this, arraylist2<CharSequence>, android.R.layout.simple_spinner_item);
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(arrayAdapter2);
spinner2.setOnItemSelectedListener(this);
}
But it gives several errors:
At addAll() it says: "The method addAll(int, Collection) in the type ArrayList is not applicable for the arguments (int)"
At arraylist it says: "The method arraylist(int) is undefined for the type Configuration"
At string (inside substring) it says: "string cannot be resolved"
I am still relatively new to Android, and am having a lot of trouble getting this working. Can anybody please help me out?
There is a lot of little mistakes in your code :
To access an element in an arraylist use the get(position) method
When you add your "spot_array", you actually add the id of the resource, not the array itself (see here)
Here is your code updated, it should works or may need some tweaks
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selectedCountry = parent.getItemAtPosition(pos).toString();
List<CharSequence> arraylist = new ArrayList<CharSequence>();
arraylist.addAll(Arrays.asList(getResources().getTextArray(R.array.spots_array)));
List<CharSequence> arraylist2 = new ArrayList<CharSequence>();
String delimiter = " - ";
for (int i=0; i<arraylist.size(); i++) {
String country = arraylist.get(i).toString();
if (country.contains(selectedCountry)) {
arraylist2.add(country.substring(country.lastIndexOf('-') + 2));
}
}
ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter.createFromResource(this, android.R.id.text1, android.R.layout.simple_spinner_item);
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(arrayAdapter2);
spinner2.setOnItemSelectedListener(this);
}
You have several errors in your code.
Firstly, the method addAll of the ArrayList must take as an argument a Collection. You are passing an Android array id R.array.spots_array; bear in mind that the Android ids are integers.
The usually method to fetch a string array from Android resources is (inside an activity):
String[] myArray = getResources().getStringArray(R.array.spots_array);
Second error: you should access the ArrayList elements by calling the method get(position) , not directly (arraylist(position)). Something like arraylist.get(position).
Third error:
arraylist2.add(arraylist(i).string.substring(string.lastIndexOf('-') + 1));
should simply be arraylist2.add(arraylist.get(i)); for adding one list element to another.
More on ArrayLists can be found here.

Categories

Resources