android get positon of itemclicked in another class - android

Can someone please help me? I am trying to access a "position" variable itemclicked. I want the content of the other class to display a different thing depending on the list I clicked.
What I want is this: if I click position 0, then it takes me to another page and the TextView I created on that class changes to "you clicked position 0". If I click position 1, it changes to "you clicked position 1", etc.
I've attempted to do this, but it only works when I click position 0. If I click item 1, it shows "you have clicked position 0". I am very confused. I have tried using putexraa and other methods, but they are not working. Your help would be greatly appreciated.
package com.obi.arinzeapp;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private List<list> mymusic = new ArrayList<list>();
public list currentsong;
public int man;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populatemusiclist();
populateListView();
registerclick();
}
private void registerclick() {
ListView mus = (ListView) findViewById(R.id.musiclistview);
mus.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long arg3) {
man = position;
try {
Class ourClass = Class.forName("com.obi.arinzeapp.Music");
Intent ourIntent = new Intent(MainActivity.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
private void populatemusiclist() {
mymusic.add(new list(R.drawable.ff, " Mr.J.Mederiors \"Constance\"",
R.drawable.medi));
mymusic.add(new list(R.drawable.ff, " Mr.J.Mederiors \"Constnce\"",
R.drawable.medi));
mymusic.add(new list(R.drawable.ff, " Mr.J.Mederiors \"Constnce\"",
R.drawable.medi));
}
private void populateListView() {
ArrayAdapter<list> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.musiclistview);
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<list> {
public MyListAdapter() {
super(MainActivity.this, R.layout.viewitem, mymusic);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View veiwitem = convertView;
if (veiwitem == null) {
veiwitem = getLayoutInflater().inflate(R.layout.viewitem,
parent, false);
// return super.getView(position, convertView, parent);
}
list currentsong = mymusic.get(position);
ImageView imageview = (ImageView) veiwitem
.findViewById(R.id.imageView2);
imageview.setImageResource(currentsong.getNum());
TextView wor = (TextView) veiwitem.findViewById(R.id.word);
wor.setText(currentsong.getNameofsong());
ImageView imageview2 = (ImageView) veiwitem
.findViewById(R.id.imageView1);
imageview2.setImageResource(currentsong.getPicture());
return veiwitem;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
import android.app.Activity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Music extends Activity{
TextView name,song,album,about;
String nam,son,albu,abou;
RelativeLayout picc;
public int ye ;
MainActivity maa = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stu
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
name= (TextView) findViewById(R.id.name);
song= (TextView) findViewById(R.id.song);
album=(TextView) findViewById(R.id.album);
about=(TextView) findViewById(R.id.about);
picc=(RelativeLayout) findViewById(R.id.picc);
maa.man= ye;
if(ye==0){
name.setText("You clicked position 1") ;
}else{
name.setText("You clicked position 2") ;
}
}
}

Pass the value of man in putExtra while setting the intent for that class in mainActivity
Class ourClass = Class.forName("com.obi.arinzeapp.Music");
Intent ourIntent = new Intent(MainActivity.this, ourClass);
ourIntent.putExtra("man",man);
startActivity(ourIntent);
And get this extra in Music Activity
extras = getIntent().getExtras();
newInt= extras.getInt("man");
This is the standard way to pass the values from one activity to another.
But the way you doing you can try making man as static variablebut it is not recommended.

Related

Android parse.com listView crashing

i am attempting to create this app which has a listView and when i click on an item in the listView it displays more information about the clicked item. I dont know how to fix this problem. i am getting the following from my log
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
at com.example.velvetdev01.parselistclick.MainActivity$1.onItemClick(MainActivity.java:50)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
and here is my code
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.ListView;
import com.parse.ParseObject;
import com.parse.ParseQueryAdapter;
import java.util.List;
//import android.widget.ArrayAdapter;
public class MainActivity extends Activity {
private CustomAdapter urgentTodosAdapter;
private ParseQueryAdapter<ParseObject> mainAdapter;
private ListView listView;
List<ParseObject> object;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
mainAdapter = new ParseQueryAdapter<ParseObject>(this, "RestaurantDetail");
urgentTodosAdapter = new CustomAdapter(this);
listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(urgentTodosAdapter);
urgentTodosAdapter.loadObjects();
// Binds the Adapter to the ListView
listView.setAdapter(urgentTodosAdapter);
// Capture button clicks on ListView items
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(MainActivity.this, SingleItemView.class);
// Pass data "name" followed by the position
intent.putExtra("Name", object.get(i).getString("Name"));
// Open SingleItemView.java Activity
startActivity(intent);
}
});
}
}
and my custom adapter
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.parse.ParseFile;
import com.parse.ParseImageView;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
public class CustomAdapter extends ParseQueryAdapter<ParseObject> {
public CustomAdapter(Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("RestaurantDetail");
/* query.whereEqualTo("Name", true);*/
return query;
}
});
}
#Override
public View getItemView(ParseObject object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.activity_main, null);
}
super.getItemView(object, v, parent);
ParseImageView todoImage = (ParseImageView) v.findViewById(R.id.icon);
ParseFile imageFile = object.getParseFile("Logo");
if (imageFile != null) {
todoImage.setParseFile(imageFile);
todoImage.loadInBackground();
}
TextView titleTextView = (TextView) v.findViewById(R.id.textView3);
titleTextView.setText(object.getString("Name"));
return v;
}
}
Here is the class i am trying to display the detailed information
#ParseClassName("RestaurantDetail")
public class SingleItemView extends Activity {
// Declare Variables
protected TextView txtname;
String Name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from singleitemview.xml
setContentView(R.layout.single_item_view);
txtname = (TextView) findViewById(R.id.name);
// Retrieve data from MainActivity on item click event
Intent random1 = getIntent();
// Get the name
Name = random1.getStringExtra("Name");
// Locate the TextView in singleitemview.xml
txtname = (TextView) findViewById(R.id.name);
// Load the text into the TextView
txtname.setText(Name);
}
}

Android / JAVA - How to set click function on List view cell

I am trying to add a click function to a programmatically filled List View. I followed a tutorial, and it gives me no errors and to my understanding it should work, however when I tap a cell it does completely nothing. No crash/action occures.
This is my code:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class domainViewer extends ActionBarActivity {
public List<Domain> domains = new ArrayList<Domain>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_domain_viewer);
populateDomainList();
populateViewList();
RegisterClickCallback();
}
private void populateViewList() {
ArrayAdapter<Domain> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.domainsListView);
list.setAdapter(adapter);
}
private void populateDomainList() {
domains.add(new Domain("cheese.com", true, "€15,50" , R.drawable.deselected));
domains.add(new Domain("cheese.nl", true, "€15,50" , R.drawable.deselected));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_domain_viewer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class MyListAdapter extends ArrayAdapter<Domain> {
public MyListAdapter() {
super(domainViewer.this, R.layout.item_view, domains);
}
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
}
Domain currentDomain = domains.get(position);
ImageView imageView = (ImageView)itemView.findViewById(R.id.imgSelected);
imageView.setImageResource(R.drawable.deselected);
TextView domainText = (TextView) itemView.findViewById(R.id.tvDomain);
domainText.setText(currentDomain.getDomain());
TextView priceText = (TextView) itemView.findViewById(R.id.tvPrice);
priceText.setText(currentDomain.getPrice());
return itemView;
//return super.getView(position, convertView, parent);
}
}
private void RegisterClickCallback() {
ListView list = (ListView) findViewById(R.id.domainsListView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Domain clickedDomain = domains.get(position);
String message = position + " - " + clickedDomain.getDomain();
Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
toast.show();
}
});
}
}
You need to implement the click event with in your adapter class ,
public OnItemClickListener onItemClick = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
}
};
Then create the listener where you set the adapter,
private void populateViewList() {
ArrayAdapter<Domain> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.domainsListView);
list.setAdapter(adapter);
list.setOnItemClickListener(adapter.onItemClick);
}

Is it possible to start a new activity with a click of a item in a ListView?

I was just wondering if I was able to start a new activity with the click of an item inside a ListView.
The code I have written so far:
package awad865.project.ContactManager1;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.contactmanager1.R;
import android.widget.AdapterView;
public class MainActivity extends Activity {
private ListView listView;
private ImageButton button1;
private ImageButton button2;
private ImageButton button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false);
listView = (ListView)findViewById(R.id.main_contact_listview);
button1= (ImageButton)findViewById(R.id.button_search);
button2= (ImageButton)findViewById(R.id.button_addcontact);
button3= (ImageButton)findViewById(R.id.button_options);
setUpListView();
}
private void setUpListView(){
List <Contact> displayList = new ArrayList<Contact>();
displayList.add(new Contact("Anmol","Wadhwa","53743632"));
displayList.add(new Contact("Juhi","Goswami","4234232"));
displayList.add(new Contact("Laurence","Baldwick","243232"));
ListAdapter listAdapter = new CustomListAdapter(MainActivity.this,displayList);
listView.setAdapter(listAdapter);
}
private class CustomListAdapter extends ArrayAdapter<Contact>{
private Context _context;
private List<Contact> _contacts;
public CustomListAdapter(Context context, List<Contact> contacts){
super(context,android.R.layout.simple_list_item_1,contacts);
_context = context;
_contacts = contacts;
}
public View getView(int position, View convertView,ViewGroup parent){
//Create a layout inflater to inflate our xml layout for each item in the list
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the list item layout. Keep a reference to the inflated view.
//No root view specified
View listItemView = inflater.inflate(R.layout.custom_list_item_layout,null);
//Access TextView elements inside the view (note we must specify the parent view
//to look in)
TextView firstName = (TextView)listItemView.findViewById(R.id.list_item_firstname);
TextView lastName = (TextView)listItemView.findViewById(R.id.list_item_lastname);
TextView number = (TextView)listItemView.findViewById(R.id.list_item_number);
//Set the text for each textview (use the position arugment to find the appropriate element in the list)
firstName.setText(_contacts.get(position).getFirstName());
lastName.setText(_contacts.get(position).getLastName());
number.setText(_contacts.get(position).getNumber());
return listItemView;
}
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.action_groups:
Intent groupIntent = new Intent(this,Groups.class);
startActivity(groupIntent);
return true;
case R.id.action_favourites:
Intent favouriteIntent = new Intent(this,Favourites.class);
startActivity(favouriteIntent);
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return true;
}
public void addContact(View view){
Intent intent = new Intent(this,AddContact.class);
startActivity(intent);
}
}
class listItemClickedListener implements AdapterView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parentView, View clickedView, int clickedViewPosition, long id) {
// TODO Auto-generated method stub
Intent contactInfoIntent = new Intent(this, ContactInformation.class);
}
}
I was just wondering if I was able to start a new activity inside the method onItemClick() in the class listItemClickListener. Any help would be appreciated because the compiler doesn't allow me to start a new intent.
You can retrieve the Context you need from clickedView.
Intent contactInfoIntent = new Intent(clickedView.getContext(), ContactInformation.class);
clickedView.getContext().startActivity(contactInfoIntent);
start Activity on ListView item Click as:
STEP 1:
Add on OnItemClickListener by passing instace of listItemClickedListener class as:
....
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new listItemClickedListener());
STEP 2:
start Activity from onItemClick as:
Intent contactInfoIntent = new Intent(clickedView.getContext(),
ContactInformation.class);
clickedView.getContext().startActivity(contactInfoIntent);
you need to bind the click event to each item added to the listView
You could put the Data, in your case ContactDate, as a ContactData element onto your View (each cell) by calling convertView.setTag(contactData) in your getView() Method.
onItemClick wpuld then do something like this:
ContactData cd = (ContactData)clickedView.getTag();
Bundle b = new Bundle();
// put data from cd in that Bundle
Intent contactInfoIntent = new Intent(this, ContactInformation.class);
startActivity(contactInfoIntent);
update:
try this:
package awad865.project.ContactManager1;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.contactmanager1.R;
import android.widget.AdapterView;
public class MainActivity extends Activity implements OnItemClickListener{
private ListView listView;
private ImageButton button1;
private ImageButton button2;
private ImageButton button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false);
listView = (ListView)findViewById(R.id.main_contact_listview);
button1= (ImageButton)findViewById(R.id.button_search);
button2= (ImageButton)findViewById(R.id.button_addcontact);
button3= (ImageButton)findViewById(R.id.button_options);
setUpListView();
}
private void setUpListView(){
List <Contact> displayList = new ArrayList<Contact>();
displayList.add(new Contact("Anmol","Wadhwa","53743632"));
displayList.add(new Contact("Juhi","Goswami","4234232"));
displayList.add(new Contact("Laurence","Baldwick","243232"));
ListAdapter listAdapter = new CustomListAdapter(MainActivity.this,displayList);
listView.setAdapter(listAdapter);
}
private class CustomListAdapter extends ArrayAdapter<Contact>{
private Context _context;
private List<Contact> _contacts;
public CustomListAdapter(Context context, List<Contact> contacts){
super(context,android.R.layout.simple_list_item_1,contacts);
_context = context;
_contacts = contacts;
}
public View getView(int position, View convertView,ViewGroup parent){
//Create a layout inflater to inflate our xml layout for each item in the list
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the list item layout. Keep a reference to the inflated view.
//No root view specified
if (convertView == null)
View convertView = inflater.inflate(R.layout.custom_list_item_layout,null);
//Access TextView elements inside the view (note we must specify the parent view
//to look in)
TextView firstName = (TextView)convertView.findViewById(R.id.list_item_firstname);
TextView lastName = (TextView)convertView.findViewById(R.id.list_item_lastname);
TextView number = (TextView)convertView.findViewById(R.id.list_item_number);
//Set the text for each textview (use the position arugment to find the appropriate element in the list)
firstName.setText(_contacts.get(position).getFirstName());
lastName.setText(_contacts.get(position).getLastName());
number.setText(_contacts.get(position).getNumber());
//TODO add your data to the View
convertView.setTag(yourData)
return convertView;
}
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.action_groups:
Intent groupIntent = new Intent(this,Groups.class);
startActivity(groupIntent);
return true;
case R.id.action_favourites:
Intent favouriteIntent = new Intent(this,Favourites.class);
startActivity(favouriteIntent);
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return true;
}
public void addContact(View view){
Intent intent = new Intent(this,AddContact.class);
startActivity(intent);
}
Override
public void onItemClick(AdapterView<?> parentView, View clickedView, int clickedViewPosition, long id) {
ContactData cd = (ContactData)clickedView.getTag();
Bundle b = new Bundle();
// TODO put data from cd in that Bundle
Intent contactInfoIntent = new Intent(this, ContactInformation.class);
startActivity(contactInfoIntent);
}
}
besides, you usually do iOS development or am i wrong?
First argument of an Intent constructor requires an object of Context class. But you supplied an listItemClickedListener.class.
Intent constructor requeres:
Intent(Context, Class<?>)
you supplied:
Intent(listItemClickedListener, Class<?>)

how to use a custom button in a list to redirect the user to another activity

I've written a big code and I've used a list view within one of my task layouts :
I want to know how I can make a listener for each update button in this case in order to move to another activity , I know how to use more than one activity and moves between them But I want to know how to make a listener only .
The custom adapter code :
package com.example.task_9;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class TempLyaout extends ArrayAdapter<String> {
Context context;
ArrayList<String> sa;
public TempLyaout(Context context , ArrayList<String> sa) {
super(context,R.layout.temp,sa);
this.context=context;
this.sa = sa;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater l = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View rowView = l.inflate(R.layout.temp, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView1);
Button update = (Button) rowView.findViewById(R.id.button1);
// myDb.open();
// Cursor cursor= myDb.getRowByName(sa.get(position));
// myDb.updateRowByName(cursor.getInt(DBAdapter.COL_ROWID), sa.get(position), cursor.getString(DBAdapter.COL_PASSWD), cursor.getInt(DBAdapter.COL_AGE), isAdmin);
// myDb.close();
textView.setText(sa.get(position));
return rowView;
}
}
This is the related class :
package com.example.task_9;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class UsersActivity extends Activity {
Intent redirect;
ListView list;
ArrayList<String> sa;
DBAdapter myDb;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onStart() {
super.onStart();
setContentView(R.layout.users);
list= (ListView) findViewById(R.id.usersList);
redirect = getIntent();
openDB();
/*********************************************/
Cursor cursor = myDb.getAllRows();
cursor.moveToFirst();
ArrayList<String> ha = new ArrayList<String>();
while(cursor.moveToNext()) {
ha.add(cursor.getString(DBAdapter.COL_NAME));
}
cursor.close();
#SuppressWarnings("rawtypes")
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,ha);
list.setAdapter(new TempLyaout(UsersActivity.this,ha));
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
} // end onStart method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
} // end openDB method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void closeDB() {
myDb.close();
} // end closeDB method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
}// end main class
In your getView
Button update = (Button) rowView.findViewById(R.id.button1);
update.setOnClickListener(mClickListener);
Then
private OnClickListener mClickListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ListActivtiy.this,SecondActivity.class);
startActivity(intent);
}
};
Also use a viewholder for smooth scrolling and performance
http://developer.android.com/training/improving-layouts/smooth-scrolling.html

android checkbox onCheckedChanged is not invoked

I have defined onCheckedChanged for the checkbox in my listview.
When i click on the check box to check / uncheck it this function is getting invoked.
But when i setthe state of the check box from code like
check.setChecked(true);
the onCheckedChanged is not getting invoked.
Please help.
Adapter file :
package com.idg.project.adapters;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import com.idg.project.R;
import com.idg.project.activities.ScanListActivity;
import com.idg.project.activities.SearchResultActivity;
import com.idg.project.adapters.WishListAdapter.ViewHolder;
import com.idg.project.entity.ScannedProduct;
public class ScanListAdapter extends BaseAdapter {
private Context context;
private List<ScannedProduct> productList;
protected LayoutInflater mInflater;
Button showOrHideButton;
static public int count = 0;
String barcodeForSelectedRow;
String formatForSelectedRow;
OnItemClickListener rowListener;
Activity parentActivity;
boolean isWishList;
public ScanListAdapter(Context context, List<ScannedProduct> objects,
Button button, Activity parentActivity) {
super();
this.productList = objects;
this.context = context;
this.mInflater = LayoutInflater.from(context);
showOrHideButton = button;
this.parentActivity = parentActivity;
this.isWishList = isWishList;
}
public int getCount() {
return productList.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final int pos = position;
Log.i("checkboxflag at : ", pos+"is"+(productList.get(pos).getCheckboxflag()));
Log.i("getview : fresh", "getview"+pos);
convertView = mInflater.inflate(R.layout.product_list_row, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.productid);
holder.text1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(parentActivity,
SearchResultActivity.class);
intent.putExtra("barcode", productList.get(pos)
.getBarcode());
intent.putExtra("format", productList.get(pos).getFormat());
intent.putExtra("IsScan", false);
Log.i("", "" + productList.get(pos).getBarcode());
parentActivity.startActivity(intent);
Log.i("", "" + pos);
}
});
holder.text2 = (TextView) convertView.findViewById(R.id.price);
// holder.text2.setOnClickListener(listener);
holder.image = (ImageView) convertView
.findViewById(R.id.productimageid);
convertView.setTag(holder);
// holder.image.setOnClickListener(listener);
holder.text1.setText(productList.get(position).getTitle());
holder.text2.setText(productList.get(position).getPrice().toString());
if (productList.get(position).getSmallImage() != null) {
byte[] bb = (productList.get(position).getSmallImage());
holder.image.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0,
bb.length));
} else {
holder.image.setImageBitmap(null);
holder.image.setBackgroundResource(R.drawable.highlight_disabled);
}
// holder.image.setImageBitmap(Utils.loadBitmap(productList.get(position).getSmallImage()));
final CheckBox check = (CheckBox) convertView
.findViewById(R.id.checkbox);
check.setClickable(true); // to remove anything carried over from prev convert view
if(productList.get(pos).getCheckboxflag()==1)
{
Log.i("CheckBox set checked",""+pos);
check.setChecked(true);
}
else{
Log.i("CheckBox set unchecked",""+pos);
check.setChecked(false);
}
setWishListItemsInScanList(pos, convertView);
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Log.i("OnclickListener","Current Position"+pos);
if (check.isChecked()
&& productList.get(pos).getWishListFlag() == 0) {
if(check.isClickable()){
Log.i("CheckBox check",""+pos);
ScanListActivity.updateCheckBoxSelection(1, pos);
ScanListAdapter.count++;
}
} else if (!check.isChecked()
&& productList.get(pos).getWishListFlag() == 0){
if(check.isClickable()){
ScanListActivity.updateCheckBoxSelection(0, pos);
ScanListAdapter.count--;
Log.i("CheckBox UNcheck",""+pos);
}
}
if (ScanListAdapter.count == 0) {
// showOrHideButton.setClickable(false);
// showOrHideButton.setVisibility(View.GONE);
showOrHideButton.setEnabled(false);
} else {
// showOrHideButton.setVisibility(View.VISIBLE);
showOrHideButton.setEnabled(true);
}
}
});
return convertView;
}
private void setWishListItemsInScanList(int pos, View convertView) {
if (productList.get(pos).getWishListFlag() == 1) {
Log.i("CheckBox set checked from wish list",""+pos);
CheckBox check = (CheckBox) convertView.findViewById(R.id.checkbox);
check.setClickable(false);
check.setChecked(true);
}
}
static class ViewHolder {
TextView text1;
ImageView image;
TextView text2;
}
}
List activity file :
package com.idg.project.activities;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.idg.project.R;
import com.idg.project.adapters.WishListAdapter;
import com.idg.project.adapters.ScanListAdapter;
import com.idg.project.entity.ScannedProduct;
import com.idg.project.services.ScannedProductDataAccessManager;
public class ScanListActivity extends BaseActivity {
static Button scanlist;
ScanListAdapter listAdapter;
static List<ScannedProduct> productList;
/* Notes for the Developer :
* For tracking the checked items Checkboxflag
* is maintained.
* Point1 : Select all will just set this flag in the local list and then call notifyDatachange of the adapter
* within adapter the check box is set or reset based on this flag for each row
*
* Point 2: When individual rows are selected , there is an onclick of the check box is invoked
* Here the Checkboxflag of the local list is set /unset . Also we need a way to knpw the select all button is
* to enabled or diabled. for that Count variable is updated here.
* Now Important point is these two actions shoulnt be taking place if the checkbox state change due to select all
* So there is a special check of isclickable in the onclicklistener
*
* Point 3: In scan list the items in the wish list are to be marked. This again needs special logic.
* This is done in the adapter code by checking all the rows whose wishListFlag is 1 and making it non clickable
*
* Important : Listview has the concept of ViewGroup and each view group is usually the rows fitting in the display screen
* so when we scroll, the viewGropu changes.
* Convertview is get reused for view groups. So need to careful undesired values that will be carried to next viewgroup*/
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.scan_list);
productList = new ArrayList<ScannedProduct>();
productList = getProductList();
for(int i=0;i<productList.size();i++){
Log.i("checkboxflag at : ", i+"is"+(productList.get(i).getCheckboxflag()));
}
final ListView lv = (ListView) findViewById(R.id.list);
scanlist = (Button) findViewById(R.id.addtowishlist);
scanlist.setEnabled(false);
listAdapter = new ScanListAdapter(this, productList, scanlist, this);
lv.setAdapter(listAdapter);
}
private List<ScannedProduct> getProductList() {
List<ScannedProduct> productList = new ArrayList<ScannedProduct>();
ScannedProductDataAccessManager productDataBaseManager = new ScannedProductDataAccessManager(
getApplicationContext());
String[] colList = { "title", "smallImage", "price" };
productList = productDataBaseManager.fetchAllProducts();
return productList;
}
static boolean selectFlag = false;
public void selectAll(View view) {
ListView listView = (ListView) findViewById(R.id.list);
view = findViewById(R.id.select_all);
if (selectFlag == false) {
for (int i = 0; i < listView.getAdapter().getCount(); i++) {
productList.get(i).setCheckboxflag(1);
}
view.setBackgroundResource(R.drawable.login_remme_dwn_btn);
selectFlag = true;
TextView text=(TextView) findViewById(R.id.select);
text.setText("Unselect All");
scanlist.setEnabled(true);
} else {
for (int i = 0; i < listView.getAdapter().getCount(); i++) {
productList.get(i).setCheckboxflag(0);
}
view.setBackgroundResource(R.drawable.login_remme_up_btn);
selectFlag = false;
TextView text=(TextView) findViewById(R.id.select);
text.setText("Select All");
scanlist.setEnabled(false);
}
((BaseAdapter)listView.getAdapter()).notifyDataSetChanged(); // we are only setting the flags in the list
// so need to notify adapter to reflect same on checkbox state
//listView.refreshDrawableState();
}
public void addToWishList(View view) {
ListView listView = (ListView) findViewById(R.id.list);
for (int i = 0; i < listView.getAdapter().getCount(); i++) {
ScannedProduct product = productList.get(i);
if (product.getWishListFlag() == 0 && product.getCheckboxflag()==1) {
product.setWishListFlag(1);
new ScannedProductDataAccessManager(getApplicationContext())
.updateProduct(product, "title",
new String[] { product.getTitle() });
product.setCheckboxflag(0);
//ScanListAdapter.count--;
}
Log.i("ScanList selected", product.getTitle());
}
Toast.makeText(getApplicationContext(),
"Added selected items to Wish List", Toast.LENGTH_SHORT).show();
scanlist.setEnabled(false);
((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
}
static public void updateCheckBoxSelection(int flag,int pos){ // when individual row check box is checked/ unchecked
// this fn is called from adapter to update the list
productList.get(pos).setCheckboxflag(flag);
}
}
Since your checkbox is inside listview, so you need to call notifyDataSetChanged method on your list's adapter to refresh it's contents.
update
instead of ((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();, try calling listAdapter.notifyDataSetChanged();
I got the answer / bug in my code
i am not reusing convertview so its every time a new holder.
I am changing the flag of the checkbox and then assigning a statechange listener for the checkbox
thus its not getting invoked
when i changed the order to assign checkchangelistener before actually changing the state , its working as expected. The listener is getting called.
thanks all of you

Categories

Resources