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".
Related
So I want to create a listview that consists of more than a column. I already succeed called the database, but the layouting still not work. I think this is because the all my data are put in one array and its difficult to make them in three columns. anyone can find solution for me?
My program result is like this in listview:
John Doe 12 Argentina
Marilyn Rose 32 Russia
Annabella 19 United States
However what I want is more like this:
John Doe 12 Argentina
Marilyn Rose 32 Russia
Annabella 19 United States
From what I read, we will need 2 XMLs. One for listview, and another is for layouting (give space between text). And One .JAVA called adapter to connect my MainActivity.java and layouting XML.
add:
I already tried using two XMLs. one XML, lets call it main.XML is for calling ListView. And grid.XML, is where i put android:layout_alignParentLeft="true" (to create spaces).
I used MyAdapter.JAVA to convertview in grid.XML. and in MainActivity.JAVA i called MyAdapter. However my code in MainActivity became error when its connected it MyAdapter.
this was my code that gave error java.lang.RuntimeException. So I had to delete it.. more information about it, please check two last code...
MainActivity.java (error)
public static ArrayList<String> arraydealer = new ArrayList<String>();
MyAdapter bohwat = new MyAdapter(MainActivity.this, arraydealer);
lvcustom.setAdapter(bohwat);
And here is the code that is working well. It uses class MainActivity, AstraDB, and MySetGet, and main.XML. Other class thats not working is MyAdapter and grid.xml
This is how I called my database:
public class MainActivity extends Activity
{
public static ArrayList<String> arraydealer = new ArrayList<String>();
AstraDB astrahandler = new AstraDB(this);
Spinner spDealer;
ListView lvcustom;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvcustom = (ListView)findViewById(R.id.custom_lv);
ShowListView();
}
private void ShowListView()
{
astrahandler.getAllDealer();
ArrayAdapter<String> adapt = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, arraydealer);
lvcustom.setAdapter(adapt);
}
}
This code of ArrayList in Activity and String name in AstraDB are very important to connect my MainActivity with the database but it seems this create trouble in layouting. because they are contained in ONE array
And this is function to get all data in my DB. its on AstraDB.java:
public List<MySetGet> getAllDealer()
{
List<MySetGet> info = new ArrayList<MySetGet>();
db = DBHelper.getReadableDatabase();
// Select All Query
String selectQuery = "SELECT * FROM Dealer";
cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
MySetGet lets = new MySetGet();
lets.setDealerID(Integer.parseInt(cursor.getString(0)));
lets.setDealerName(cursor.getString(1));
lets.setDealerOwner(cursor.getString(2));
lets.setDealerWil(cursor.getString(3));
String name = cursor.getInt(0) +
"\u00A0 "+ cursor.getString(1)+
"\u00A0 "+ cursor.getString(2)+
"\u00A0 "+ cursor.getString(3);
MainActivity.arraydealer.add(name);
//add
info.add(lets);
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
//return contentdealer;
return info;
}
The MySetGet in getAllDealer() connects with MySetGet.java where I put setter and getter so the data can become object. which is more like this:
public int getDealerID(){ return DealerID;}
public void setDealerID(int DealerID) { this.DealerID = DealerID; }
Code to connect other XML with Java but still gave error:
grid_dealer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_height="wrap_content"
android:layout_width="50dp"
android:id="#+id/col1"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text=""/>
<TextView
android:layout_height="wrap_content"
android:layout_width="100dp"
android:id="#+id/col2"
android:layout_toRightOf="#id/col1"
android:layout_centerVertical="true"
android:text=""/>
important code in MyAdapter.java:
public class MyAdapter extends BaseAdapter
{
Context context;
ArrayList<MySetGet> dealerlist;
public MyAdapter(Context context, ArrayList<MySetGet>list)
{
this.context = context;
dealerlist = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
MySetGet yay = dealerlist.get(position);
//this is to customize the layout of the listview
if(convertView == null)
{
LayoutInflater inflater = null;
inflater = (LayoutInflater)context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grid_dealer, null);
}
TextView tvID = (TextView)convertView.findViewById(R.id.col1);
tvID.setText(yay.getDealerID());
TextView tvName = (TextView)convertView.findViewById(R.id.col2);
tvName.setText(yay.getDealerName());
TextView tvOwner = (TextView)convertView.findViewById(R.id.col3);
tvOwner.setText(yay.getDealerOwner());
return convertView;
}
}
Please help me. I am very new to this. Is there a way to modify my code without changing too much on how I called my database? The class and XML below works fine in showing database, but didnt create a neat layout space between columns
Working class : AstraDB, MainActivity, MySetGet
Working XML : main.xml
Im sorry, if the post becomes longer. I want to clarify several things so that there is no misunderstanding.
you can use android:layout_weight="" for better arrangement of views
Using SimpleCursorAdapter is the ideal solution in your case. Please checkout a tutorial here that will take you through the steps in achieving what you want.
In simple_list_item_1 layout if you arrange items relative to each other you will get the result what you are getting now. If you want proper formatting, relate the elements to left, center and right using android:layout_alignParentLeft="true", android:centerHorizontal="true" and android:layout_alignParentRight="true" respectively
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};
I am filling a listview from names of a database. That is all working fine. After clicking on an Listitem with the name i would like to set the onListItemClickto fill out textviews in another activity. That is where i am stuck.
Here the code of my listview activity which is working:
public class DataListView extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private SQLiteDatabase newDB;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hotelslist);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
ListView hotelslist = (ListView) findViewById(android.R.id.list);
hotelslist.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Toast.makeText(getBaseContext(), l.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
}
private void openAndQueryDatabase() {
try {
DataBaseHelper newDB = new DataBaseHelper(this, "mydatabase.sqlite");
SQLiteDatabase sdb = newDB.getReadableDatabase();
Cursor c = sdb.rawQuery("SELECT name FROM hotel ORDER BY name ASC", null);
if (c != null ) {
if (c.moveToFirst()) {
int i = 0;
do {
i++;
String name = c.getString(c.getColumnIndex("name"));
results.add(name);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.close();
}
}
}
Besides the name the table also contains columns "address" and "telephone". This data i would like to be filled in textviews "addressfill" and "telephonefill" of another activity with following xml:
<?xml version="1.0" encoding="utf-8"?>
<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:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Address" />
<TextView
android:id="#+id/addressfill"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/telephone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Telephone number" />
<TextView
android:id="#+id/telephonefill"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
I tried to read into many tutorials out there and many posts here but didnt get around to found the right answer.
What code would i have to use for the onListItemClick and in my activity that uses the xml I presented. Help is very appreciated!
If you want to set up listeners on list items, you will need to extend array adapter and put the listener code in the adapter:
public class SettingsListAdapter extends ArrayAdapter<String> {
#Override
public View getView(int position, View convertView, ViewGroup parent){
// put your listener in here
mybutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do work here
}
}
}
In other words, the simplelistadapter is not sufficient to do want you want, you will need to create your own.
edit
Here's a good example of creating your own custom ArrayAdapter: Custom Array Adapter Tutorial
In onListItemClick() create an Intent and put the name in the Intent:
Intent intent = new Intent(DataListView.this, SecondActivity.class);
intent.putExtra("name", l.getItemAtPosition(position).toString());
startActivity(intent);
You must change SecondActivity to the class name of the Activity that will receive the name.
In this second Activity's onCreate(), read the String:
String name = getIntent().getStringExtra("name");
if(name != null) {
// Do something with the name, like selecting the address
// and telephone number from your database to display
}
However since you are working with a database you really should use a SimpleCursorAdapter. Working with a Cursor is more useful and efficient.
how can i do it for the other columns data of the table like address and telephone?
You have two options:
In your second Activity use a query like:
"SELECT address, telephone FROM Hotel WHERE name = '" + name + "'"
But if multiple hotels have the same name, you will get more than one address...
Change your query in your first Activity to:
"SELECT name, address, telephone FROM Hotel ORDER BY name"
Now in onListItemClick() you can pass the name, address, and telephone number all at once, but you will need to store the address and telephone number somewhere... This is where a SimpleCursorAdapter is extremely useful.
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.
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>