ListView onClick - android

I'm trying to do something very simple: create a frequently asked questions listview, and when a question is clicked, the answer appears in a textview. I created two string arrays for questions and answers, and each element is listed as an item. There are 5 q's and 5 a's. Right now the questions are being displayed correctly in a listview, but the onclick isn't working. What is wrong??
package freq.asked;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class FreqActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//displays all elements of questions array in listview
setListAdapter(ArrayAdapter.createFromResource(getApplicationContext(),
R.array.questions, R.layout.main));
}
public void onItemClick(AdapterView<?> arg0, TextView v, int position, long id) {
String[] ans = getResources().getStringArray(R.array.answers);
for (int i=0; i<6; i++) {
//should display answer to question in textview
v.setTag(ans[i]);
}
}
}

I believe you are using the wrong method, try onListItemClick() instead:
protected void onListItemClick(ListView l, View v, int position, long id) {
An example:
public class FreqActivity extends ListActivity {
String[] ans;
String[] questions;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ans = getResources().getStringArray(R.array.answers);
questions = getResources().getStringArray(R.array.questions);
//displays all elements of questions array in listview
setListAdapter(ArrayAdapter.createFromResource(getApplicationContext(),
R.array.questions, android.R.layout.simple_list_item_1));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
((TextView) v).setText(questions[position] + ": " + ans[position]);
}
}
Notice that you don't need to get the ans every time the user clicks a row, you only need to do it once in onCreate()
If you only wan to start a new Activity after clicking a "question" use this in onListItemClick():
Intent i = new Intent(this, AnswerActivity.class);
i.putExtra("answer", ans[position]);
startActivity(i);
You can read about how to read this data here: How do I pass data between Activities in Android application?

Please use the following replacing the method onItemClick,
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}

Related

Adding onClickListener to specific items in ListView

please I'm trying to add understand how to add onItemClickListener to the followng code such that when "Smartphone Plans" is clicked, its activity starts and so on. I've seen other questions on StackOverflow relating to this question but do not understand how to go about them.
I've already added an onItemClickListener but do not understand how to set it to specific list items.
here is the code
package devchuks.com.rechargeit;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.app.ListActivity;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class EtisalatData extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_etisalat_data);
listView = (ListView) findViewById(R.id.list);
String[] values = new String[] {
"Smartphone Plans",
"Internet Bundles",
"Weekend Plans",
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
You can define your listView.setOnItemClickListener like this to go to different activity for clicking different element.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = listView.getItemAtPosition(position);
Toast.makeText(this,"You selected : " + item,Toast.LENGTH_SHORT).show();
if(position==0) {
// Do your code for clicking "Smartphone Plans" example
// startActivity(new Intent(getApplicationContext(),SmartphonePlans.class));
}
else if(position==1) {
// Do your code for clicking "Internet Bundles". example
// startActivity(new Intent(getApplicationContext(),InternetBundles.class));
}
else if(position==2) {
// Do your code for clicking "Weekend Plans". example
//startActivity(new Intent(getApplicationContext(),WeekendPlans.class));*/
}
});
onItemClick will be called whenever any of the list items are clicked. The position will be the position of the view in the Adapter.
Please refer -
How to handle the click event in Listview in android?
Thanks
Sriram
try this:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = values[position];
if(text.equals("Smartphone Plans")){ //your specific list item text
Intent i = new Intent(MainActivity.this, AnotherActivity.class);
i.putExtra("TEXT", text);
startActivity(i);
}
}
}
If this helps and is your concern
`
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String data = values[position];
switch(data){
case "Smartphone Plans":
// do somwthing
break;
// similarly for other two values.
}
}
});`
Below method give you a position of a clicked row. Take advantage of that and value from your array.
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Move your values array to member array or make it final to use
// in Anonymous class
final String selectedValue = values[position];
Intent intent = null
// Now add case and start activity
if("Smartphone Plans".equals(selectedValue)) {
intent = new Intent(EtisalatData.this, SmartPhonePlan.class);
}
else if("other Plans".equals(selectedValue)){
// other action
}
//... more cases and at the end start your activity if its not null
startActivity(intent);
}

Starting an Activity from ListView

My list includes eight items positioned beneath a 'header' row, all contained within a tab on my application. I cannot figure out how to change to an activity (or possibly a different tab) based upon the item clicked on in the list.
I'm currently extending the Activity class, not sure if this is an issue. I've attempted to use the onListItemClick whilst extending the ListActivity class; this however caused the application to crash.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class Tab2 extends Activity {
private ListView listView1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab2);
Cinema cinema_data[] = new Cinema[]{
new Cinema(R.drawable.blue, "Blue Cinema"),
new Cinema(R.drawable.green, "Green Cinema"),
new Cinema(R.drawable.purple, "Purple Cinema"),
new Cinema(R.drawable.red, "Red Cinema"),
new Cinema(R.drawable.yellow, "Gold Cinema"),
new Cinema(R.drawable.blue, "Cyan Cinema"),
new Cinema(R.drawable.green, "Lime Cinema"),
new Cinema(R.drawable.purple, "Magenta Cinema")
};
CinemaAdapter adapter = new CinemaAdapter(this,
R.layout.listview_item_row, cinema_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
}
any help will be greatly appreciated!
edit:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
try {
Intent i = new Intent("android.lab.two.Tab1");
startActivity(i);
} catch(Exception e){
e.printStackTrace();
}
}
if the OnItemClickListener doesn't work, you can try setting it in your adapter :
in your adapter, in the getView method, you can add an OnClickListener to your row view like this :
public View getView(int arg0, View arg1, ViewGroup arg2) {
//Create the view for your row
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, 64);
TextView rowView = new TextView(getApplicationContext());
rowView.setLayoutParams(lp);
rowView.setText("your value");
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//Starting a new intent ( here a Dial Activity )
Intent newIntent = new Intent(Intent.ACTION_DIAL);
newIntent.setData(Uri.parse("tel:"+value));
startActivity(newIntent);
} catch (ActivityNotFoundException e) {
Log.e("your application", "Dial failed", e);
}
}
});
}
You just set the click listener on your listview. You get the position and perform you logic from there. The code below should help you get started. I don't know what error you were getting, but there is not much that can go wrong.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myIntent = new Intent(view.getContext(),
NextClass.class);
startActivity(myIntent);
}
});
Use the setCurrentTab method in TabHost to change tab based on the list item index.
Fire intent to this activity itself keeping it in the single top launch modes & then using the bundled data change the tab via tab host.
I hope this helps..
You cannot start an activity from a TabHost. You are in a inner class. You must use NestedClasses.
Instead of starting an Intent in your onClickListener, try to Log something, and you will see that will work.
Log.d("LOG","Message");
if you set onListItemClick() method inside your tab(activity) then you have to use
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this,tab1.class);
startActivity(i);
}
if you set onListItemClick() method is define in other class then you have to use
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Intent i = new Intent(v.getContext(),tab1.class);
startActivity(i);
}
if tab1(activity) is a main activity and you have to call tab2(activity) inside the tab1(activity) then you have to use this way...
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
System.exit(0);
}

ListActivity Intents

I currently have a ListActivity and I am looking to start a new activity based on the selection in the list. Based upon Intents and Extras, how can I make this possible? Here is my code so far:
package com.fragile.honbook;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class GuideSelection extends ListActivity{
private TextView selection;
private static final String[] heroes={ "Agility", "Intelligence",
"Strength"};
public void onCreate(Bundle icicle){
super.onCreate(icicle);
setContentView(R.layout.heroselect);
setListAdapter(new ArrayAdapter<String>(this,
R.layout.row, R.id.label,
heroes));
selection=(TextView)findViewById(R.id.select);
}
public void onListItemClick(ListView parent, View v,
int position, long id){
}
}
Like this
If you want to call an activity called NewActivity after clicking the list item with sending data as extra you can do this
public void onListItemClick(ListView parent, View v,
int position, long id){
Intent intent = new Intent(GuidSelection.this, NewActivity.Class());
intent.putExtra("DATA",heroes[position]);
GuideSelection.startActivity(intent);
}
public void onListItemClick(ListView parent, View v, position, long id){
Intent intent = new Intent(GuideSelection.this, NewActivity.class);
intent.putExtra("hero", heroes[position]);
startActivity(intent);
}
Update (with different activities per list item):
final Map<String, Class> activities = new HashMap<String, Class>();
{
activities.put("agility", AgilityActivity.class);
activities.put("intelligence", IntelligenceActivity.class);
// add more here
}
public void onListItemClick(ListView parent, View v, position, long id){
Intent intent = new Intent(GuideSelection.this, activities.get(heroes[position]));
intent.putExtra("hero", heroes[position]);
startActivity(intent);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(position==1){
//First item clicked.
Intent intent = new Intent(this,NewActivity.class);
startActivity(intent));
}
// handle else ifs
}
This is just an idea. You may wish to improvise this to too much of if elses.

Android: Listview's onItemClick() event not getting called

Following is my code :
public class TestActivity extends ListActivity {
private Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
fillData();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG)
.show();
}
private void fillData() {
TermsData_DataHelper termsDataHelper = new TermsData_DataHelper(
TestActivity.this);
cursor = termsDataHelper.fetchAllCategories();
startManagingCursor(cursor);
String[] names = new String[] { "name" };
int[] to = new int[] { R.id.label };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter categories = new SimpleCursorAdapter(this,
R.layout.terms_row, cursor, names, to);
setListAdapter(categories);
}
}
When I click on a row in the listview, I don't see any Toast. Can anybody tell me where am I making a mistake.
Thanks in advance.
I was having a similar problem and found that after removing android:clickable="true" from my list items, the onListItemClick() was being triggered just fine. I hope this helps.
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String mString = parent.getItemAtPosition(position).toString();
//will give you the text of current line or
int i = parent.getItemAtPosition(position);
//if you want just position number
}
The solution is to override protected void onListItemClick (ListView l, View v, int position, long id) method.
I had this problem also. I solved it by Removing this from my TextView in the the layout XML.
android:textIsSelectable="true"

ListView onListItemClick setcontentview crash?

I have been trying to set a new xml layout, when a particular item on this list is clicked.
Am I missing something, because the emulator crashes when clicked?! setContentViewById(R.id.newxml file)
public class intentProject extends ListActivity
{
ListView list;
ArrayAdapter<String> aa;
List<String> data = new ArrayList<String>();
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
data.add("France");
data.add("Japan");
data.add("Russia ");
data.add("Poland");
data.add(" USA");
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data
);
setListAdapter(aa);
}
protected void onListItemClick(ListView l, View v, int position, long id)
{
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
this.setContentView(R.layout.main2);
}
}
No I am not using a listview in the next xml. It is going to be a plain xml file with 2 buttons. These buttons are going to implement intents.

Categories

Resources