I want to retrieve all the records from table and show it in another activity,but when I do I am getting one record at a time and in reverse order.
I want all the records in single activity
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ViewAllActivity.class);//
while (c.moveToNext()) {
i.putExtra("rollno", c.getString(0));
i.putExtra("name", c.getString(1));
i.putExtra("marks", c.getString(2));
startActivity(i);
}
}
});
ViewAllActivity
String rollno=getIntent().getStringExtra("rollno");
String name=getIntent().getStringExtra("name");
String marks=getIntent().getStringExtra("marks");
TextView text;
text=(TextView) findViewById(R.id.text);
String str="Roll no:"+rollno+"\nName:"+name+"\nmarks:"+marks;
text.setText(str);
You have to create a model for doing the same..
example :
ArrayList<myModel> modelList = new ArrayList<>();
while(c.moveToNext()){
MyModel myModel = new MyModel();
myModel.setRollNumber(c.getString(0));
myModel.setName(c.getString(1));
myModel.setMark(c.getString(2));
modelList.add(myModel);
}
}
});
intent.putParcelableArrayListExtra(TAG, modelList);
startActivity(intent);
MyModel
public class MyModel implements Parcelable{
private String rollNumber;
private String name;
private String mark;
public void setRollNumner(String rollNumber){
this.rollNumber = rillNumber;
}
.....
}
the model should implement Parcelable or Serializable
I'l prefer just start your activity in the button click, and retrieve the data in the second activity.
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ViewAllActivity.class);
startActivity(i);
}
});
ViewAllActivity
//retrieve data to your cursor
String str = "";
while(c.moveToNext()){
str = str + "Roll no:" + rollno + "\nName:" + name + "\nmarks:" + marks;
text.setText(str);
}
If i were you i just start new intent activity and in some method in the second activity, oncreate or onstart retrieve your data from db.
But if you want to send your data in a bundle to the another one, you have to consider something
1.- you have to create a lis of your objets to send.
2.- to send arraylist or objects with a bundle you have to implement and extend Parcelable interface, otherwise will fail.
3.- if you use to send data vía bundle, is not good idea, could weak your performance, just think if your list are many objects, and you want to send vis bundle, app will bd slow. So think about.
Regards.
Related
This is the activity where I defined the checkboxes and Array list.
I have save the result in the arraylist and want to display the same arraylist in another activity.
public ArrayList<String> Result;
Result = new ArrayList<>();
public void statuscheck(){
bcg.setOnClickListener(v -> {
if(bcg.isChecked()){
Result.add("BCG(Bacillus Calmette and Guérin)");
}
else {
Result.remove("BCG(Bacillus Calmette and Guérin)");
}
});
bopv0.setOnClickListener(v -> {
if(bopv0.isChecked()){
Result.add("b Oral Polio vaccine(bOPV)-0 ");
}
else {
Result.remove("b Oral Polio vaccine(bOPV)-0 ");
}
});
hepatitis0.setOnClickListener(v -> {
if(hepatitis0.isChecked()){
Result.add("Hepatitis B birth dose ");
}
else {
Result.remove("Hepatitis B birth dose ");
}
});
}
the activity where I want to show the arraylist in a text view
TextView vac_result;
ArrayList<String> vc_Res;
vac_result = findViewById(R.id.vac_result);
vac_result.setEnabled(false);
vc_Res = vaccineone.Result;
StringBuilder stringBuilder = new StringBuilder();
for(String s : vc_Res)
stringBuilder.append("\n");
vac_result.setText(stringBuilder.toString());
vac_result.setEnabled(true);
There are many ways to achieve what you want. You can either pass your data as a Bundle when you're trying to call startActivity() or use a static global variable across your application.
The snippet below will demonstrate how to use a static variable:
class Example {
public static ArrayList<String> Result = new ArrayList<>();
}
Fill the static arraylist with your data and simply get the data in the other activity.
Save the "Result" ArrayList with SharedPreferences and in the other activity load the data before trying to work with it.
I am storing my JSON data into a arraylist of objects, my object class is Venue and I am passing that data into another activity using serializable from fragment but I am not receiving any values in the actvity. It is receiving the extra. bundle is not null.
My code is:
Fragment:
Intent intent = new Intent(getActivity(), SearchVenueActivity.class);
//pass values
Bundle bundle = new Bundle();
bundle.putSerializable("arrayListVenue",arrayListVenue);
intent.putExtras(bundle);
startActivity(intent);
Activity:
if (getIntent().hasExtra("arrayListVenue")) {
Bundle bundle = getIntent().getExtras();
if(bundle!=null)
rowItems = (ArrayList<Venue>) bundle.getSerializable("arrayListVenue");
else
Log.e("null","null");
}
Venue Class:
public class Venue implements Serializable{
String venue_id;
String venue_name;
String venue_address;
String venue_city;
public String getVenue_city() {
return venue_city;
}
public void setVenue_city(String venue_city) {
this.venue_city = venue_city;
}
public Venue(String venue_id, String venue_name, String venue_address, String venue_city, String venue_zip, String venue_phone, String venue_mobile) {
this.venue_id = venue_id;
this.venue_name = venue_name;
this.venue_address = venue_address;
this.venue_city = venue_city;
this.venue_zip = venue_zip;
this.venue_phone = venue_phone;
this.venue_mobile = venue_mobile;
}
public String getVenue_id() {
return venue_id;
}
public void setVenue_id(String venue_id) {
this.venue_id = venue_id;
}
public String getVenue_name() {
return venue_name;
}
public void setVenue_name(String venue_name) {
this.venue_name = venue_name;
}
}
try this way may this help you
First you want to make
Class Venue implements Serializable
public class Venue implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
}
In your FirstActivity do this way
ArrayList<Venue> VenueArrayList = new ArrayList<Venue>();
Intent intent = new Intent(this,secondActivity.class);
intent.putExtra("VenueArrayList", VenueArrayList);
In your SecondActivity do this way
ArrayList<Venue> VenueArrayList;
VenueArrayList = (ArrayList<Venue>) getIntent().getSerializableExtra(
"VenueArrayList");
Learn from my mistakes.
I've tried to send Arrays and big objects using Serializablethen my app got really slow. Did some tests and found out that when it took a lot of cpu and time to parse it. Therefore (altough its not what you would call best practice) i've created a CacheManager that store object for short time periods and used it to pass larger object between fragments activities.
If you want to make a more readical change to your design (later on in my project i did exactly that) then seperate the data from your fragment/activity completely and load it by LoaderManagers and pass only specific id's or stuff like that (stored stuff in the db in my case so it was easier).
Use intent.putParcelableArrayListExtra("arrayListVenue",arrayListVenue); for putting arraylist to intent and use intent.getParcelableArrayExtra("arrayListVenue") for get arraylist back from intent in your SearchVenueActivity activity
Edit
Tutorial for using parcelable
Use Array List instead of Bundle Elements.
In your Main Activity, try this:
Intent intent = new Intent(this, newactivity.class);
intent.putParceableListArrayExtra("your_array_list_name", arrayList);
In the next activity where you want to retreive it, just use:
getIntent().getExtra("your_array_list_name", new ArrayList<> arrayList2);
I would like to parse a list of data from one intent to another intent
However, with my code,
I'm only manage to pass the first item in the listview .
I use a log.d to check for the items, and realised that only one items is being pass.
In my listview there's 2 items,when I pass it over to my next intent, only one item was shown in the log..
I did a serializable in my class.
I make a log in my summary,
however,
when I click on summary, the log that was shown in not all the data.
logcat:
01-28 18:20:49.218: D/Bundle(20278): bundle : Bundle[{clickedpreOdometer=, clickedID=2, clickedCost= 12.0, clickedDate=27/12/2014, pojoArrayList=[com.example.fuellogproject.fuelLogPojo#43bf3f18, com.example.fuellogproject.fuelLogPojo#43bf5b68], clickedPump=3, clickedPrice=4, clickedFCon= 0.0, clickedOdometer=3}]
listview
public void summaryClick (View v)
{
Intent sum = new Intent(this, summary.class);
fuelLogPojo clickedObject = pojoArrayList.get(0);
Bundle dataBundle = new Bundle();
dataBundle.putString("clickedID", clickedObject.getid());
dataBundle.putString("clickedDate", clickedObject.getdate());
dataBundle.putString("clickedPrice", clickedObject.getprice());
dataBundle.putString("clickedPump", clickedObject.getpump());
dataBundle.putString("clickedCost", clickedObject.getcost());
dataBundle.putString("clickedOdometer", clickedObject.getodometer());
dataBundle.putString("clickedpreOdometer",
clickedObject.getpreodometer());
dataBundle.putString("clickedFCon", clickedObject.getfcon());
dataBundle.putSerializable("pojoArrayList", pojoArrayList);
Log.i("FuelLog", "dataBundle " + dataBundle);
// Attach the bundled data to the intent
// sum.putExtras(dataBundle);
sum.putExtras(dataBundle);
Log.i("Exrrass", "dataBundle " + dataBundle);
// Start the Activity
startActivity(sum);
}
summary.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
//month = (TextView)findViewById(R.id.month);
avgPrice = (TextView)findViewById(R.id.showavfPriceTV);
exFuel = (TextView)findViewById(R.id.showexFuelTV);
avgFC = (TextView)findViewById(R.id.showavgFCTV);
doneButton = (Button)findViewById(R.id.doneBTN);
exitButton = (Button)findViewById(R.id.exitBTN);
Bundle takeBundledData = getIntent().getExtras();
// First we need to get the bundle data that pass from the UndergraduateListActivity
bundleID = takeBundledData.getString("clickedID");
/*bundleDate = takeBundledData.getString("clickedDate");
bundlePrice = takeBundledData.getString("clickedPrice");
bundlePump = takeBundledData.getString("clickedPump");
bundleCost = takeBundledData.getString("clickedCost");
bundleOdometer = takeBundledData.getString("clickedOdometer");
bundlePreOdometer = takeBundledData.getString("clickedpreOdometer");
bundleFcon = takeBundledData.getString("clickedFCon");*/
Log.d("Bundle","bundle : "+ takeBundledData);
}
fuelLogpojo.java
public class fuelLogPojo implements Serializable{
fuelLogPojo should implement either Parcelable or Serializable
Bundles can accept custom classes, if they implement either Parcelable or Serializable, Parcelable is faster but more work to implement and Serializable is easier to implement, but slower.
I'm going to imagine that fuelLogPojo extends Serializable in this example, just because its easier to setup but you should really consider Parcelable
Then you can do this:
dataBundle.putSerializable("pojoArrayList", pojoArrayList);
sum.setArguments(bundle);
Also, you should reconsider the naming convention for your classes.
EDIT:
Here's how to access that pojoArrayList in summary.
List<fuelLogPojo> pojoArrayList = (List<fuelLogPojo>)extras.getSerializable("pojoArrayList");
If you want to pass array of Custom Objects You have to implements Parcerable interface
Take a look here
And then pass array like
Intent i=...
i.putParcelableArrayListExtra("ARRAY", array);
and read it
getIntent().getParcelableArrayListExtra("ARRAY")
i'm continuously running into problems trying to pass an ArrayList from one Activity to another. My code is failing with a Null Pointer Exception when i try to iterate through the ArrayList in my XMLParser Class. I've put print statements into the Activity that generates the ArrayList and it looks fine. Can anyone see what i'm doing wrong or why i get a Null pointer Exception when retrieving the ArrayList?
public void onClick(View v) {
if (selItemArray[0] == null) {
Toast.makeText(getApplicationContext()," Please make a Selection ", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(Recipes2.this, XMLParser.class);
Log.v("Recipes2", "selItemArray[0] before call to XML Parser : " + selItemArray[0]);
//Log.v("Recipes2", "selItemArray[1] before call to XML Parser : " + selItemArray[1]);
intent.putExtra("items_to_parse", selItemArray);
startActivityForResult(intent, 0);
}
}
public class XMLParser extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Bundle b = getIntent().getExtras();
//itemsToParse = b.getStringArrayList("items_to_parse");
ArrayList<String> itemsToParse = new ArrayList<String>();
itemsToParse = getIntent().getExtras().getStringArrayList("items_to_parse"); Iterator<String> iterator = itemsToParse.iterator(); while(iterator.hasNext())
Log.v("XMLParser", iterator.next().toString());
It looks like you're putting a String array, not a ArrayList<String>.
You used a string array on the "sender" side and are trying to get it back as an ArrayList on the receiver side. That won't work. Use a String array on both sides and -- if necessary -- pull it into an array list.
The procedure for passing the data is here:
Passing String array between two class in android application
To convert it to a List - simply do:
List<String> = Arrays.asList(stringArray);
So I've been googling most of yesterday and last nite and just can't seem to wrap my head around how to pass an arraylist to a subactivity. There are tons of examples and snippets passing primitive data types, but what I have is an arraylist of type address (address.java below).
I've found a lot of stuff on stackoverflow and around the web on this, but nothing that got a lot of attention except for one with a GeoPoint example. Again, it looked to me like they just flattened the GeoPoint object into two integers and passed it in. I can't do that because my address class may expand to include integers, floats, whatever. Right now, the test app below is only two strings for simplicity. I thought if I could get the parcelalbe stuff working with that, the rest could follow.
Can someone post a working example for an ArrayList of a non-primitive object, or perhaps add code below to make this work?
UPDATE: code below is now working after replies/editing. Thanks!
/* helloParcel.java */
public class helloParcel extends Activity
{
// holds objects of type 'address' == name and state
private ArrayList <address> myList;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
setContentView (R.layout.main);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(ocl);
myList = new ArrayList();
address frank = new address ("frank", "florida");
address mary = new address ("mary", "maryland");
address monty = new address ("monty", "montana");
myList.add (frank);
myList.add (mary);
myList.add (monty);
// add the myList ArrayList() the the extras for the intent
}
OnClickListener ocl = new OnClickListener()
{
#Override
public void onClick(View v)
{
// fill parceable and launch activity
Intent intent = new Intent().setClass(getBaseContext (), subActivity.class);
// for some reason, I remember a posting saying it's best to create a new
// object to pass. I have no idea why..
ArrayList <address> addyExtras = new ArrayList <address>();
for (int i = 0; i < myList.size(); i++)
addyExtras.add (myList.get(i));
intent.putParcelableArrayListExtra ("mylist", addyExtras);
startActivity(intent);
}
};
}
/* address.java */
public class address implements Parcelable
{
private String name;
private String state;
private static String TAG = "** address **";
public address (String n, String s)
{
name = n;
state = s;
Log.d (TAG, "new address");
}
public address (Parcel in)
{
Log.d (TAG, "parcel in");
name = in.readString ();
state = in.readString ();
}
public String getState ()
{
Log.d (TAG, "getState()");
return (state);
}
public String getName ()
{
Log.d (TAG, "getName()");
return (name);
}
public static final Parcelable.Creator<address> CREATOR
= new Parcelable.Creator<address>()
{
public address createFromParcel(Parcel in)
{
Log.d (TAG, "createFromParcel()");
return new address(in);
}
public address[] newArray (int size)
{
Log.d (TAG, "createFromParcel() newArray ");
return new address[size];
}
};
#Override
public int describeContents ()
{
Log.d (TAG, "describe()");
return 0;
}
#Override
public void writeToParcel (Parcel dest, int flags)
{
Log.d (TAG, "writeToParcel");
dest.writeString (name);
dest.writeString (state);
}
}
/* subActivity.java */
public class subActivity extends Activity
{
private final String TAG = "** subActivity **";
private ArrayList <address> myList;
#Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
Log.d (TAG, "onCreate() in subActivity");
setContentView(R.layout.subactivity);
TextView tv1 = (TextView) findViewById(R.id.tv_sub);
myList = getIntent().getParcelableArrayListExtra ("mylist");
Log.d (TAG, "got myList");
for (int i = 0; i < myList.size (); i++)
{
address a = myList.get (i);
Log.d (TAG, "state:" + a.getState ());
tv1.setText (a.getName () + " is from " + a.getState ());
}
}
}
I can see a number of problems here:
Why use addressParcelable? Why not make address implement Parcelable, and then use:
intent.putParcelableArrayListExtra( "addresses", addyExtras );
Your parcelable object must include a static CREATOR. See the documentation for details.
You are not actually adding any extras to the intent before you call startActivity(). See point 1 for a suggestion here.
I think that you will need to address all of these issues in order to get it working.
It can be done MUCH simpler, without all the pain-in-the-ass of implementing Parcelable...
ArrayList (but NOT any List) is Serializable. So, you can put the entire list using putExtra() and retrieve it using getSerializableExtra(), as Sam said.
BUT, I want to add one more important thing: the object your array list stores has to also implement Serializable... and all other complex objects that the object may contain (in your case none) must also implement that (so it's recursive - in order to serialize an object, you must be able to serialize all of its fields).
Now, you might be asking yourself why implementing Serializable instead of Parcelable when there are already methods for reading and writing array lists of parcelables?
Well... the difference is simplicity - just add implements Serializable and optionally private static final long serialVersionUID = SOME_CONSTANT and you're DONE! That is the reason why I never use Parcelable - you can do all those things using Serializable with literally 2 lines of code - instead of many method inheritances and all that stuff...
You can pass Serializable objects via putExtra. ArrayList implements Serializable.
Mike dg is correct!
putExtra() and getSerializable() will store and retrieve an ArrayList<> of your custom objects, with no interface implementing required. Worked for me!