I am trying to populate a list view with a select all query from a data base (1 Primary Key, and 4 attributes. what I have now is not throwing errors, but its not generating anything that is usable. Below is the query that I am using:
public List<SavedLocation> getAllLocationDescriptions() {
List<SavedLocation> locationList = new ArrayList<SavedLocation>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LOCATIONS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
SavedLocation location = new SavedLocation();
location.setLocation(cursor.getString(0));
// Adding locationt to list
locationList.add(location);
} while (cursor.moveToNext());
}
return locationList;
}
This is my list view activity. (note: the log output is writing the correct results, so that seems to be working)
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class SavedLocationsListTest extends ListActivity{
#Override
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent intent = getIntent();
DatabaseHandler db = new DatabaseHandler(this);
List<SavedLocation> test = db.getAllLocationDescriptions();
for (SavedLocation cn : test){
String log = "ID: "+ cn.getID()+ ", Location:" + cn.getLocation() + ", Accuracy:"+ cn._accuracy+ ", Description: " +cn._description+ ", Provider:" + cn.getProvider();
Log.d("Location: ", log);}
setListAdapter (new ArrayAdapter<SavedLocation>(this, R.layout.list_test,test));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
}
}
and this is my xml layout
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textView0"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</TextView>
and now as I said, I'm not getting errors, but I feel like what I am getting is even more frustrating; I have 4 records in my database and this is what I keep getting as the output when running the app:
com.example.gpstest1.SavedLocation#41eb8128
com.example.gpstest1.SavedLocation#41eb8218
com.example.gpstest1.SavedLocation#41eb8270
com.example.gpstest1.SavedLocation#41eb82c8
it looks like I'm able to populate the list view, I'm just doing it wrong.
The reason your TextViews are displaying information like com.example.gpstest1.SavedLocation#41eb8128 is that you haven't overriden the toString() method in your SavedLocation class.
The ArrayAdapter class has no idea how to convert your Java objects into a readable format. It can't read your mind and determine what a valid textual representation of a SavedLocation might be. The best it can do is call toString() on your object and hope for the best.
According to the Object.toString() documentation, the default implementation of toString() does this:
The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `#', and the unsigned hexadecimal representation of the hash
code of the object. In other words, this method returns a string equal
to the value of: getClass().getName() + '#' + Integer.toHexString(hashCode())
You have a few options. The easiest is to just override toString() in your SavedLocation and have it output what you want. This will work well if you really just want a single TextView to represent each entry.
If you want a more complicated layout, you will want to create your own ArrayAdapter subclass that overrides getView() to generate the appropriate View for each row in the ListView.
well I ended up changing:
#Override
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent intent = getIntent();
DatabaseHandler db = new DatabaseHandler(this);
List<SavedLocation> test = db.getAllLocationDescriptions();
for (SavedLocation cn : test){
String log = "ID: "+ cn.getID()+ ", Location:" + cn.getLocation() + ", Accuracy:"+ cn._accuracy+ ", Description: " +cn._description+ ", Provider:" + cn.getProvider();
Log.d("Location: ", log);}
setListAdapter (new ArrayAdapter<SavedLocation>(this, R.layout.list_test,test));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
to:
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
Intent intent = getIntent();
displayList();
}
public void displayList(){
Cursor cursor=db.getAllLocationsCursor();
String from [] = new String[] {db.COLUMN_DESCRIPTION, db.COLUMN_LOCATION, db.KEY_ID};
int to [] = new int[]{R.id.textView1, R.id.textView2, R.id.textView3 };
dataAdapter = new SimpleCursorAdapter(this, R.layout.row_item, cursor, from, to, 0);
ListView lv = getListView();
lv.setAdapter(dataAdapter);
}
If I have the terminology correct, I'm using a "cursor adapter" to accomplish this...?
Related
It shows database first data, but i want to show all data which number is 3 column table of each row, and after it will open after click a button and open this list in a new activity
//Read Database
public void readDB(View v) {
SQLiteDatabase db2 = openOrCreateDatabase(" Result ", MODE_PRIVATE, null);
String strThree = "SELECT * FROM my_result";
Cursor c = db2.rawQuery(strThree, null);
c.moveToNext();
String grade = c.getString(c.getColumnIndex("Grade_Point"));
String ss = c.getString(c.getColumnIndex("Subject_Name"));
Toast.makeText(getApplicationContext(), " Subject Name is "+ss+" and Gragde point is"+grade , Toast.LENGTH_LONG).show();
}
Store the extracted values from your column 3 into a variable preferably in an arraylist. Then On the click of your button send it to your activity and populate your listview in that activity in the onCreate() method of that activity. Example below(Not tested)
ArrayList<String> col_3 = new ArrayList<String>();
void readDB(View v){
SQLiteDatabase db2 = openOrCreateDatabase(" Result ", MODE_PRIVATE, null);
String strThree = "SELECT * FROM my_result";
Cursor c = db2.rawQuery(strThree, null);
while(c.moveToNext()!=null){
col_3.add(c.getString(2)) //since 3rd column
}
}
Now on the onClick of your button send it to the destination activity via intents
Intent intent = new Intent(CurrentActivity.this, DestinationActivity.class);
intent.putStringArrayListExtra("col_3_data", col_3);
startActivity(intent);
onCreate() method of your destination Activity will be something like this
Intent i = new Intent();
ArrayList col_value =new ArrayList<String>();
col_value = i.getStringArrayListExtra("col_3_data");
ListView lv = (ListView)findViewById(R.id.my_lsitview); //my_listview is your listview where you want to display your data
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, col_value );
lv.setAdapter(arrayAdapter);
I suggest instead of creating a new activity, you can create a dialog with listview, follow one of the following tutorials:
http://envyandroid.com/creating-listdialog-with-images-and-text/
http://www.edumobile.org/android/custom-listview-in-a-dialog-in-android/
I am trying to get saved values in a list. I am creating anotepad and I want when anybody open notepad every saved list display on homepage in a list.
I have successfully saved the value in a database but when I am trying to get a value in a list it is giving full string value like this "com.todo.task.activity#4106a690" in every single row.
I think problem is in my database getlist() method please check:
public List<TaskDetailsActivity> GetAddTaskLists() {
List<TaskDetailsActivity> TaskLists = new ArrayList<TaskDetailsActivity>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TASKLISTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
TaskDetailsActivity tasks = new TaskDetailsActivity();
tasks.settaskLists_ID(cursor.getString(0));
tasks.settasklists_Title(cursor.getString(1));
// Adding Doc to list
TaskLists.add(tasks);
} while (cursor.moveToNext());
}
// return Doc list
return TaskLists;
}
Here I am calling database method like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView list_tasklistname = (ListView)findViewById(R.id.list_tasklistname);
TaskManager_Database db = new TaskManager_Database(getApplicationContext());
list = db.GetAddTaskLists();
ArrayAdapter<TaskDetailsActivity> adapter = new ArrayAdapter<TaskDetailsActivity>(getApplicationContext(),
android.R.layout.simple_list_item_1, list);
list_tasklistname.setAdapter(adapter);
adapter.notifyDataSetChanged();
Please let me know what is the error. Thanks
You are getting object representation of objects been added to ListView...
In your case you should return data in cursor.getString(1) for adapter input param i.e. String array...... i.e list must be a string array or ArrayList... if you know what I mean..
check out this sample for ref
Your TaskDetailsActivity class should define a toString() method that returns whatever you want to display for that row.
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
}
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.
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();
}
};