Displaying List View on Button Click in Android - 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>

Related

Android new Intent not responding after ListView

I wanted to devise some intents between two activities. I passed the intent without declaring anything . I wanted to define Adapter to inflate listview in the intent but I came across the issue when the intent is opened . It is caused by listview. How can I solve it out?
Here are the code below.
public class AttactivePlacesActivity extends AppCompatActivity {
ArrayList<City> c = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a);
MainActivity m = new MainActivity();
c = m.mArraylist;
AAdapter r = new AAdapter(this,c,R.color.mainBackground);
ListView listView = (ListView) findViewById(R.id.aa);
listView.setAdapter(r);
}
}
R.layout.a
<?xml version="1.0" encoding="utf-8"?>
<ListView 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"
android:id="#+id/aa"
tools:context="com.example.android.tourguide.AttactivePlacesActivity">
</ListView>
gridview Intent
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
switch (position){
case 0:
Toast.makeText(getApplicationContext(),"A",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this,AttactivePlacesActivity.class);
startActivity(intent);
break;
}
}
});
You create a reference of MainActivity to get the mArrayList, don't you? Firstly, pls don't create any reference of an activity in another one. Secondly, if you want to get the mArraylist in the second activity, just put it in intent like this:
intent.putSerializable("My array",mArrayList);
and receive it by using:
c = getIntent.getSerializable("My array");
P/S: Some advices for you, please name the variable by the meaningful name, try to learn the OOP java carrefully before starting with Android. And the last one, searching before asking

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".

Multiple ListViews, with same content, on different layouts

Multiple ListViews, with same content, on different layouts
So basically what I have is two ListViews that are getting their content from SQLite DB. I have created a BaseActivity below to extend my other activities to access the same data. The problem I ran into is that I cannot display the data because their are two different layout that contain these ListViews, one in a Dialog and the other in a TabWidget, that are both in separate activities.
So basically....
I need to know how to display two ListViews with the same data that are in different activities (one in dialogBox and the other in TabWidget)
The error I am currently getting is from the layout in the SimpleCursorAdapter is only for one of the ListViews and it wont add the other because it cannot find the View
I am not extending ListActivity at any point
Thank you very much in advance. I will be standing by to edit or clarify.
Part of my Base Activity
public class BaseActivity extends Activity
{
private SimpleCursorAdapter contactAdapter;
public static final String ROW_ID = "row_id";
private static ListView study_guide_list_view;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
String[] from = new String[] { "name" };
int[] to = new int[] { R.id.study_guide_item_in_listview };
contactAdapter = new SimpleCursorAdapter(BaseActivity.this, R.layout.study_guide_item_in_listview, null, from, to);
}
}
This segment is where I add the ListView to the TabWidget and it is currently working
study_guide_list_view = (ListView) findViewById(R.id.list);
contactAdapter = getSimpleCursorAdapter();
study_guide_list_view.setAdapter( contactAdapter );
study_guide_list_view.setOnItemClickListener(listview_item_listener);
Where I am trying to add the ListView in the Custom Dialog Box (does not work: error is on study_guide_dialog_list_view.setAdapter( contactAdapter ); )
public OnClickListener save_slide_page_to_guide_btn_listener = new OnClickListener()
{
#Override
public void onClick(View v)
{
TabbedPagesActivity.getListViewAdapter();
dialog = new Dialog(PDFViewerActivity.this);
dialog.setContentView(R.layout.study_guide_custom_dialog_box);
dialog.setTitle("Select a Study Guide");
dialog.setCancelable(true);
study_guide_dialog_list_view = (ListView) findViewById(R.id.list);
contactAdapter = getSimpleCursorAdapter2();
study_guide_dialog_list_view.setAdapter( contactAdapter );
study_guide_dialog_list_view.setOnItemClickListener(listview_item_listener);
Button dialog_ok_btn = (Button) dialog.findViewById(R.id.dialog_ok_btn);//it says cancel though
dialog_ok_btn.setTextSize(20);
dialog_ok_btn.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/AGENCYR.TTF"));
dialog_ok_btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.dismiss();
}
});
dialog.show();
}
};
Wow so I finally figured it out. The problem lies within the custom Dialog. Instead of calling...
study_guide_dialog_list_view = (ListView) findViewById(R.id.list);
it needs to be....
study_guide_dialog_list_view = (ListView) dialog.findViewById(R.id.list);
If you do not do this the findViewById will return null, hence the NullPointerException

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.

Launching a ListActivity from another Activity

I am creating an application that saves GPS coordinates; I have created a button which launches a new Activity to display, as a list all the save coordinates. The program crashes a soon as I hit the button, here is what I am doing.
class 1:
public void openLatLonData(View view)
{
Intent intent = new Intent(this, GpsDataList.class);
ArrayList<String> allLocalStrings = new ArrayList<String>();
for(int i =0; i< AllLocals.size();i++)
{
allLocalStrings.add(AllLocals.get(i).getLat());
allLocalStrings.add(AllLocals.get(i).getLon());
}
intent.putStringArrayListExtra("data", allLocalStrings);
startActivity(intent);
}
This method calls the new activity:
public class GpsDataList extends ListActivity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle bundleIn)
{
super.onCreate(bundleIn);
Intent intent = getIntent();
ArrayList<String> listData = new ArrayList<String>();
listData = intent.getStringArrayListExtra("data");
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listData));
getListView().setTextFilterEnabled(true);
//finish();
}
}
the button contains the following XML:
<Button android:layout_height="wrap_content"
android:text="Show Collected Data"
android:id="#+id/view_lat_lon_data"
android:layout_width="wrap_content"
android:onClick="openLatLonData">
</Button>
And I have added a new .xml file named gpsdatalist.xml under the res/layout folder:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>
Lastly the manifest contains this: .
I believe I have all the pieces in play- Hopefully someones see the mistake
Thanks in advance guys!
Did you define the activity in the AndroidManifest.xml file?
Anyway, your best clue resides in the logcat of your exception. You will solve it in 2 seconds after cheking the logcat.

Categories

Resources