Set OnItemClickListener for a listItem - android

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();
}
});
}
}

Related

ListView is not showing items that are added

EDIT
Got the error, it turns out it is an issue regarding the API version of the emulator. Works fine in higher API version
I am new to Android development and I am trying to build a simple to-do list where items will be added to ListView when a button is clicked. The problem is, the items are not shown in the listview, although they are added and deleted. Please help me identify what I am doing wrong.
Here is my activity_main.xml file
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.erfan.todolist.MainActivity">
<RelativeLayout
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<EditText
android:id="#+id/editTextAddItem"
android:hint="Enter Item"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_weight="4"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/buttonAddItem"
android:text="Add"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_below="#+id/editTextAddItem"
android:layout_marginTop="23dp" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
Here is my MainActivity.java file
package com.example.erfan.todolist;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
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.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
EditText vEditTextAddItem;
Button vButtonAddItem;
ListView vListViewItemList;
ArrayList<String> items;
ArrayAdapter<String> adapter;
public static final String FILENAME = "data.dat";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vEditTextAddItem = (EditText) findViewById(R.id.editTextAddItem);
vButtonAddItem = (Button) findViewById(R.id.buttonAddItem);
vListViewItemList = (ListView) findViewById(R.id.listView);
items = readData(getApplicationContext());
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item, items);
vListViewItemList.setAdapter(adapter);
vButtonAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonAddItem:
String itemEntered = vEditTextAddItem.getText().toString();
adapter.add(itemEntered);
vEditTextAddItem.setText("");
writeData(items, getApplicationContext());
Toast.makeText(getApplicationContext(), "Item is added", Toast.LENGTH_SHORT).show();
break;
}
}
});
vListViewItemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
items.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Item Deleted", Toast.LENGTH_SHORT).show();
}
});
}
public static void writeData(ArrayList<String> items, Context context) {
try {
FileOutputStream fileOutputStraStream = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStraStream);
objectOutputStream.writeObject(items);
objectOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ArrayList<String> readData(Context context) {
ArrayList<String> itemList = null;
try {
FileInputStream fileInputStream = context.openFileInput(FILENAME);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
itemList = (ArrayList<String>) objectInputStream.readObject();
} catch (FileNotFoundException e) {
itemList = new ArrayList<>();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
itemList = new ArrayList<>();
e.printStackTrace();
}
return itemList;
}
}
I am attaching the screenshot of the emulator as well
When the item is added, no item is showing in the ListView.
Got the error, it turns out it is an issue regarding the API version of the emulator. Works fine in higher API version

Enabling the Edittext on selecting Item from Spinner

hello friends I am trying to enable the edittext depending upon my selection of records.The XML file is as 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" >
<Spinner
android:id="#+id/per_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:gravity="center"
android:layout_marginTop="20dp"/>
<Spinner android:id="#+id/columnToUpdate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:spinnerMode="dialog"
android:gravity="center"
android:layout_marginTop="20dp"/>
<EditText
android:id="#+id/enterToUpdateString"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="20dp"
android:inputType="text"
android:hint="#string/EnterTheTextHere"/>
<EditText
android:id="#+id/enterToUpdateInt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="20dp"
android:inputType="number"
android:hint="#string/EnterTheNumberHere"/>
<Button
android:id="#+id/clickToUpdate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/clickToUpdate"/>
</LinearLayout>
And the Java Code that I am applying is as below :-
package com.indianic.databaseprac;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class UpdateFrom25Table extends Activity {
String id, column, text;
EditText integertext;
EditText stringText;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.update_from_25_table);
stringText = (EditText) findViewById(R.id.enterToUpdateString);
integertext = (EditText) findViewById(R.id.enterToUpdateInt);
stringText.setVisibility(View.GONE);
integertext.setVisibility(View.GONE);
Button updateButton = (Button) findViewById(R.id.clickToUpdate);
// Here I am setting the spinner where I am taking the content of the
// table per_ID having all the unique IDs and setting it to the spinner
Spinner spinnerid = (Spinner) findViewById(R.id.per_id);
final Database25TableHandler db = new Database25TableHandler(
getApplicationContext());
List<String> ids = db.gettingid();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, ids);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinnerid.setAdapter(dataAdapter);
// Here I am setting all the column names in the second spinner with the
// help of the cursor.
Spinner spinnerColumn = (Spinner) findViewById(R.id.columnToUpdate);
List<String> column = db.getcolumnname();
ArrayAdapter<String> dataAdaptercolumn = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, column);
dataAdaptercolumn
.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinnerColumn.setAdapter(dataAdaptercolumn);
final String spinnerSelectedID = (String) spinnerid.getSelectedItem();
final String spinnerSelectedcolumn = (String) spinnerColumn
.getSelectedItem();
spinnerColumn.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Log.d("TESTING", parent.getItemAtPosition(pos).toString());
// TODO Auto-generated method stub
if(parent.getItemAtPosition(pos).toString() == "reg_id") {
//integertext.setEnabled(true);
Log.d("TESTING", "LOOOOGGGGG");
integertext.setVisibility(View.VISIBLE);
text = integertext.getText().toString();
} else if (parent.getItemAtPosition(pos).toString() == "first_name") {
//stringText.setEnabled(true);
stringText.setVisibility(View.VISIBLE);
text = stringText.getText().toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
// Here I am setting all the Items that are selected in the string in
// order to perform the update process.
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.updateRow(spinnerSelectedID, spinnerSelectedcolumn, text);
db.close();
}
});
}
}
Here even when I am selecting the reg_id from spinner it is not entering the first if part as the Log.d("TESTING", "LOOOOGGGGG"); is not printed
Try this..
If you comparing String you should use .equels
if(parent.getItemAtPosition(pos).toString().equels("reg_id")) {
//integertext.setEnabled(true);
Log.d("TESTING", "LOOOOGGGGG");
integertext.setVisibility(View.VISIBLE);
text = integertext.getText().toString();
} else if (parent.getItemAtPosition(pos).toString().equels("first_name")) {
//stringText.setEnabled(true);
stringText.setVisibility(View.VISIBLE);
text = stringText.getText().toString();
}
== always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.
However, the equals method can be overridden - so two distinct objects can still be equal
EDIT
if(parent.getItemAtPosition(pos).toString().equalsIgnoreCase("reg_id") || parent.getItemAtPosition(pos).toString().equels("first_name")){
}
You should use the .equals(String) method for string comparison (which performs a simple 'shallow' comparison) rather than the '==' comparison (which performs a 'deep' comparison - verifying if two string objects point to the same instance in memory).
Also, to toggle enabled/disabled state, you need to use the setEnabled(boolean) method. setEnabled(true) will set the edittext to be enabled and setEnabled(false) will disable the edittext.

How to link listView to another class when list item is selected?

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

Send ListView results via Messaging application

I am very new to programming. I have an app that has several views. The Main view shows a list such as Breakfast, Lunch & Dinner. When a an item is selected, example Lunch, a list of lunch menu items is displayed such as Hamburger, Cheeseburger, French Fries... (this list is created from the string-array lunch_menu that is stored in \values\lunch.xml) as the user selects the items they want, it is stored in a new array called myNewList and is displayed whe the users presses the lunchList button. All of the items are displayed that the user selected. So far, So good. I created a android:onClick="shareMyList" in the selecteditems.xml and the button works, but does not populate my list. I think what i need is to some how convert it to a string, this is where I need help.
Here is my Problem now.... I have my Share button, that when pressed, I would like it to automatically open the default Messaging app and populate the list from the selected items ListView.
package com.mycompany.lunch;
import java.util.ArrayList;
import android.app.Activity;
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.Button;
import android.widget.ListView;
import android.widget.Toast;
public class LunchListMenu extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maincoarse);
final ListView lv=(ListView)findViewById(R.id.listView1);
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this, R.array.lunch_menu,android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
final ArrayList<String> myNewList = new ArrayList<String>();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String item=lv.getItemAtPosition(arg2).toString();
String itemordered;
itemordered = item + " added to list";
Toast.makeText(getApplicationContext(), itemordered, Toast.LENGTH_SHORT).show();
myNewList.add(item);
}
});
// List View Button
Button btnLunchList = (Button) findViewById(R.id.lrList);
btnLunchList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.selecteditems);
ListView selecteditems = (ListView) findViewById(android.R.id.list);
ArrayAdapter<String> newadapter = new ArrayAdapter<String>(LunchListMenu.this, android.R.layout.simple_list_item_1, myNewList);
selecteditems.setAdapter(newadapter);
}
});
}
public void shareMyList(View v){
// Share Selected Items Button
Button btnShareItems = (Button) findViewById(R.id.shareMyList);
btnShareItems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, "I'm being sent!!");
startActivity(Intent.createChooser(share, "Share Text"));
}
});
}
}
Here is the Lunch Menu Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/main_background"
android:paddingLeft="10.0dip"
android:paddingTop="0.0dip"
android:paddingRight="10.0dip"
android:paddingBottom="10.0dip"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/lrList"
android:layout_width="72dip"
android:layout_height="72dip"
android:layout_gravity="right"
android:background="#drawable/list" />
<ImageView
android:id="#+id/LunchMenuTitle"
android:contentDescription="#string/LunchMenu"
android:layout_width="0dip"
android:layout_height="72dip"
android:layout_weight="0.96"
android:background="#drawable/lunch"
android:paddingLeft="10.0dip"
android:paddingRight="10.0dip" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="10.0dip"
android:background="#drawable/head"
android:orientation="horizontal" />
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#FFCC00"
android:dividerHeight="2dp" >
</ListView>
<LinearLayout
android:orientation="horizontal"
android:background="#drawable/head"
android:layout_width="fill_parent"
android:layout_height="10.0dip" />
</LinearLayout>
And Here is my selecteditems.xml Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#drawable/main_background"
android:paddingLeft="10.0dip"
android:paddingTop="0.0dip"
android:paddingRight="10.0dip"
android:paddingBottom="10.0dip"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/shareMyList"
android:layout_width="72dip"
android:layout_height="72dip"
android:layout_gravity="right"
android:onClick="shareMyList"
android:background="#drawable/share" />
<ImageView
android:id="#+id/selectedItemsTitle"
android:contentDescription="#string/LunchTitle"
android:layout_width="0dip"
android:layout_height="72dip"
android:layout_weight="0.96"
android:background="#drawable/title"
android:paddingLeft="10.0dip"
android:paddingRight="10.0dip" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="10.0dip"
android:background="#drawable/head"
android:orientation="horizontal" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#FFCC00"
android:dividerHeight="2dp"
android:padding="10dip"
android:textColor="#ffffff"
android:textSize="20dip"
android:textStyle="bold" />
</LinearLayout>
This may be the most kludgiest way of doing this, but it works.
package com.mycompany.lunch;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class LunchListMenu extends Activity {
String itemsordered;
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maincoarse);
final ListView lv=(ListView)findViewById(R.id.listView1);
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this, R.array.lunch_menu,android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
final ArrayList<String> myNewList = new ArrayList<String>();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String item=lv.getItemAtPosition(arg2).toString();
String itemordered;
itemordered = item + " added to list";
Toast.makeText(getApplicationContext(), itemordered, Toast.LENGTH_SHORT).show();
myNewList.add(item);
}
});
// List View Button
Button btnLunchList = (Button) findViewById(R.id.lrList);
btnLunchList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.selecteditems);
ListView selecteditems = (ListView) findViewById(android.R.id.list);
ArrayAdapter<String> newadapter = new ArrayAdapter<String>(LunchListMenu.this, android.R.layout.simple_list_item_1, myNewList);
selecteditems.setAdapter(newadapter);
// Get sdCard location so we can Create Dir and File
File sdCard = Environment.getExternalStorageDirectory();
File lunch = new File(sdCard,"Lunch");
lunch.mkdirs();
File file = new File(lunch, "Lunch.txt");
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter(file));
} catch (IOException e) {
e.printStackTrace();
}
// Write each string in the array
StringBuilder text = new StringBuilder();
for (String s : myNewList) {
out.println(s);
}
out.close();
// read File
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append(',');
text.append(' ');
}
}
catch (IOException e) {
}
itemsordered = text;
}
});
}
public void shareMyList(View v){
// Share Selected Items Button
Button btnShareItems = (Button) findViewById(R.id.shareMyList);
btnShareItems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", itemsordered);
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
}
});
}
}

OnListItemClick is not firing

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.

Categories

Resources