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");
Related
I have two intents.
Main Activity: Containing the Recycler View, showing some default items to make sure it works. An ArrayList is set to the Recycler View, which is the List containing those default items.
Second Activity: A button which will collect the data on the same page and put the data into an object, the object will be added into the Arraylist which set to the Recycler View of the Main Activity.
I made some Toast Message to confirm the object in the 2nd Activity was added to the ArrayList.
//My item
public item(int id, int money, String date, String category, String
description) {
this.id = id;
Money = money;
Date = date;
Category = category;
Description = description;
}
Then I created a class to control my ArrayList
//Building ArrayList
public Util(){
Log.d(TAG, "Util: Start");
if(IncomeItems==null){
IncomeItems = new ArrayList<>();
initIncomeItems();
}
}
private static void initIncomeItems() {
Log.d(TAG, "initIncomeItems: initI");
int Iid = 0
int Money= 0;
String Date = "";
String Category= "";
String Description = "";
Iid++;
IncomeItems.add(new item(Iid, 10000, "8-Jun-2019", "Salary",
"Salary"));
}
//adding item to ArrayList
public boolean addIncomeItem(item Item){
Log.d(TAG, "addIncomeItem: addI");
return IncomeItems.add(Item);
}
//getting ArrayList
public static ArrayList<item> getIncomeItems() {
Log.d(TAG, "getIncomeItems: getI");
return IncomeItems;
}
I set my ArrayList to the RecyclerView in the Main Activity
//Recycler View in Main Activity
RVAdapter IncomeAdapter = new RVAdapter(this);
Util util = new Util();
MainIncomeRV.setAdapter(IncomeAdapter);
MainIncomeRV.setLayoutManager(new GridLayoutManager(this, 1));
IncomeAdapter.notifyDataSetChanged();
IncomeAdapter.setItems(util.getIncomeItems());
In the 2nd Activity, I have a button to create a new item by getting data from the user.(I skipped some Widgets intitiation code here). At last I add the item to the ArrayList which set to the Recycler View in the Main Activity.
//Button in 2nd Activity
SubmitIncomeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Date = date_day.getSelectedItem().toString() +"-" +
date_month.getSelectedItem().toString() + "-" +
date_year.getSelectedItem().toString();
id++;
item IncomeItem = new item(id,
Integer.parseInt(Money.getText().toString()), Date,
IncomeCategories.getSelectedItem().toString(),
Description.getText().toString());
util=new Util();
util.addIncomeItem(IncomeItem);
Toast.makeText(IncomePage.this, IncomeItem.toString(),
Toast.LENGTH_SHORT).show();
Toast.makeText(IncomePage.this,
String.valueOf(util.getIncomeItems().size()), Toast.LENGTH_SHORT).show();
Log.d(TAG, "onClick: addI");
}
});
}
No error occurred, but the item(IncomeItem) created in the 2nd Activity cannot be added to the Main Activity.
I expected the item will show in the Recycler view when I return to the Main Activity. Is it the problem that I use the return button to go back to the Main Activity?
Following two points should work for you:
You should use same util object which is used in MainActivity
instead of creating new in submit button under 2nd Activity, So pass util object to
2nd activity.
Also pass adapter object to 2nd Activity, so that you can call NotifyDatasetChanged()
function after adding item.
This is how it should work. First create an arrayList in your 2ndActivity.
ArrayList<Item> str = new ArrayList<Item>();
In SubmitIncomeBtn,
SubmitIncomeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Date = date_day.getSelectedItem().toString() +"-" + date_month.getSelectedItem().toString() + "-" + date_year.getSelectedItem().toString();
id++;
item IncomeItem = new item(id,Integer.parseInt(Money.getText().toString()), Date, IncomeCategories.getSelectedItem().toString(),Description.getText().toString());
str.add(IncomeItem) // add IncomeItem to arrayList
}
});
In 2ndActivity, you need to have this code to pass arrayList to MainActivity.
#Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("mylist", str);
setResult(1, intent);
}
Finally in MainActivity, add this code to receive data from 2ndActivity
onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
ArrayList<Item> myList = (ArrayList<Item>) getIntent().getSerializableExtra("mylist");
}
}
}
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
}
I have created a RecyclerView which populates the users' contacts with a checkbox.
When a user clicks on a checkbox, I want to add that contact to an Object.
Now I have been able to do that, but I am facing issues with sending that object from the adapter to another activity:
#Override
public void onBindViewHolder(ViewHolder holder, final int position){
// final PlayerDetails thePlayer = playerData.get(position);
// ArrayList<PlayerDetails> thePlayer = playerData;
//holder.playerNameNumber.setText(thePlayer.name + " " + thePlayer.number);
holder.playerNameNumber.setText(playerData.get(position).name +playerData.get(position).number );
holder.pickedPlayer.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View thisView){
PlayerDetails contact = new PlayerDetails();
contact.number = playerData.get(position).name;
contact.name = playerData.get(position).number;
playerListGame.addPlayer(contact);
String name = playerData.get(position).name;
Toast.makeText(thisView.getContext(),name + " added",Toast.LENGTH_LONG).show();
}
});
}
When I debug the above, I can see playerListGame contains the data I am adding to it.
Now, I tried to do the following :
public PlayerList donePickingSendPlayers(){
return playerListGame;
}
at the bottom of my adapter.
But when I debug, it shows that it has a value of 0. (I did initialise it at the start.
How can I send playerListGame to another activity?
I have set up a floating button, which onClick does the following:
private void donePicking(){
ContactPickerRecyclerViewAdapter justToGetPlayerData = new ContactPickerRecyclerViewAdapter();
justToGetPlayerData.donePickingSendPlayers();
Intent backToComposeMessage = new Intent(this,ComposeMessage.class);
startActivity(backToComposeMessage);
}
But that doesn't seem to work as the playerListGame within "donePickingPlayers"
is empty.
use the same object of adapter you have set in recyclerview while fetching data using your method created inside adapter.
private void donePicking(){
ContactPickerRecyclerViewAdapter justToGetPlayerData = new
ContactPickerRecyclerViewAdapter();
justToGetPlayerData.donePickingSendPlayers();
Intent backToComposeMessage = new Intent(this,ComposeMessage.class);
startActivity(backToComposeMessage);
}
in this method you are creating another instance of the adapter class which always gives you empty data.
Write an interface with method donePicking(PlayerDetails contact) in your adapter and implement that method in your activity and override method in your activity there you'll get PlayerDetails object in overridden method and you can pass it to next activity.
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'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.