Click on ListView item not opening new Activity - android

I have a ListView "resultList", but clicking on an item is not opening the new (detailed) Activity. What's my mistake?
Thank you!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.resultList = (ListView) findViewById(R.id.resultList) ;
this.dataSource = MyExpenseOpenHandler.getInstance(this).readAllExpenses();
this.adapter = new ExpenseOverviewAdapter(this, dataSource);
this.resultList.setAdapter(adapter);
this.resultList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, View view, final int i, final long l) {
Object element = adapterView.getAdapter().getItem(i);
if (element instanceof Expense) {
Expense expense = (Expense) element;
Intent intent = new Intent(MainActivity.this, ExpenseDetailActivity.class);
intent.putExtra(ExpenseDetailActivity.EXPENSE_KEY, expense);
startActivity(intent);
}
Log.e("Click on List: ", element.toString());
}
});
}

Your code seems alright .I think the problem is that your if condition may be returning false and the code inside the if statement is not being executed.You can put a log message inside the if statement to check if the code is being executed.
if (element instanceof Expense) {
Log.d(YOUR_LOG_TAG,"The if condition not executed")
Expense expense = (Expense) element;
Intent intent = new Intent(MainActivity.this, ExpenseDetailActivity.class);
intent.putExtra(ExpenseDetailActivity.EXPENSE_KEY, expense);
startActivity(intent);
}
If you see the log message in your android monitor you can be sure that the code inside your if condition is not executed and hence your activity is not starting.

Did you implement Parcelable on your class Expense ?
Something like this
public class Expense implements Parcelable{
private String id;
private String name;
private String grade;
// Constructor
public Expense(String id, String name, String grade){
this.id = id;
this.name = name;
this.grade = grade;
}
// Getter and setter methods
.........
.........
// Parcelling part
public Expense(Parcel in){
String[] data = new String[3];
in.readStringArray(data);
// the order needs to be the same as in writeToParcel() method
this.id = data[0];
this.name = data[1];
this.grade = data[2];
}
#Оverride
public int describeContents(){
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.id,
this.name,
this.grade});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Expense createFromParcel(Parcel in) {
return new Expense(in);
}
public Expense[] newArray(int size) {
return new Expense[size];
}
};
}

what kind of view in the list, if the child view get the focus like button may lead to item click not work well.
you can try to add android:descendantFocusability="beforeDescendants" in you listview.

Related

parse arraylist form one fragment to another fragment in android

How I can parse Arraylist of JSON from one Fragment to another fragment here is my arraylist code where I am getting arraylist from my model:
private void setListOffers(JSONArray categoryArray) {
for (int i = 0; i < categoryArray.length(); i++) {
try {
JSONObject object = categoryArray.getJSONObject(i);
hotDealID = object.getInt("ID");
deals.add(new ListOffers(hotDealID));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here I am sending data from fraggment:
private ArrayList<ListOffers> deals = new ArrayList<>();
Fragment fragment = new HotDealFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("dealsId", deals);
fragment.setArguments(bundle);
When I put this code then deals gives exception that wrong second argument and ListOffers is my model where I am fetching data
and here is my model list Offers:
private int Id;
public ListOffers(int Id){
this.Id = Id;
}
public void setId(int id) {
Id = id;
}
public int getId() {
return Id;
}
One possible problem:
Your ListOffers model does not implement parcelable. Your model should implement parcelable. You can get help from this link
https://github.com/codepath/android_guides/wiki/Using-Parcelable
import android.os.Parcel;
import android.os.Parcelable;
public class ListOffers implements Parcelable {
private int Id;
public ListOffers(int Id) {
this.Id = Id;
}
public void setId(int id) {
Id = id;
}
public int getId() {
return Id;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(Id);
}
protected ListOffers(Parcel in) {
Id = in.readInt();
}
public static final Creator<ListOffers> CREATOR = new Creator<ListOffers>() {
#Override
public ListOffers createFromParcel(Parcel in) {
return new ListOffers(in);
}
#Override
public ListOffers[] newArray(int size) {
return new ListOffers[size];
}
};
}
Using hashmap you can pass
HashMap <String,ArrayList<ListOffers>> hashMap;
Bundle extras = new Bundle();
extras.putSerializable("HashMap",hashMap);
intent.putExtras(extras);
And get it using below code
Intent intent = getIntent();
hasMap= intent.getSerializableExtra("hashMap");
your datamodel ListOffers should be implement the Parcelable then only you can pass as ParcelableArrayList.
refer
Help passing an ArrayList of Objects to a new Activity
Using Parcelable your model will be
public class ListOffers implements Parcelable {
private int Id;
/**
* Constructs a Model from a Parcel
*
* #param parcel Source Parcel
*/
public ListOffers(Parcel parcel) {
this.Id = parcel.readInt();
}
public ListOffers(int Id) {
this.Id = Id;
}
public void setId(int id) {
Id = id;
}
public int getId() {
return Id;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(Id);
}
// Method to recreate a Model from a Parcel
public static Creator<ListOffers> CREATOR = new Creator<ListOffers>() {
#Override
public ListOffers createFromParcel(Parcel source) {
return new ListOffers(source);
}
#Override
public ListOffers[] newArray(int size) {
return new ListOffers[size];
}
};
}
Sending ParcelableArrayList from one fragment to other -
private ArrayList<ListOffers> deals = new ArrayList<>();
setListOffers(categoryArray);
Fragment fragment = new HotDealFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("dealsId", deals);
fragment.setArguments(bundle);
Fetching it into other Fragment in it's onCreate -
ArrayList<ListOffers> deals = new ArrayList<>();
if (getArguments() != null) {
deals = getArguments().getParcelableArrayList("dealsId");
}
Hope this will help you :)
Here is an easier approach.
Most times when one wants to send this data is because they want it to be accessed in the new class for just a short time. Instead of sending the data every time, go to the fragment that contains the data and make it public and static.
public static ArrayList<ListOffers> deals;
Access it in your desired activity
MainFragment.deals
Make your ListOffer implements Serializable and then use
private ArrayList<ListOffers> deals = new ArrayList<>();
Fragment fragment = new HotDealFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("dealsId", deals);
fragment.setArguments(bundle);
Here is how to get that
if (getArguments() != null) {
mdealsId = (ListOffers)getArguments().getSerializable("dealsId");
}

I have listview connected to database, when i click on any item in listview i want to fetch data for the particular item in next activity

Here is the Listview I want it to fetch data for a particular item from Database and fetch it to 2nd Activity and put it in the Edittext.
#Override
protected void onStart() {
super.onStart();
mArrayList.clear();
ArrayList<String> ar = new ArrayList<String>();
final List<DatabaseAccounts> data = dB.getallrows();
list = (ListView)findViewById(R.id.listView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DatabaseAccounts dbAccount = data.get(position);
Intent intent = new Intent(getApplicationContext(),Diary2.class);
startActivity(intent);
}
});
for(DatabaseAccounts dbb : data){
mArrayList.add(dbb.getState());
}
mArrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,mArrayList);
list.setAdapter(mArrayAdapter);
}
First you need to implement Parcelable interface in your class:
public class Student implements Parcelable {
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int arg1) {
// TODO Auto-generated method stub
dest.writeInt(id);
dest.writeString(name);
}
public Student(Parcel in) {
id = in.readInt();
name = in.readString();
}
public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
public Student createFromParcel(Parcel in) {
return new Student(in);
}
public Student[] newArray(int size) {
return new Student[size];
}
};
}
And the list
ArrayList<Student> arraylist = new ArrayList<Student>();
Code from Calling activity
Intent intent = new Intent(this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("mylist", arraylist);
intent.putExtras(bundle);
this.startActivity(intent);
Code on called activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle bundle = getIntent().getExtras();
ArrayList<Student> arraylist = bundle.getParcelableArrayList("mylist");
}

Update an object passed through Parcelable intent

I'm new to Android and i'm still learning. I currently have a ListView which allows you to click on an item. Clicking on an item will open a new intent displaying extra information about the item.
The thing i'm tripping up on is figuring out how to get the updated values back into my custom object and update the values in array at the correct index.
For example:
I'll add an item and set it's quantity to 2. This will appear in my ListView. Great. I decide i need 3 instead of 2, so i click the item to open the new activity, see 2 sitting in quantity, update it to 3 and hit save. On the save click i want to go back to my listview and have the updated quantity value displaying there and also updated in the array at the index.
Code for segments:
Onclick method for the listview in ItemList class
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
bean = (CustomObject) listview.getItemAtPosition(arg2);
Intent in1 = new Intent(Itemlist.this, SingleItem.class);
in1.putExtra("ActivityObject", bean);
startActivity(in1);
}
});
Adding an item the array in my ItemList class. this contain the listview.
else {
objects.add(new CustomObject(roomname.getText().toString() + " - " + resultSet.get(namecount), resultSet.get(partno), itemq, "$" + resultSet.get(rrpcol), resultSet.get(glcode), resultSet.get(desc)));
adapter.notifyDataSetChanged();
SingleItem class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singleitem);
siname = (TextView) findViewById(R.id.siname);
sipartno = (TextView) findViewById(R.id.sipartno);
siquantity = (EditText) findViewById(R.id.siq);
sirrp = (EditText) findViewById(R.id.sirrp);
siglcode = (TextView) findViewById(R.id.siglcode);
sidesc = (EditText) findViewById(R.id.sidesc);
update = (Button) findViewById(R.id.siupdate);
Bundle b = getIntent().getExtras();
CustomObject itemInfo = b.getParcelable("ActivityObject");
siname.setText(itemInfo.getItemName());
sipartno.setText(itemInfo.getItemPartNo());
siquantity.setText(itemInfo.getItemQuantity());
sirrp.setText(itemInfo.getItemPrice());
siglcode.setText(itemInfo.getItemGLCode());
sidesc.setText(itemInfo.getItemDesc());
}
Custom Object class
public class CustomObject implements Parcelable {
private String itemName;
private String itemPartNo;
private String itemQuantity;
private String itemPrice;
private String itemGLCode;
private String itemDesc;
public CustomObject(Parcel source){
/*
* Reconstruct from the Parcel
*/
//Log.v(TAG, "ParcelData(Parcel source): time to put back parcel data");
//id = source.readInt();
itemName = source.readString();
itemPartNo = source.readString();
itemQuantity = source.readString();
itemPrice = source.readString();
itemGLCode = source.readString();
itemDesc = source.readString();
}
public CustomObject(String prop1, String prop2, String prop3, String prop4, String prop5, String prop6) {
this.itemName = prop1;
this.itemPartNo = prop2;
this.itemQuantity = prop3;
this.itemPrice = prop4;
this.itemGLCode = prop5;
this.itemDesc = prop6;
}
public String getItemName() {
return itemName;
}
public String getItemPartNo() { return itemPartNo; }
public String getItemQuantity() {
return itemQuantity;
}
public String getItemPrice() {
return itemPrice;
}
public String getItemGLCode() {return itemGLCode;}
public String getItemDesc() {return itemDesc;}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(itemName);
dest.writeString(itemPartNo);
dest.writeString(itemQuantity);
dest.writeString(itemPrice);
dest.writeString(itemGLCode);
dest.writeString(itemDesc);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public CustomObject createFromParcel(Parcel in) {
return new CustomObject(in);
}
public CustomObject[] newArray(int size) {
return new CustomObject[size];
}
};
}
I want to be able to change the quantity in the SingleItem class, click the Update button, and then have it load up the itemlist class with the updated values in the item list.
It'd be more efficient to use Fragments with your own callback interfaces defined for the activity. But, if you want to go the Activity approach, use startActivityForResult() and have your detail Activity send back a result Intent with any updates object contents.

get ArrayList<MyClass> with getIntent().getExtras()

in an activity from my app I have an Intent to start a new Activity and I want to pass an ArrayList i.e. an ArrayList where each item is an instance of a own class ... how can I make this?
I have been seeing possible getExtras() like getStringArrayList() or getParcelableArrayList() and it doesn't work, I haven't found any valid type.
Can anyone help me? Thanks.
This is my class:
public class ItemFile {
protected long id;
protected String nombre;
protected String rutaImagen;
protected boolean checked;
public ItemFile(long id, String nombre, String rutaImagen, boolean check) {
this.id = id;
this.nombre = nombre;
this.rutaImagen = rutaImagen;
this.checked = check;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getRutaImagen() {
return rutaImagen;
}
public void setRutaImagen(String rutaImagen) {
this.rutaImagen = rutaImagen;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked){
this.checked = checked;
}
}
How I must change it to set Parcelable?
First make sure MyClass class implements Parcelable interface then use this code for getting ArrayList in other Activity :
In your first activity do something like this:
ArrayList<MyClass> myClassList= new ArrayList<MyClass>();
Intent intent = new Intent(<YOUR ACTIVITY CONTEX>, <NEXT ACTIVITY>);
intent.putExtra("myClassList", myClassList);
startActivity(intent);
In your next activity do something like this:
ArrayList<MyClass> list = (ArrayList<MyClass>)getIntent().getExtras()getSerializable("myClassList");
Make MyClass Parcelable. See example below.
public class MyClass implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
// Send it using
ArrayList<MyClass> list;
intent.putParcelableArrayListExtra("list", list);
In First activity
ArrayList<MyClass> fileList = new ArrayList<MyClass>();
Intent intent = new Intent(MainActivity.this, secondActivity.class);
intent.putExtra("FILES_TO_SEND", fileList);
startActivity(intent);
In Secand
activity:ArrayList<MyClass> filelist =(ArrayList<MyClass>)getIntent().getSerializableExtra("FILES_TO_SEND");
I had been struggling with this myself but I found a fairly simple solution on tutorialspoint that worked well for me.
In the source activity, use
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key", numbers);
startActivity(intent);
Then in the destination activity, use
ArrayList<String> numbersList = (ArrayList<String>) getIntent().getSerializableExtra("key");
A link to the full tutorial is: https://www.tutorialspoint.com/how-to-pass-an-arraylist-to-another-activity-using-intents-in-android

Android ArrayAdapter with Object and Get some data from that object

Im trying to make ListView using data from Array, but I need to get Id of clicked row (not shown in that row, but userd in creation of that product)
Im using this class for object:
package com.example.raidplanner;
public class RaidWpis {
private int id;
private int id_gildia;
private String nazwa;
private int schemat;
private int data_zapis;
private int data_start;
private int opis;
private int id_officer;
private int nick_officer;
private int typ;
public RaidWpis(int id,String nazwa) {
setNazwa(nazwa);
setId(id);
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getNazwa() { return nazwa; }
public void setNazwa(String nazwa) { this.nazwa = nazwa; }
public String toString() {
return this.nazwa;
}
public String toString2() {
return this.id+" - "+nazwa;
}
}
And this code in Activity:
RaidWpis[] items = {
new RaidWpis(1, "aaaa"),
new RaidWpis(3, "bbbb"),
new RaidWpis(6, "cccc"),
new RaidWpis(11, "dddd"),
new RaidWpis(17, "eeee"),
};
mainListView = (ListView) findViewById( R.id.mainListView );
ArrayAdapter<RaidWpis> raidList = new ArrayAdapter<RaidWpis>(this, R.layout.simplerow, items);
// Create ArrayAdapter using the raid list.
mainListView.setAdapter(raidList);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
I need to get Id of clicked row (not shown in that row, but userd in creation of that product)
Try this in your onItemClick() method:
RaidWpis obj = parent.getAdapter().getItem(position); // or just raidList.get(position) if raidList is a field variable
Toast.makeText(getBaseContext(), obj.getID() + "", Toast.LENGTH_LONG).show();
from the position, you can get the RaidWpis Object by using raidList.get(position). Once you have this RaidWpis object, you can call getId() to get the id

Categories

Resources