I am trying to pass an ArrayList of type Album to another activity in Android Studio.
The problem is that the Lastfm API I am using does not implement Parcelable.
I tried making my own Album class and extending their Album class but I got the error
"there is no default constructor available in 'de.umass.lastfm.Album'
Quiz.java - intent.getParcel... not working as Album is not Parcelable
public class Quiz extends AppCompatActivity {
private static TextView tv_quiz;
private static EditText et_quiz;
private ArrayList<Album> albums;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
Intent intent = getIntent();
albums = intent.getParcelableArrayListExtra(MainActivity.ALBUMS_LIST);
}
}
The calling portion of my MainActivity.java.
Intent intent = new Intent(this, Quiz.class);
intent.putExtra(ALBUMS_LIST, allAlbums);
intent.putExtra(DIFFICULTY, difficulty);
startActivity(intent);
Is there any way I can get around this?
Thanks anyway
I took a look at the api you linked, and Album looks extremely difficult to parcel. I would say that you might be better off simply re-loading the list in the next Activity (rather than trying to pass the list).
The only way to "construct" a new Album instance is through the getInfo() static factory method. You could create a new class AlbumWrapper that is parcelable, send a list of AlbumWrapper through the Intent, and then use getInfo() on the other side to re-fetch the albums.
public class AlbumWrapper implements Parcelable {
// insert CREATOR here
public final String artist;
public final String mbid;
public AlbumWrapper(Album a) {
this.artist = a.getArtist();
this.mbid = a.getMbid();
}
private AlbumWrapper(Parcel in) {
this.artist = in.readString();
this.mbid = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(artist);
dest.writeString(mbid);
}
#Override
public int describeContents() {
return 0;
}
}
You can put your list of Albums in the intent like this:
ArrayList<AlbumWrapper> wrappers = new ArrayList<>();
for (Album album : albums) {
AlbumWrapper wrapper = new AlbumWrapper(album);
wrappers.add(wrapper);
}
intent.putParcelableArrayListExtra("ALBUM_WRAPPERS", wrappers);
And then in your next activity you can do something like:
List<AlbumWrapper> wrappers = getIntent().getParcelableArrayListExtra("ALBUM_WRAPPERS");
List<Album> albums = new ArrayList<>();
for (AlbumWrapper wrapper : wrappers) {
Album album = Album.getInfo(wrapper.artist, wrapper.mbid, YOUR_API_KEY);
albums.add(album);
}
Here is the solution
open activity using this code
Bundle bundle = new Bundle();
bundle.putSerializable("data", allAlbums);
bundle.putString(DIFFICULTY", difficulty);
Intent intent = new Intent(this, Quiz.class);
intent.putExtra(bundle);
startActivity(intent);
get intent data
albums = (ArrayList<Album>) getIntent().getExtras().getSerializable("data");
updated Album Class
public class Album implements java.io.Serializable {
//your code
}
Related
I am new in Android. I need your help. My Problem is - I have 2 classes Nplist.java and Addcustomer.java. In my AddCustomer class,One TextView and one Button is there to go Nplist class. In my Nplist class there is checklist and this checklist is coming from database and all the checked values are stored in ArrayList<String> and one Button is used to go back to AddCustomer class. I want that ArrayList<String> which is in Nplist to by display in my AddCustomer class Textview . I haved tried these but my Addcustomer class crashed.
1.Nplist.class
add.setOnClickListener(new View.OnClickListener() {<br>
#Override<br>
public void onClick(View view) {<br>
Bundle extra=new Bundle();<br>
extra.putSerializable("objects",checkedList);<br>
Intent intent = new Intent(Nplist.this, AddCustomer.class);<br>
intent.putExtra("extra",extra);<br>
startActivity(intent);<br>
});
2.AddCustomer.class
onCrete()...{
Bundle extra = getIntent().getBundleExtra("extra");<br>
ArrayList<String> object = (ArrayList<String>)extra.getSerializable("objects");<br>
for (String str : object) {<br>
getnp.append(str + "\n");<br>
}
}
What do you expect the result to be?
- What is the actual result you get? (Please include any errors.)
When i go like this Nplist-->AddCustomer its working well but crash on ( AddCustomer-->Nplist-->AddCustomer)
It's because when you are coming back to your AddCustomer Activity the list is null . You can solve this problem by making a global class which will store the list in a Static Field , And You can access that list from any class or Activity you want to. Try out below solution .
Global.java Class is as below :
public class Global {
private static ArrayList<String> object = new ArrayList<>();
public static ArrayList<String> getObject() {
return object;
}
public static void setObject(ArrayList<String> object) {
Global.object = object;
}
}
From NpList.java class set the value of the list as below :
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Global.setObject(checkedList);
Intent intent = new Intent(Nplist.this, AddCustomer.class);
startActivity(intent);
}
});
Now Access in AdCustomer.java as below :
onCreate()...{
Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<String> object = Global.getObject();
for (String str : object) {
getnp.append(str + "\n");
}
}
This maybe helpful for you.
Using putStringArrayListExtra method you can send an array list of strings along with the intent.
Sender side:
Intent intent = ...
intent.putStringArrayListExtra("THE_KEY", theList);
Receiver side:
ArrayList<String> theList = intent.getStringArrayListExtra("THE_KEY");
I'm trying to create an app like shopping cart
Using this to access my database http://www.tutecentral.com/restful-api-for-android-part-2/
And i'm stuck at adding products to cart, so far I understand that the selected products go to arraylist in a few tutorials. In the code below I have two Activities, the MaterialView (this shows the details of the materials and has the option to add to cart), and the MaterialCart (shows the list of selected products.)
this is the block of code in MaterialView to send the values to MaterialCart
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
Intent i=new Intent(MaterialView.this, MaterialCart.class);
i.putExtra("mID", mid);
i.putExtra("name", Name.getText().toString());
i.putExtra("qty", Qty.getText().toString());
i.putExtra("price", Price.getText().toString());
i.putExtra("stock", Stock.getText().toString());
i.putExtra("rqQty", RqQty.getText().toString());
startActivity(i);
Toast.makeText(MaterialView.this, "Added Succesfully.", Toast.LENGTH_LONG).show();
}
} );
I have used Intent to pass the values (I'm pretty sure this method is wrong, I also tried calling the MaterialCart class itself to access the arrayList so I can add values and it didn't work)
This is the block of codes in my MaterialCart to receive the values
public class MaterialCart extends Activity {
final ArrayList<PropertyCartTable> materialProperties = new ArrayList<>();
#SuppressLint("LongLogTag")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_material_cart);
Intent i = new Intent();
Bundle extras = getIntent().getExtras();
try{
String Name = extras.getString("name");
String Qty = extras.getString("qty");
String Price = extras.getString("price");
String Stock = extras.getString("stock");
String RqQty = extras.getString("rqQty");
String ID = extras.getString("mID");
Log.d("EXTRAS:", Name + " " + Qty + " " + ID);
materialProperties.add(new PropertyCartTable( ID,Name,Qty,Price,Stock,RqQty));
getIntent().removeExtra("Name");
getIntent().removeExtra("Qty");
getIntent().removeExtra("Price");
getIntent().removeExtra("Stock");
getIntent().removeExtra("RqQty");
getIntent().removeExtra("MID");
}
catch (Exception h){
Log.d("Exception!",h.toString());
}
// materialProperties.add(array);
Log.d("MaterialView.Cart isEmpty", String.valueOf(materialProperties.isEmpty()));
if(materialProperties.isEmpty()) {
Toast.makeText(this, "You have no materials to request.", Toast.LENGTH_LONG).show();
i = new Intent(MaterialCart.this, ProductDetails.class);
startActivity(i);
}else{
ArrayAdapter<PropertyCartTable> adapter = new propertyArrayAdapter(this, 0, materialProperties);
ListView listView = (ListView) findViewById(R.id.lv_materialcart);
listView.setAdapter(adapter);
}
}
The codes work for receiving the values, but when I go back to the materialView (or choose another product) the ArrayList doesn't append the values.
What I'm trying to achieve here is to add the values from the MaterialView (even if the user adds many prodducts) to MaterialCart's ArrayList.
You can let your Application contain the data:
public class MyApp extends Application {
private static List<String> data = new ArrayList<>();
public static void addItem(String item) {
data.add(item);
}
public static List<String> getData() {
return data;
}
}
And when button is clicked:
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
MyApp.addItem(your item);
Intent i=new Intent(MaterialView.this, MaterialCart.class);
startActivity(i);
}
} );
And in MaterialCart.class:
List<String> data = MyApp.getData();
But remember:data will be clear when app is closed.And if you want save it locally,you need to use SharedPreferences
I have created the class textViewTable In this class i am saving data related to TextViews That I want to Pass to Next Activity.
public class TextViewTable implements Serializable {
private String FONT;
private String TEXT;
private float TEXT_SIZE;
private ColorStateList TEXT_COLOR;
private float MARGIN_TOP;
private float MARGIN_BOTTOM;
private float MARGIN_LEFT;
private float MARGIN_RIGHT;
private Boolean BoldFlag;
private Boolean ItalicFlag;
private Boolean NormalFlag;
public TextViewTable(){
}
public TextViewTable(String FONT, String TEXT, float TEXT_SIZE, ColorStateList TEXT_COLOR, float MARGIN_TOP, float MARGIN_BOTTOM, float MARGIN_LEFT, float MARGIN_RIGHT, Boolean boldFlag, Boolean italicFlag, Boolean normalFlag) {
this.FONT = FONT;
this.TEXT = TEXT;
this.TEXT_SIZE = TEXT_SIZE;
this.TEXT_COLOR = TEXT_COLOR;
this.MARGIN_TOP = MARGIN_TOP;
this.MARGIN_BOTTOM = MARGIN_BOTTOM;
this.MARGIN_LEFT = MARGIN_LEFT;
this.MARGIN_RIGHT = MARGIN_RIGHT;
BoldFlag = boldFlag;
ItalicFlag = italicFlag;
NormalFlag = normalFlag;
}
}
From my activit i want to send ArrayList of Objects of TextViewTable class.
I have use the below function to send the ArrayList. But every time I am getting null pointer exception. Please Help to solve this.
public void onClick(View view)
{
Intent intent = new Intent(getApplicationContext(), displayImage.class);
Bundle bundleObject = new Bundle();
bundleObject.putSerializable("key", textViewsData);
intent.putExtras(bundleObject);
try {
startActivity(intent);
}catch (Exception e){
System.out.println(e);
}
}
};
Currently using Bundle.putSerializable for sending TextViewTable class object ArrayList to next Activity but not implementing Serializable interface in TextViewTable class:
public class TextViewTable implement Serializable{
....
}
you can follow ρяσѕρєя K's answer OR also you can do like below code:
public class GeneralClass{
public static ArrayList<TextViewTable> data = new ArrayList<TextViewTable>();
}
and then you can store your data in above arraylist on first activity like below:
Collections.copy(GeneralClass.data,textViewsData);
and now you can use GeneralClass.data arraylist in your second activity;
Sending the POJO from one activity to another acitivity:
Bundle bundle = new Bundle();
ArrayList<StatusData> passData = new ArrayList<StatusData>();
bundle.putSerializable("key", passData);
intent.putExtras(bundle);
startActivity(intent);
//then the transaction part
Getting the bundle`:
Bundle bundle = new Bundle();
bundle = getIntent().getExtras();
ArrayList<StatusData> dataReceived = (ArrayList<StatusData>)bundle.getSerializable("key"));
and then do whatever you like.Hope this helps.Cheers.
You can also use Parcelable.
First Activity
public void shareCustomArrayListObject(ArrayList<CUSTOMOBJECT> arrayList) {
if (arrayList != null && arrayList.size() > 0) {
Intent intent = new Intent(getApplicationContext(), displayImage.class);
Bundle bundleObject = new Bundle();
bundle.putSerializable("KEY", arrayList);
intent.putExtras(bundleObject);
}
}
Second activity where you want to retrieve the arraylist
private ArrayList<CUSTOMOBJECT> arrayList;
Bundle bundle=YOURACTIVITY.getBundle();
if(bundle==null){
bundle=getArguments();
}
if(bundle.getSerializable("KEY")!=null){
arrayList=(ArrayList)bundle.getSerializable("KEY");
}
and also if you have made a bean class for the arraylist
you need to implement
public class CUSTOMOBJECT implements Serializable{
and you done :)
you should use Parcelable object to pass data between activities as below:
Passing data from activity A to activity B
Intent intent=new Intent(A.this,B.class);
intent.putParcelableArrayListExtra("key", array_list);
startActivity(intent);
Getting data in Activity B from activity A
Intent intent=getIntent();
array_list = intent.getParcelableArrayListExtra("key");
So simple.
I hope this will help you.
I'm programming an Android application and I got a little problem. I'm trying get a value from the Class A in the Class B but it doesn't return the correct value.
Here's my code to better understand (Sorry for my poor english)!
Class A
package com.androidhive.androidlistview;
//import
public class AndroidListViewActivity extends ListActivity {
int day;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
day = Integer.parseInt(product.replaceAll("[^\\d.]", ""));
System.out.println(day);
//prints 1 When I click on the first list item, 2 When I click on the second, ...
startActivity(i);
// sending data to new activity
i.putExtra("product", product);
}
});
}
public int getDay() {
return day;
}
}
Class B
package com.androidhive.androidlistview;
//import
#SuppressLint({ "NewApi", "HandlerLeak" })
public class SingleListItem extends Activity {
AndroidListViewActivity alva = new AndroidListViewActivity();
int day;
String url;
String code;
//others variables
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Graphic
new NetworkOperation().execute();
}
class NetworkOperation extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
Document doc;
try {
day = alva.getDay();
System.out.println(day);
//prints 0
url = "http://www.planetehockey.com/calendrier.php?saison=45&div=9&club=&journee=" + day + "&jour=&mois=&page=0";
doc = Jsoup.connect(url).get();
//Récupère le texte d'une balise ayant bg_tableau pour class
Elements getId = doc.getElementsByClass("bg_tableau");
code = getId.text();
code = code + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
handler.sendEmptyMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
//other code
}
};
}
Thank's a lot for all your answers it helped me a lot:
How I solved the problem:
Class A
i.putExtra("product", product);
startActivity(i);
and:
Class B
int day = Integer.parseInt(i.getStringExtra("product").replaceAll("[^\\d.]", ""));
In your Class A, you're trying to bundle components AFTER the activity has been called.
put the call function like this..
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
day = Integer.parseInt(product.replaceAll("[^\\d.]", ""));
System.out.println(day);
i.putExtra("product", product);
startActivity(i);
The passes the parameter in a bundle to the called activity.
HTH!
There are two simple solutions for your problem,
1. Pass day values in intent to SingleListItem
Or
2. Make day as a Static member and use it with class Name like,
public static int day; and access it `AndroidListViewActivity.day`
and remove public int getDay() method from AndroidListViewActivity as in both activity it refers a different object of AndroidListViewActivity .
Try doing i.putExtra("product", product); before startActivity(i);
In your Activity A you have written the getter method but not setter method to set the value of day in your code. Just write the setter method also and set the value of day.
public void setDay(int p_day)
{
day=p_day;
}
Make the variable day as static. After setting the day value try to get it in activity B.
I hope this will help you.
I'm a novice programmer and I'm trying to learn Android coding using Eclipse.
This is my first time using StackOverflow.
Just for tutorial purposes, I want to make a simple Animal Encyclopedia.
So in my Home class, there are some buttons: "Dog", "Cat", "Bird", etc. When I click the button, it will bring me to the same layout but of course with different content.
So I created a class named AnimalData that holds the
ArrayList<Integer> to store R.drawable.xxx and ArrayList<String>
to store the text that I will put below the picture (like "Bulldog"
or "Husky")
Then I created a class named ChangeContent to set all those drawable
and text to the XML
But whenever I click the button, it results in Stopped Unexpectedly Error
Below are the shortened Home class, The "crash-maker" isn't here. I have checked the whole code line per line using Thread.sleep(2000), so if my app crashes before 2 second, the error is before the sleep() code and vice versa.
public class Home extends Activity implements OnClickListener{
Button dog, cat, bird;
AnimalData ad;
ChangeContent cc;
private ArrayList<Integer> drawable;
private ArrayList<String> title;
public Home(){
ad = new AnimalData();
cc = new ChangeContent(ad);
drawable = new ArrayList<Integer>();
title = new ArrayList<String>()
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
//set the findViewById for all the buttons
//set onClickListener() to all the buttons
}
public void onClick(View v) {
switch (v.getId()){
case R.id.bDog:
drawable.add(R.drawable.xxx);
drawable.add(R.drawable.yyy);
title.add("Bulldog");
title.add("Husky");
break;
case R.id.Cat:
//same
break;
case R.id.bBird:
//same
break;
}
ad.setDrawable(drawable);
ad.setTitle(title);
Intent i = new Intent("animal.ChangeContent"); //from Manifest
startActivity(i);
}
}
The AnimalData is just a typical getter setter, so I will just skip the code for that
The error is right after ChangeContent started because even when I put the sleep() on the first line of constructor, it doesn't have any effect.
public class ChangeContent extends Activity {
TextView title1, title2;
ImageView pic1, pic2;
private ArrayList<Integer> drawable;
private ArrayList<String> title;
public ChangeContent(AnimalData data){
drawable = new ArrayList<Integer>();
title = new ArrayList<String>();
drawable = data.getDrawable();
title = data.getTitle();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animal_info);
//findViewById for the TextView and ImageView
//setText() for TextView and setImageResource() for ImageView
}
}
Sorry for the long question, I tried to make it as short as possible
Can you guys help me figure the error out?
Thanks before
You are trying to get arraylist from intent, whereas you are not putting putStringArrayList and putIntegerArrayList methods.
putIntegerArrayListExtra(String name, ArrayList<Integer> value)
putStringArrayListExtra(String name, ArrayList<String> value)
so Change calling activity to following:
Intent i = new Intent(Home.this, ChangeContent.class); //from Manifest
i.putIntegerArrayListExtra("drawables", drawable);
i.putStringArrayListExtra("titles", titles);
startActivity(i);
and get data from intent in onCreate method by following methods:
getIntegerArrayListExtra, and getStringArrayListExtra
you also can do following by making contentChanged method to static, by this you wont need to do much changes in your application code, just do following:
public class ChangeContent extends Activity {
TextView title1, title2;
ImageView pic1, pic2;
private static ArrayList<Integer> drawable;
private static ArrayList<String> title;
public static ChangeContent(AnimalData data){
drawable = new ArrayList<Integer>();
title = new ArrayList<String>();
drawable = data.getDrawable();
title = data.getTitle();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animal_info);
//findViewById for the TextView and ImageView
//setText() for TextView and setImageResource() for ImageView
}
}
See the answer by RajaReddy P here:
https://stackoverflow.com/a/9937854
In the send class use:
Intent intent = new Intent(PhotoActivity.this,PhotoActivity1.class );
intent.putIntegerArrayListExtra("VALUES", image);
startActivity(cameraIntent);
.. and in the receiver class use:
Intent i = getIntent();
ArrayList<Integer> img = i.getIntegerArrayListExtra("VALUES");
Your approach is wrong -
public Home(){
ad = new AnimalData();
cc = new ChangeContent(ad);
drawable = new ArrayList<Integer>();
title = new ArrayList<String>()
}
ChangeContent is a Activity class so, you don't pass parameter like this.
Passsing class should be serializable and use it -
startActivity(new Intent(this, ChangeContent.class)
.putExtra("key", ad);
And in your ChangeContent class extract the class from Intent
So, change your code design and go ahead.
Best of luck.