I am trying to set up an OnItemClickListener for a ListView that was created inside of the main activity (extending Activity). The following code is not firing. Why isn't the onItemClick running?
Main.java
import java.io.InputStream;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class Main extends Activity {
/** Called when the activity is first created. */
List<Title> titleList;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set list view
setContentView(R.layout.listview);
setTitle("TITLE");
// Create Parser for raw/countries.xml
TitleParser titleParser = new TitleParser();
InputStream inputStream = getResources().openRawResource(R.raw.titles);
// Parse the input stream
titleParser.parse(inputStream);
// Get Titles
titleList = titleParser.getList();
// Create a customized ArrayAdapter
TitleArrayAdapter adapter = new TitleArrayAdapter(
getApplicationContext(), R.layout.title_listitem, titleList);
// Get reference to ListView holder
lv = (ListView) this.findViewById(R.id.titleLV);
// Set the ListView adapter
lv.setAdapter(adapter);
// on list item click
AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Title title = (Title) lv.getItemAtPosition(position);
try{
Class<?> challengeClass = Class.forName("com.glvangorp.app.TITLECHALLENGE");
Intent challengeIntent = new Intent(Main.this, challengeClass);
challengeIntent.putExtra("challenge", title.challenge);
challengeIntent.putExtra("title", title.resourceId);
startActivity(challengeIntent);
} catch(ClassNotFoundException e){
Log.d("TAG", e.getMessage());
e.printStackTrace();
}
}
};
lv.setOnItemClickListener(listener);
}
}
listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="#+id/titleLV"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>
one reason one not calling is the list item has been set to clickable false. or on the list item you have set some click or touch listener with return true ( make it to return false if you have written).
Maybe it is getting called but you are just getting an ClassNotFoundException thus, you don't know if it doing anything in the OnItemClick ... Why don't you put a Log.d("TAG", e.getMessage); inside the
catch clause.
Related
I get how to do this for a simple ListView, something like:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
But whenever I do it in my activity I get a nullpointerexception.
Could someone please show me how it is supposed to be? Thanks!
EDIT: I'm sorry! Didn't want to fill up an entire question only with code, I think it's necessary in this case, so I'm putting my entire java code below:
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class Save extends ListActivity {
String FileName;
EditText et;
String listItem[]={};
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_save);
Button save = (Button) findViewById(R.id.SAVE); //this is my button
final EditText title = (EditText) findViewById(R.id.save_filename); //This is unused
final EditText maintext = (EditText) findViewById(R.id.test);
getActionBar().setDisplayUseLogoEnabled(false);
getActionBar().setDisplayHomeAsUpEnabled(true);
et = (EditText) findViewById(R.id.save_filename);
listView = (ListView) findViewById(R.id.list); //I've specified this listView only for the OnItemClickListener action
List values = new ArrayList();
for (int i = 0; i < listItem.length; i++) {
values.add(listItem[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
FileName = et.getText().toString() + ".txt";
FileOutputStream fout = openFileOutput(FileName, Context.MODE_PRIVATE);
OutputStreamWriter outsw = new OutputStreamWriter(fout);
try {
outsw.write(String.valueOf(maintext));
outsw.flush();
outsw.close();
Toast.makeText(getBaseContext(), "Your file has been saved", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();
String device;
switch (view.getId()) {
case R.id.SAVE:
List myList = new ArrayList();
device = et.getText().toString();
myList.add(device);
adapter.add(device);
et.setText("");
break;
}
adapter.notifyDataSetChanged();
}
});
//I think this is wrong, I get no error in Java by the way. How could this work if there's a specific extension for my activity that define the listview? **That's my question**.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});
}
And the xml:
<Button
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/SAVE"
android:text="#string/save_button" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/save_filename"
android:layout_alignRight="#+id/linearLayout"
android:hint="#string/save_hint"
android:layout_alignEnd="#+id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="5dp" />
<ListView
android:id="#android:id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_above="#+id/linearLayout"
android:layout_below="#+id/save_filename">
</ListView>
Sorry again for the cunfusion!!
The problem here comes from the fact that you are using ListActivity instead of Activity. For this reason the ListView's ID is not added to the R file so it is not callable by the findById call. This would not happen if Activity were used. When using ListActivity you can use the built in getListView() method to get the ListView object.
Also when I ran your given code I got an error that a listView had to be defined by the ID list. This comes from an error in your XML file when you defined the ID.
Below I posted two sections from your given XML
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/save_filename"
<ListView
android:id="#android:id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_above="#+id/linearLayout"
android:layout_below="#+id/save_filename">
</ListView>
Notice when defining the id, the top one says android:id="#+id/save_filename" while the bottom says android:id="#android:id/list". Also when you use save_file_name it is done like thisandroid:layout_below="#+id/save_filename"This is incorrect. To define an id you use#+id`. This should be done the first time an element is referenced. It tells android to generate a value for it in R.java. Errors like this in your XML can cause your R.java file to not be generated and lead to different problems but I think the extra pluses on the ids are forgivable.
I was getting the error because of how you defined the id for layout. Instead it should look more like this
android:id="#+id/android:list"
Notice the + to create a new id and because I am using ListActivity I also must define it as android:list instead of just list.
I changed your XML to this:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/save_filename"
android:layout_alignRight="#+id/linearLayout"
android:hint="save here"
android:layout_alignEnd="#id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="5dp" />
<ListView
android:id="#+id/android:list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_above="#id/linearLayout"
android:layout_below="#id/save_filename">
</ListView>
Here is some corrected code, I noted what I changed.
package com.example.sosandbox;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class Save extends ListActivity {
String FileName;
EditText et;
//Added some test values
String listItem[]={"1","2","3","4","5"};
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_save);
Button save = (Button) findViewById(R.id.SAVE); //this is my button
// This is unused so I commented it out
// final EditText title = (EditText) findViewById(R.id.save_filename); //This is unused
final EditText maintext = (EditText) findViewById(R.id.save_filename);
getActionBar().setDisplayUseLogoEnabled(false);
getActionBar().setDisplayHomeAsUpEnabled(true);
et = (EditText) findViewById(R.id.save_filename);
// This is your issue.
// listView = (ListView) findViewById(R.id.list);
// Change it to this because you are using a listActivity
listView = getListView();//I've specified this listView only for the OnItemClickListener action
List values = new ArrayList();
// This won't run because you initilize listItem to an empty array or 0 so 0 < 0 evaluates to false and the loop doesn't run
for (int i = 0; i < listItem.length; i++) {
values.add(listItem[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
FileName = et.getText().toString() + ".txt";
FileOutputStream fout = openFileOutput(FileName, Context.MODE_PRIVATE);
OutputStreamWriter outsw = new OutputStreamWriter(fout);
try {
outsw.write(String.valueOf(maintext));
outsw.flush();
outsw.close();
Toast.makeText(getBaseContext(), "Your file has been saved", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();
String device;
switch (view.getId()) {
case R.id.SAVE:
List myList = new ArrayList();
device = et.getText().toString();
myList.add(device);
adapter.add(device);
et.setText("");
break;
}
adapter.notifyDataSetChanged();
}
});
//I think this is wrong, I get no error in Java by the way. How could this work if there's a specific extension for my activity that define the listview? **That's my question**.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});
}
}
Sorry for my english.
I'm using a list and I want each item I click on to send me to a different activity.
With my code it sends me to the same activity for each item I select.
Example: I have Activity 1, Activity 2, and Activity 3. In the list I have 3 items: Item 1, Item 2, Item 3. When I click on Item 1 it sends me to Activity 1, same thing for Items 2 and 3. When I click to Item 2 I want to open Activity 2, and when I click on Item 3 I want to open Activity 3. I'm new with these so be kind with me ;)
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity1 extends ListActivity {
static final String[] MENU = new String[] { "Ne salla", "Se shpejti", "Kinemate",
"Rreth Nesh"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// no more this
// setContentView(R.layout.list_fruit);
setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_main_activity1,MENU));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getBaseContext(),NeSalla.class);
startActivity(intent);
}
});
}
}
And in XML file
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="20sp" >
</TextView>
Use a switch statement using the position of the clicked item to choose which Activity to start.
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent;
switch(position) {
case 0:
intent = new Intent(getBaseContext(), NeSalla.class);
break;
case 1:
intent = new Intent(getBaseContext(), ...);
break;
...
}
startActivity(intent);
}
});
package com.yiqiexample.cc;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
//import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Food extends ListActivity
implements OnClickListener {
// Progress Dialog
private ProgressDialog pDialog;
//testing on Emulator:
private static final String READ_COMMENTS_URL = "http://10.0.2.2/pbda2/foodordered.php";
// my ip add 192.168.43.176
//private CheckBox chkFood, chkDrinks, chkServices;
//private Button btnDisplay, chkClear, deliever, chkClearFood, fooddeliever, drinksdeliever, servicesdeliever, chkClearDrinks, chkClearServices;
//private TextView clearThis,orderdisplay, clearThisFood, foodorderdisplay, drinksorderdisplay, servicesorderdisplay, clearThisDrinks, clearThisServices;
private static final String TAG_SUCCESS = "success";
private static final String TAG_POSTS = "posts";
private static final String TAG_SEATNUMBER = "seatnumber";
private static final String TAG_FOODORDERED = "foodordered";
//it's important to note that the message is both in the parent branch of
//our JSON tree that displays a "Post Available" or a "No Post Available" message,
//and there is also a message for each individual post, listed under the "posts"
//category, that displays what the user typed as their message.
//An array of all of our comments
private JSONArray mComments = null;
//manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.food);
View v = findViewById(R.id.backmain);
//set event listener
v.setOnClickListener(this);
View z = findViewById(R.id.drinksbtn);
//set event listener
z.setOnClickListener(this);
View x = findViewById(R.id.servicebtn);
//set event listener
x.setOnClickListener(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadComments().execute();
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
// Instantiate the arraylist to contain all the JSON data.
// we are going to use a bunch of key-value pairs, referring
// to the json element name, and the content, for example,
// message it the tag, and "I'm awesome" as the content..
mCommentList = new ArrayList<HashMap<String, String>>();
// Bro, it's time to power up the J parser
JSONParser jParser = new JSONParser();
// Feed the beast our comments url, and it spits us
//back a JSON object. Boo-yeah Jerome.
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
//when parsing JSON stuff, we should probably
//try to catch any exceptions:
try {
//I know I said we would check if "Posts were Avail." (success==1)
//before we tried to read the individual posts, but I lied...
//mComments will tell us how many "posts" or comments are
//available
mComments = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
//gets the content of each tag
String seatnumber = c.getString(TAG_SEATNUMBER);
String foodordered = c.getString(TAG_FOODORDERED);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_SEATNUMBER, seatnumber);
map.put(TAG_FOODORDERED, foodordered);
// adding HashList to ArrayList
mCommentList.add(map);
//annndddd, our JSON data is up to date same with our array list
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View arg0) {
if(arg0.getId() == R.id.backmain){
//define a new Intent for the second Activity
Intent intent = new Intent(this,MainActivity.class);
//start the second Activity
this.startActivity(intent);
}
if(arg0.getId() == R.id.drinksbtn){
//define a new Intent for the second Activity
Intent intent = new Intent(this,Drinks.class);
//start the second Activity
this.startActivity(intent);
}
if(arg0.getId() == R.id.servicebtn){
//define a new Intent for the second Activity
Intent intent = new Intent(this,Services.class);
//start the second Activity
this.startActivity(intent);
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_comment, new String[] { TAG_SEATNUMBER, TAG_FOODORDERED
//TAG_DRINKSORDERED, TAG_SERVICES
}, new int[] { R.id.seatnumber, R.id.orders
//R.id.drinkstv, R.id.servicestv,
});
// I shouldn't have to comment on this one:
setListAdapter(adapter);
// Optional: when the user clicks a list item we
//could do something. However, we will choose
//to do nothing...
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// This method is triggered if an item is click within our
// list. For our example we won't be using this, but
// it is useful to know in real life applications.
//new!
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("product", product);
startActivity(i);
//end new lines!!
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Food.this);
pDialog.setMessage("Loading orders...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
//we will develop this method in version 2
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
//we will develop this method in version 2
updateList();
}
}
}
single_item.java
package com.yiqiexample.cc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
txtProduct.setText(product);
}
}
single_list_item_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/product_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:padding="10dip"
android:textColor="#ffffff"/>
</LinearLayout>
food.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android1:id="#+id/bg2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android1:background="#E0FFFF" >
<Button
android1:id="#+id/btnDelete"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_alignParentBottom="true"
android1:layout_alignParentRight="true"
android1:text="#string/delete" />
<Button
android:id="#+id/servicebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="358dp"
android:layout_toRightOf="#+id/foodbutton"
android:text="SERVICES" />
<Button
android1:id="#+id/drinksbtn"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_alignParentBottom="true"
android1:layout_marginBottom="23dp"
android1:layout_marginRight="24dp"
android1:text="DRINKS ORDERS" />
<LinearLayout
android:id="#+id/top_layover"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="horizontal" >
<TextView
android1:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/foodtitle"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/top_layover"
android1:layout_alignBottom="#+id/servicesdelivered"
android:background="#fff"
android:divider="#android:color/transparent"
android:scrollbars="none"
android1:clickable="true" />
<LinearLayout
android:id="#+id/bottom_layover"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:orientation="horizontal"
android:weightSum="2" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<Button
android1:id="#+id/backmain"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:text="#string/backtomain" />
</LinearLayout>
</LinearLayout>
<Button
android1:id="#+id/servicesdelivered"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_above="#+id/drinksbtn"
android1:layout_alignParentLeft="true"
android1:layout_marginLeft="111dp"
android1:text="#string/servicesdelivered"
android1:visibility="invisible" />
</RelativeLayout>
When I tried to click on the listview,
it appears an error -
error opening trace file: No such file or directory (2)
I need help with making the listview clickable and it will intent into a page where I can delete specific data.
define Listview and Myadapter,DatabaseConnection class globaly
adapter
private ListView listview;
private Myadapter adapter;
private DatabaseConnection databaseconnection;
and in oncreate
listview = (ListView) findViewById(R.id.list);
databaseconnection=new DatabaseConnection(this);
adapter=new Myadapter(this,list); // list means pass record as list and create
custom adapter thats best way
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
//do something here like-
here get the id of record from list using listview position and
detete record from database using dis id
databaseconnection.open(); //create the database object first
deleteRecord(int id); //pass id for delete that record
databaseconnection.close();
}
});
In your code you still not use the list view.First define it globally like
private ListView mList;
Then initialize inside onCreate() like:
mList = (ListView) findViewById(R.id.list);
mList.setAdapter(your_adapter) //this adapter contains the mCommentList arraylist
mList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
//do something here
}
});
Its good if you use an adapter class to set value in your custom layout.
Check this example
Thank you
Hi I am trying to make an app that shows a list of items using listView and when the user select one of the items from the list. the app will call the specific class that is link to the item selected however i encountered an error at the second #override, saying that the override must override a super class. Here are my codes for class and 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="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/botanicgate" />
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
package com.fyp.gulliver;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class HotSpot extends ListActivity{
/** Called when the activity is first created. */
String places[] = {"BotanicGarden", "Sentosa"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hotspot);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(new ArrayAdapter
(HotSpot.this, android.R.layout.simple_list_item_1,
places));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Class ourClass;
String item = ((TextView)view).getText().toString();
try {
ourClass = Class.forName
("com.fyp.gulliver." + item);
Intent ourIntent = new Intent(HotSpot.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
As i am still new to android, thus i do not know what mistakes i have made, I will be grateful if another one can help me to solve my error thank you :D
Try changing this:
listView.setOnItemClickListener(new OnItemClickListener();
to
listView.setOnItemClickListener(new AdapterView.OnItemClickListener();
and remove the 2nd #Override
I've been browsing all possible sites for ages and haven't found my needs yet. I rly need to find a code-example of a basic listview in android that lets me click on the items in the list and takes me to an imageview displaying an image (different for every item in the list). Please post a working samplecode for this as it's driving me mad that I can't figure it out :(
I'm not going to go into detail about creating the ListView or setting an adapter or any of that stuff, there's plenty of other examples on the Web to do that and your question isn't asking how to set a ListView adapter ;)
Create an activity that extends ListActivity
Create a layout for your new ListActivity and put a ListView in it
(#+id/list) for my example
What's in your list? idk, but lets say it's an ArrayList of strings
now override onListItemClick in your ListActivity
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
if (l.getItemAtPosition(position).equals("LIST1"))
{
// Do something with it
}
}
Alternatively, you don't need a ListActivity, you can set an onItemClickListener
e.g.
myListView.setOnItemClickListener(new onItemClickListener()
{
#Override protected void onListItemClick(ListView l, View v, int position, long id) {
// Do stuff
}
}
check that link
all you need to do is change the OnItemClickListener() method
Ok here's the code, first we got the list menu.
package item.list.lol;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Menu extends ListActivity {
String classes[] = {"startingPoint", "lol"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String pointer = classes[position];
try{
Class ourClass = Class.forName("item.list.lol." + pointer);
Intent ourIntent = new Intent(Menu.this, ourClass);
startActivity(ourIntent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
}
And then the class that handles the imageView
package item.list.lol;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
public class startingPoint extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageResource(R.drawable.ic_launcher);
}}
And the 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="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.67"
android:src="#drawable/ic_launcher" />
</LinearLayout>
As you see it can now only display an image if I press the first item in the list, I need a way to make it display different images if I click different items, any ideas?