CursorAdapter not showing any data in ListView - android

This is my code For activity.I have just begun to learn android.
And i am not able to get any data through the SimpleCursorAdaptor on my ListView
When I m using the ArrayAdaptor then i am able to get data on the ListView but not With Simple Cursor Adaptor
public class LaunchActivity extends Activity {
ListView taskList;
SQLiteDatabase db ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch);
// Log.d("Anuranjit", "IN activity");
taskList = (ListView) findViewById(R.id.TaskList);
taskList.setDividerHeight(7);
TaskDatabaseManager taskManager = new TaskDatabaseManager(
getApplicationContext());
db = taskManager.getWritableDatabase();
addData();
Cursor c=db.rawQuery("Select * from "+TaskDatabaseManager.DATABASE_TABLE, null);
c.moveToFirst();
String[] fromCol={TaskDatabaseManager.KEY_ROWID,TaskDatabaseManager.TASK_DESCRIPTION,TaskDatabaseManager.TASK_STATUS,TaskDatabaseManager.TASK_TIMESTAMP};
int[] v={R.id.TaskList,R.id.TaskList,R.id.TaskList,R.id.TaskList};
SimpleCursorAdapter sa=new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1 ,c,fromCol,v,0);
taskList.setAdapter(sa);
}
public void addData(){
Date c=new Date();
db.execSQL("insert into "+TaskDatabaseManager.DATABASE_TABLE+"( "+TaskDatabaseManager.TASK_DESCRIPTION+","+TaskDatabaseManager.TASK_TIMESTAMP +","+TaskDatabaseManager.TASK_STATUS+") values ('Hello World',' "+(new Timestamp(c.getTime()))+" ' ,'0');");
Cursor ac=db.rawQuery("Select * from "+TaskDatabaseManager.DATABASE_TABLE, null);
ac.moveToFirst();
Toast.makeText(getApplicationContext(), String.valueOf(ac.getCount()), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), ac.getString(1), Toast.LENGTH_LONG).show();
}
}
Launcher activity layout.I only have a list view in the XML is this the problem ?
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LaunchActivity" >
<ListView
android:id="#+id/TaskList"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:divider="#android:color/holo_green_light" >
</ListView>

This line is your problem.
int[] v={R.id.TaskList,R.id.TaskList,R.id.TaskList,R.id.TaskList};
You have to map the values from your cursor to Textfields in your list item layout. Not in your layout that countains the list view.
Atm you are using a generic layout for your list items (android.R.layout.simple_list_item_1)
Try making your own. (simple xml layout containing 1 TextView for every value you want to display) Then:
SimpleCursorAdapter sa=new SimpleCursorAdapter(this,R.layout.my_list_item ,c,fromCol,v,0);
and
int[] v={R.id.textView1,R.id.textView2,R.id.textView3,R.id.textView4};

Related

View data from SQLite database using ListView on Android

I am quite new to Android development. I managed to get data saved to SQLite database. Now, what I want is to view these data when I call viewData(). I have viewData() which shows data as a Toast as I made it as a sample. Now I need these data to show on a new activity using a ListView, but the number of data to show is depending on how many data is in the database at the moment, If user saved 10 items then I want all the 10 items to shown up. How can I do it?
I hope my question is clear.
Thanks in advance.
you could use ListView
declare it in your layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</LinearLayout>
in yor activity declare a globar var:
ListView listView;
and onCreate
listView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id){
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
}
});
datos can be an array that you can populate with data that you extract from your data base and that's the most simple way to show it. if you want to customizise your listView you can create a custom adapter, or in other way the newest element that replace listView is ReciclerView. I hope tihs help you
You can use a SimpleCursorAdapter:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView answerList=(ListView)findViewById(R.id.answerList);
Cursor mCursor = getData();
startManagingCursor(mCursor);
// now create a new list adapter bound to the cursor.
// SimpleListAdapter is designed for binding to a Cursor.
ListAdapter adapter = new SimpleCursorAdapter(this, // Context.
android.R.layout.two_line_list_item,
mCursor, // Pass in the cursor to bind to.
// Array of cursor columns to bind to.
new String[] {"_id", "answer"};
// Parallel array of which template objects to bind to those
// columns.
new int[] { android.R.id.text1,android.R.id.text2 });
// Bind to our new adapter.
answerList.setAdapter(adapter);
}
private Cursor getData() {
String sq = "Select _id, answer from foo";
Cursor c = db.rawQuery(sql);
return c;
}
I will try to give an in-depth answer to this.
Whenever you want to fetch and display a list of data from the database, you can use a ListView, GridView, Spinner, etc for it.
You can use a CursorAdapter which can make the job of querying and displaying data much more simple and easy.
Here is a basic visual representation of it,
Step 1
Firstly, you need to create a database. As mentioned in your question, it is clear that you know how to create a database and put some data into it. So I am not going into the depths of it.
Step 2
We need to define the layout to be used for the individual items in the ListView and save it as res/layout/item_todo.xml This is just a sample layout, you can design any kind of layout you want to.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Study cursors"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvPriority"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="3"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Step 3
Now we need to define an adapter. Here we are using a CursorAdapter which converts a Cursor (that you provide) into Views (defined by your layout).
There are two methods, newView and bindView which we need to override. The newView is responsible for inflating newViews for the first time and the bindView is responsible for binding the data to the Views.
public class TodoCursorAdapter extends CursorAdapter {
public TodoCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_todo, parent, false);
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.tvBody);
TextView tvPriority = (TextView) view.findViewById(R.id.tvPriority);
// Extract properties from cursor
String body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
int priority = cursor.getInt(cursor.getColumnIndexOrThrow("priority"));
// Populate fields with extracted properties
tvBody.setText(body);
tvPriority.setText(String.valueOf(priority));
}
}
Step 4
Now as you can clearly see, that the constructor needs a Context and a Cursor. Now we need to query the database and retrieve the data into a Cursor and pass it to the adapter.
// TodoDatabaseHandler is a SQLiteOpenHelper class connecting to SQLite
TodoDatabaseHandler handler = new TodoDatabaseHandler(this);
// Get access to the underlying writeable database
SQLiteDatabase db = handler.getWritableDatabase();
// Query for items from the database and get a cursor back
Cursor todoCursor = db.rawQuery("SELECT * FROM todo_items", null);
Step 5
This is the last step where we need to instantiate the adapter and attach the ListView with the adapter to populate the data.
// Find ListView to populate
ListView lvItems = (ListView) findViewById(R.id.lvItems);
// Setup cursor adapter using cursor from last step
TodoCursorAdapter todoAdapter = new TodoCursorAdapter(this, todoCursor);
// Attach cursor adapter to the ListView
lvItems.setAdapter(todoAdapter);

List view is not getting displayed

Hi I have created a simple application for displaying contents from database to list view, but my list view is not displaying any data I am a beginner and I need some assistance.
Giving my list view class below
public class Show extends Activity {
//SQLiteDatabase db;
//Datahelper dh;
Context context=this;
Dataclass dc;
private ListView mainListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.show);
mainListView=(ListView)findViewById(R.id.list);
//getDetails();
dc=new Dataclass(this);
Bundle bundle=getIntent().getExtras();
String message=bundle.getString("MSG");
List<String> friendlist=dc.getDetails(message);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_activated_1,friendlist);
mainListView.setAdapter(adapter);
}
public void onDestroy() {
super.onDestroy();
dc.close();
}
}
I have passed data from one activity to this activity using bundle and I have got the data , but no data is retrieved from the database..
giving m y getdetails function from dataclass below
public List<String> getDetails(String message) {
List<String> Friendlist = new ArrayList<String>();
String selectQuery="SELECT * FROM Mytables WHERE Name='" + message + "' ";
db = dh.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
while(cursor.moveToNext()) {
Friendlist.add(cursor.getString(1));
}
return Friendlist;
}
giving my xml layout for list activity below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
try set listview's background color to red, see it is NO-CONTENT or DIDN'T DISPLAY.
From your layout I can see that you don't have an ListView element with id "list" mainListView=(ListView)findViewById(R.id.list);. Since all the operations you are running assume the existence of this element, probably this is the reason why nothing appears on the screen.
I also suggest that instead of inheriting from Activity you should inherit from ListActivity and use existing methods to deal with ListView like getListView(), setListAdapter(adapter) and keep your ListView with the default id android:id="#android:id/list".

Why is first text view in list empty when populating the list from SQLite Database?

I am populating a list from an SQLite database which works fine but the first text view is always empty and I cannot figure out why. This is causing me issues because I use the populated text views to display information when clicked but as the first one is empty and can be clicked it is causes the program to fail. Here is my code:
public class ShowPhrases extends Activity implements OnInitListener {
SQLiteDatabase database;
NotesDbAdapter md;
CursorAdapter dataSource;
TextToSpeech tts;
private static final String fields[] = { "phrase", "folang",BaseColumns._ID };
NotesDbAdapter.DatabaseHelper helper = new NotesDbAdapter.DatabaseHelper(
this);
#Override
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.hs);
//Set volume buttons to music volume instead of ringer
setVolumeControlStream(AudioManager.STREAM_MUSIC);
tts = new TextToSpeech(this, this);
database = helper.getWritableDatabase();
Cursor data = database.query("notes", fields, null, null, null, null,null);
dataSource = new SimpleCursorAdapter(this, R.layout.highscores, data, fields, new int[] { R.id.first });
final ListView lv = (ListView) findViewById(R.id.list_view);
lv.setHeaderDividersEnabled(true);
lv.addHeaderView(getLayoutInflater().inflate(R.layout.highscores, null));
lv.setAdapter(dataSource);
The highscores xml layout:
android:orientation="vertical" >
<TextView
android:id="#+id/first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginTop="20dp"
android:focusable="false"
android:textColor="#357ae8"
android:textSize="20dp" />
</RelativeLayout>
The hs xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/gerback"
android:orientation="vertical" >
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
Can anyone see why this is happening?
Try this:
Cursor data = database.query("notes", fields, null, null, null, null,null);
data.moveToNext();
dataSource = new SimpleCursorAdapter(this, R.layout.highscores, data, fields, new int[] { R.id.first }, 0);
Does it works?
Remember to add 0 as last parameter to use the non deprecated method.
When you say that the first Textview is empty, are you talking about the headerview or the first item in the list?
If you mean the headerview, and the first piece of xml (in your question) is the one being inflated into it (R.layout.highscores), then the problem is simply that you haven't assigned it any text to display. The headerview isn't populated by the adapter, and it scrolls with the list, so it will be blank in your case.

ListView inside LinearLayout no longer reacts to OnclickListener

I am designing a simple app from tutorials that I have seen, and I am attempting to simply display two text views in each row of a listview, a name and a price. This worked and I could select the row and it would activate an intent. However I then changed my xml code so that the listview would be placed in a linearLayout in order for me to have a header at the top of the screen. Now when I click on any of the rows they are highlighted but nothing else happens. I have already tried to making the textviews set to clickable = false in the xml but still no luck. I am hoping I am just missing something simple in the onCreate method. `public class ViewMenuListing extends ListActivity {
public static final String ROW_ID = "row_id"; // Intent extra key
private ListView contactListView; // the ListActivity's ListView
private CursorAdapter contactAdapter; // adapter for ListView
private String tableName;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
contactListView = getListView(); // get the built-in ListView
contactListView.setOnItemClickListener(viewContactListener);
setContentView(R.layout.viewmenu);
//Get table name of menu clicked.
Bundle extras = getIntent().getExtras();
tableName = extras.getString("table");
// map each contact's name to a TextView in the ListView layout
String[] from = new String[] { "name", "price" };
int[] to = new int[] { R.id.itemTextView, R.id.priceTextView };
//int[] to = new int[] { R.id.itemTextView};
contactAdapter = new SimpleCursorAdapter(
ViewMenuListing.this, R.layout.menu_list_item, null, from, to);
setListAdapter(contactAdapter); // set contactView's adapter
}`
The only thing I changed in this code was that I used the setContentView(R.layout.viewmenu) now when I didnt before and the list would just be the content view.
Here is my viewMenu file:
`
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello" />
<ListView
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>`
and my menu_list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemTextView"
android:padding="8dp"
android:clickable = "false"
android:textSize="20sp" android:textColor="#android:color/white"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/priceTextView"
android:clickable = "false"
android:textColor="#android:color/white"/>
</LinearLayout>
Thank you for your help!
Looks like you are explicitly setting an onItemClickListener for your ListView. This really isn't necessary since you are extending ListActivity and ListActivity has a method you can override called onListItemClick(). I would override the onListItemClick() method instead of explicitly setting an onItemClickListener. http://developer.android.com/reference/android/app/ListActivity.html#onListItemClick(android.widget.ListView, android.view.View, int, long)
Please correct following things
contactListView = getListView(); and setListAdapter(contactAdapter);
The above syntax can be only used if your class is extending ListActivity .In your case you are extending Activity,So above Approach will not work.
Your menu_list_item.xml looks perfectly fine to me.
in viewmenu.xml file make following correction while specifying id for listview.
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Please see to this corrected code.
public class SampleActivity extends ListActivity
{
public static final String ROW_ID = "row_id"; // Intent extra key
private ListView contactListView; // the ListActivity's ListView
private CursorAdapter contactAdapter; // adapter for ListView
private String tableName;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
contactListView = (ListView) findViewById(R.id.list); // get the
// built-in
// ListView
contactListView.setOnItemClickListener(this);
setContentView(R.layout.viewmenu);
Bundle extras = getIntent().getExtras();
tableName = extras.getString("table");
// map each contact's name to a TextView in the ListView layout
String[] from = new String[]
{ "name", "price" };
int[] to = new int[]
{ R.id.itemTextView, R.id.priceTextView };
contactAdapter = new SimpleCursorAdapter(SampleActivity.this,
R.layout.menu_list_item, null, from, to);
contactListView.setAdapter(contactAdapter);
}
#Override
public void onListItemClick(AdapterView<?> adapterView, View view,
int position, long arg3)
{
}
}
Now in onListItemClick method you can write whatever logic you want.
Hope this help.

Displaying List View on Button Click in Android

I am creating an android application in which there are two activites. One activity contains a button. On the button click, i want to switch to other activity which displays a list view containing few options.
Two switch between the screens or activities , i am using the following code
Intent intent = new Intent(Activity1.this,Activity2.class);
startActivity(intent);
Since my Activity2 class extends the 'ListActivity', this code doesn't seem to work. On my button click, i want to display a list view containing some data.
Any help would be appreciated
#Siddharth
i seem to be doing almost the same thing
Here is my actual code
From Activity 1
public void onClick(View v) {
Intent intent = new Intent(View_Data.this,CategoryList.class);
startActivity(intent);
}
In Activity 2
public class CategoryList extends ListActivity {
public TextView selection;
public String[] categories;
ArrayList<String> type_of_category;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list);
getCategories();
}
public void getCategories() {
DBHelper dbhelper = new DBHelper(this);
type_of_category = new ArrayList<String>();
type_of_category = dbhelper.getTypesOfQuotes();
String[] items = new String[100];
for(int i=0;i<type_of_type_of_category.size();i++)
{
items[i] = type_of_type_of_category.get(i);
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,items));
}
}
Here is my XML File
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>
In My 2nd Activity, i get the error in this line
setContentView(R.layout.category_list);
Depending on whether your data in the second activity is from a database or static data, this code should work for you. I am assuming from your post that you dont need to send data from the 1st activity to the 2nd activity. This is actual code from my application which is database driven. If you are not using a database, parts of this code can be changed to use that instead of a database. It should get you started:
From the 1st Activity:
public void onClickListContacts(View target)
{
Intent listContacts = new Intent(this, com.dzinesunlimited.quotetogo.ContactsList.class);
startActivity(listContacts);
}
The 2nd activity:
public class ContactsList extends ListActivity {
DBAdapter dbContactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_list);
dbContactList = new DBAdapter(this);
// Calls the method to display the ListView of all Contacts
fillData();
}
private void fillData() {
// Pull the data from the database
String[] fields = new String[] { dbContactList.TABLE_CON_NAME };
int[] views = new int[] { android.R.id.text1 };
Cursor c = dbContactList.getAllContacts();
startManagingCursor(c);
// Set the ListView
ListAdapter prjName = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, c, fields, views);
setListAdapter(prjName);
dbContactList.close();
}
For a static list, you can also refer to this tutorial: http://www.vogella.de/articles/Android/article.html#lists
Hope this helps.
PS: It would be great help if you could post code of the 2nd activity which has problems.
Add this to your XML and see if that helps:
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
</ListView>

Categories

Resources