I have an Input with a button to add items in a listview but I want to recover all item in other activity but there are 4 activitys where I want to recover items. I hope somebody can help me. There is the code of my MainActivity where is the input to add in the listview
public class MainActivity extends AppCompatActivity {
private Button bt2;
private EditText et;
private Button bt;
private ListView lv;
public ArrayList<String> arrayList;
private ArrayAdapter<String> customeAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText);
bt = (Button) findViewById(R.id.button);
lv = (ListView) findViewById(R.id.listview);
bt2 = (Button) findViewById(R.id.button2);
arrayList = new ArrayList<String>();
customeAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putStringArrayListExtra("arraylist",arrayList);
startActivity(intent);
}
});
lv.setAdapter(customeAdapter);
onBtnClick();
}
public void onBtnClick() {
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result = et.getText().toString();
arrayList.add(result);
customeAdapter.notifyDataSetChanged();
}
});
}
}
public class Main2Activity extends AppCompatActivity {
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tv = (TextView) findViewById(R.id.tvMainTwo);
Intent intent = getIntent();
ArrayList<String> arrayList = intent.getStringArrayListExtra("arrayList");
Random theRandom = new Random();
int playersNumb = theRandom.nextInt(arrayList.size());
tv.setText(tv.getText() + " " + arrayList.get(playersNumb));
}
}
In one activity you have an ArrayList which backs your listview. You update the ArrayList by some input through the user interface.
Then you want to use the data in that ArrayList in other activities.
The alternatives you have are:
1) Send the data in an intent.
The data must be Serializable or Parcelable
2) Pesist the data and have the other activities read the persisted data.
In some way you will also need to serialize the data in order to persist it.
The alternatives for persisting data are SharedPreferences, a flat file for convenience in the app's private storage folder, or in SQLite.
If you have complex objects in the ArrayList as data, one way you can make the ArrayList a String that can be serialized, is to encode it to Json using the Gson library. Depending on the way you choose to go you can use Gson() with the entire ArrayList or with each element.
EDIT I
For ArrayList<String> in particular you can sen the ArrayList in the intent itself.
Intent intent = new Intent(this, AnotherActivity.class);
intent.putStringArrayListExtra("arraylist",arraylist);
startActivity(intent);
In AnotherActivity class
private ArrayList<String> arraylist;
and in onCrate():
// You will have to add the checking for null values.
Intent intent = getIntent();
arraylist = intent.getStringArrayListExtra("arraylist");
you may try using shared viewmodel to share data between activities. or you can save the data's into SQlite database.
There is built in android feature for your problem. It is called Intents and putExtra. Sample code below
val parametersGoHere: ArrayList<SomethingParcalableOrSerializable> = arrayListOf()
val intent = Intent(context, AnotherActivity.javaClass).putExtra("key", parametersGoHere)
context.startActivity(intent)
In next activity you can recover data by calling
(ArrayList<OfYourType>)(getIntent().getExtras().getSerializable("key"))
For open/display second screen, use Intnet and pass the arraylist with extras.
Intent intent = new Intent(CurretnActivity.this, SecondActivity.class);
intent.putExtra("arrayList", arrayList);
startActivity(intent);
get the arraylist in SecondActivity using below line.
ArrayList<String> arrayList = new ArrayList<>();
if (getIntent() != null) {
arrayList = (ArrayList<String>) getIntent().getSerializableExtra("arrayList");
}
you should create a singleton data class and get list from every activity on create and and update list from each activity
public class DataHolder {
private String data;
public String getData() {return data;}
public void setData(String data) {this.data = data;}
private static final DataHolder holder = new DataHolder();
public static DataHolder getInstance() {return holder;}
}
for getting data:
String data = DataHolder.getInstance().getData();
Intent.class To start others activities and send values.
Send values
Map<String, String> hashMap = new HashMap<>(); // or List, or Set...
Intent intent = new Intent(SourceActivity.this, DestinationActivity.class);
intent.putExtra("hashMap", hashMap); // putArray(), putChars()...
startActivity(intent);
Receive values
Intent intent = getIntent();
HashMap<String, String> hashMap = (HashMap<String, String>)intent.getSerializableExtra("hashMap");
¡¡CODE NOT TESTED BUT IDEA IS CORRECT!!
Related
I have 2 Activities. Activity A contains recyclerview, and Activity B is going to pass the Arraylist data to recyclerview in Acrivity A.
my Adapter is like this.
public MainAdapter(MainActivity context,ArrayList<MainData> list) {
this.context = context;
this.list = list;
}
and MetaData.
public MainData(String tv_name, String tv_content) {
this.tv_name = tv_name;
this.tv_content = tv_content;
}
Activity A (that receives arraylist data):
recyclerView = (RecyclerView) findViewById(R.id.rv);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
list = new ArrayList<>();
list = (ArrayList<MainData>)getIntent().getSerializableExtra("key");
adapter = new MainAdapter(this,list);
recyclerView.setAdapter(adapter);
AAnd Activity B that pass Arraylist :
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(upload.this, MainActivity.class);
ArrayList<MainData> list = new ArrayList<MainData>();
EditText edit = (EditText) findViewById(R.id.edittext_name);
String tv_name = edit.getText().toString();
EditText edit_main = (EditText) findViewById(R.id.edittext_main);
String tv_content = edit_main.getText().toString();
list.add(new MainData(tv_name,tv_content));
intent.putExtra("key", list);
startActivity(intent);
}
});
And it throws Runtime Exception.
The context you provided is not complete, please review the Android guide. If you need to transfer data between activities, please check this article
enter link description here
You should use Intent extras to pass the the array list from ActivityB to ActivityA and in the ActivityA you have to pass the list to the adapter so it will set the data on the recyclerView.
You shouldn't directly pass the data from ActivityB to the adapter of AdapterA
This might be helpful: https://developer.android.com/reference/android/content/Intent
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 5 years ago.
I have two Java classes. Where I want to retrieve TextView data from DrinkDetail.java into Cart.java in order to save it into Firebase database. The TextView is deliveryOption and wanted to save in Cart.java from Requests table.
How can I do it? Below are my Java codes.
DrinkDetail.java
public class DrinkDetail extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink_detail);
private void showAlertDialogChooseOptions() {
alertDialog = new AlertDialog.Builder(DrinkDetail.this);
alertDialog.setTitle("Drop by our kiosk or rider deliver?");
LayoutInflater inflater = this.getLayoutInflater();
View takeaway_deliver = inflater.inflate(R.layout.takeaway_delivery, null);
btnTakeAway = (FButton)takeaway_deliver.findViewById(R.id.btnTakeAway);
btnDelivery = (FButton)takeaway_deliver.findViewById(R.id.btnDelivery);
deliveryOption = (TextView)takeaway_deliver.findViewById(R.id.deliveryOptionChosen);
alertDialog.setView(takeaway_deliver);
alertDialog.create();
btnTakeAway.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deliveryOption.setText("Take Away");
alertDialogTakeAway.show();
}
});
}
Cart.java:
public class Cart extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
private void showAlertDialog() {
alertDialog2 = new AlertDialog.Builder(Cart.this);
alertDialog2.setTitle("Cash on Delivery:");
alertDialog2.setMessage("Choose amount of money will be given to the rider upon order arriving: ");
LayoutInflater inflater2 = this.getLayoutInflater();
View cash_on_delivery = inflater2.inflate(R.layout.cash_on_delivery, null);
btnOrderNow = (FButton)cash_on_delivery.findViewById(R.id.btnOrderNow);
btnOrderNow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Submit to Firebase
Request request = new Request(
Common.currentUser.getPhone(),
Common.currentUser.getName(),
editAddress.getText().toString(),
txtTotalPrice.getText().toString(),
"0", //status
editComment.getText().toString(),
paymentMethod.getText().toString(),
moneySelected.getText().toString(),
//WANTED TO SAVE DELIVERY OPTION "TAKE AWAY" HERE,
cart
);
requests.child(String.valueOf(System.currentTimeMillis()))
.setValue(request);
//Order placed
alertDialogOrderPlaced.show();
alertDialog2.setCancelable(true);
}
});
alertDialog2.setView(cash_on_delivery);
alertDialog2.setIcon(R.drawable.icons8_cash_in_hand_filled_50);
}
Make a public method in the class you want to retrieve the data from. Like getData(), something similar to this:
public Data getData(){
return this.data;
}
If your using Intent to navigate from DrinkDetail to Cart then you can pass that string in Intent itself.
like this
Intent intent=new Intent(DrinkDetail.this, Cart.class);
intent.putExtra("Key","String value you want to pass");
startActivity(intent);
and can retrieve that string in Cart.java place below code in onCreate() method
String value;
if(getIntent()!=null)
value=getIntent().getStringExtra("Key");
Data can be stored using SharedPreferences.
In your DrinkDetail.java save the data.
SharedPreferences prefs = this.getSharedPreferences("File", MODE_PRIVATE);
prefs.edit().putString("deliveryOption", deliveryOption.getText()).apply();
In your Cart.java you can retrieve it back.
SharedPreferences prefs = this.getSharedPreferences("File", MODE_PRIVATE);
String deliveryOption = prefs.getString("deliveryOption", "default");
To send the data from one activity to another activity
DrinkDetail.java is first activity from where you want to send data
to another activity
DrinkDetail.java
TextView aText = (TextView )findViewById(R.id.textview);
String text = aText .getText().toString();
Intent myIntent = new Intent(view.getContext(),Cart.java);
myIntent.putExtra("mytext",text);
startActivity(myIntent);
Cart.java is second activity which receive the Intent data whatever
you pass from DrinkDetail.java
Cart.java
public class Cart extends Activity {
TextView mTextview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Cart);
aTextview = (TextView)findViewById(R.id.textView);
aTextview.setText(getIntent().getStringExtra("mytext"));
}
So I am making a simple app. It's just basically making a list of win with a custom list view at the end.
It starts off on the main screen where there are two buttons, one is an "Add" button which takes you to the Add activity. If you push this it'll take you to a page where you type in the name,price, description of the wine and then hit a submit button to the list. The other button on the main screen is a "Go to List" button which just takes you directly to the list activity.
If I go through the Add button, add a wine, and then go to the list, it works fine. I can see the list. It even works if I don't add anything to the list. I can see the empty list activity.
When I push the "Go to List" button on the main screen though, it crashes and says "The application has stopped".
I don't get why I can go through the Add button to get to the list fine, but this button doesn't work at all.
Could I get some help?
Here are the three relevant activities, the AddActivity, the ListActivity, and the MainActivity.
AddActivity:
public class AddActivity extends AppCompatActivity {
EditText editWineName;
EditText editWinePrice;
EditText editWineDescription;
Button btnSubmit;
Button btnGoToList;
String stringWineName;
String stringWinePrice;
String stringWineDescription;
ArrayList<String> listWineName = new ArrayList<>();
ArrayList<String> listPrice = new ArrayList<>();
ArrayList<String> listWineDescription = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
setVariables();
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setVariables();
listWineName.add(stringWineName);
listPrice.add(stringWinePrice);
listWineDescription.add(stringWineDescription);
Toast.makeText(AddActivity.this, stringWineName + " was added to the list.", Toast.LENGTH_SHORT).show();
clearEditText();
}
});
btnGoToList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intentGoToList = new Intent(AddActivity.this,ListActivity.class);
intentGoToList.putStringArrayListExtra("WINENAME", listWineName);
intentGoToList.putStringArrayListExtra("WINEPRICE", listPrice);
intentGoToList.putStringArrayListExtra("WINEDESCRIPTION", listWineDescription);
startActivity(intentGoToList);
}
});
}
private void setVariables(){
editWineName = (EditText) findViewById(R.id.editName);
editWinePrice = (EditText) findViewById(R.id.editPrice);
editWineDescription = (EditText) findViewById(R.id.editDescription);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnGoToList = (Button) findViewById(R.id.btnGoToList);
stringWineName = editWineName.getText().toString();
stringWinePrice = "$" + editWinePrice.getText().toString();
stringWineDescription = editWineDescription.getText().toString();
}
private void clearEditText() {
editWineName.getText().clear();
editWinePrice.getText().clear();
editWineDescription.getText().clear();
}
}
ListActivity:
public class ListActivity extends AppCompatActivity {
ListView wineList;
ArrayAdapter adapter;
Button btnBacktoMain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
setVariables();
ArrayList<String> listWineName = getIntent().getStringArrayListExtra("WINENAME");
ArrayList<String > listWinePrice = getIntent().getStringArrayListExtra("WINEPRICE");
ArrayList<String> listWineDescription = getIntent().getStringArrayListExtra("WINEDESCRIPTION");
adapter = new CustomAdapter(this, listWineName, listWinePrice, listWineDescription);
wineList.setAdapter(adapter);
btnBacktoMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intentBackToMain = new Intent(ListActivity.this,MainActivity.class);
startActivity(intentBackToMain);
}
});
}
private void setVariables (){
btnBacktoMain = (Button) findViewById(R.id.btnBackToMain);
wineList = (ListView) findViewById(R.id.listWine);
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
Button btnAdd;
Button btnList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVariables();
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //Goes to the add activity
Intent intentAdd = new Intent(MainActivity.this, AddActivity.class);
startActivity(intentAdd);
}
});
btnList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //Goes to the list activity
Intent intentList = new Intent(MainActivity.this, ListActivity.class);
startActivity(intentList);
}
});
}
private void setVariables(){
btnAdd = (Button) findViewById(R.id.btnAddWine);
btnList = (Button) findViewById(R.id.btnViewList);
}
}
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:344)
at android.widget.ListView.setAdapter(ListView.java:493)
at com.example.jeremy.mywine.ListActivity.onCreate(ListActivity.java:33)
Your crash indicates that the data in the adapter given to the ListView in ListActivity is null. Make it not null. Start at ListActivity.java at line 33 and go backwards to find where you are (or this case are not) initializing the data in the list adapter.
In you case, you are expecting data in your intent. OK, where is your intent set up? In your MainActivity click. Well, there you just launch the activity without passing any data in the intent extras, hence there is nothing to pull out from the intent in ListActivity, hence your crash.
So you need to initialize the data in MainActivity and set it as extras in the Intent you use to launch ListActivity.
Since the ListActivity is expecting this:
ArrayList<String> listWineName = getIntent().getStringArrayListExtra("WINENAME");
ArrayList<String > listWinePrice = getIntent().getStringArrayListExtra("WINEPRICE");
ArrayList<String> listWineDescription = getIntent().getStringArrayListExtra("WINEDESCRIPTION");
You would update your MainActivity to do something like this (where getDescriptions() is a fictitious method you would create to return a list of strings)
btnList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Goes to the list activity
Intent intentList = new Intent(MainActivity.this, ListActivity.class);
intentList.putExtra("WINENAME", new ArrayList<String>()); // Empty list
intentList.putExtra("WINEPRICE", Arrays.asList("Foo", "Bar")); // Explicit list named items
intentList.putExtra("WINEDESCRIPTION", getDescriptions()); // Get list from private method
startActivity(intentList);
}
});
Also check this post my be useful for learning how to read and understand a crash log.
And check the documentation on how to start activities.
Hope that helps!
I use this code to save the contents of a EditText (name) to an array, i'm wanting to then display this array in a list view on another activity. any idea? thanks
SingleItemView:
ArrayList<String> addArray = new ArrayList<String>();
Intent intent = new Intent(SingleItemView.this, mygardenMain.class);
Bundle bundle =new Bundle();
public void onClick(View v) {
String getInput = txt.getText().toString();
if (addArray.contains(getInput)){
Toast.makeText(SingleItemView.this,"Plant Already Added",Toast.LENGTH_SHORT).show();
}
else if (getInput == null || getInput.trim().equals("")){
Toast.makeText(SingleItemView.this,"No Plant Selected",Toast.LENGTH_SHORT).show();
}
else
{
addArray.add(getInput);
Toast.makeText(SingleItemView.this,"Plant Added",Toast.LENGTH_SHORT).show();
bundle.putStringArrayList("addArray",addArray);
intent.putExtras(bundle);
startActivity(intent);
mygardenMain code:
public class mygardenMain extends Activity {
private ListView list;
private ArrayList<String> addArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mygarden_list);
list = (ListView) findViewById(R.id.mygardenlist);
Bundle bundle = getIntent().getExtras();
ArrayList<String> addArray = bundle.getStringArrayList("addArray");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(mygardenMain.this, android.R.layout.simple_list_item_1, addArray);
list.setAdapter(adapter);
}
}
Use Parcelable to send and receive data between activities.
To send
intent.putParcelableArrayListExtra("key", ArrayList<T extends Parcelable> list);
startActivity(intent);
To receive,
getIntent().getParcelableArrayListExtra("key");
finally set listview adapter.
public class BasicViews5Activity extends ListActivity {
String[] presidents = {
“Dwight D. Eisenhower”,
“John F. Kennedy”,
“Lyndon B. Johnson”,
“Richard Nixon”,
“Gerald Ford”,
“Jimmy Carter”,
“Ronald Reagan”,
“George H. W. Bush”,
“Bill Clinton”,
“George W. Bush”,
“Barack Obama”
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//---no need to call this---
//setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, presidents));
}
public void onListItemClick(
ListView parent, View v, int position, long id)
{
Toast.makeText(this,
“You have selected “ + presidents[position],
Toast.LENGTH_SHORT).show();
}
}
hope this helps
the String{} presidents is the array
I think this is what you want:
from:
https://developer.android.com/training/basics/firstapp/starting-activity.html
Build an Intent
An Intent is an object that provides runtime binding between separate components (such as two activities). The Intent represents an app’s "intent to do something." You can use intents for a wide variety of tasks, but in this lesson, your intent starts another activity.
In MainActivity.java, add the code shown below to sendMessage():
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
This is how you pass String in android to the next activity.
This could be adapted to add an array or values in an array potentially as and object or as string through a for loop.
try this.
first convert ArrayList to array and then pass to next activity
String [] arrrayData = addArray.toArray(new String[addArray.size()]);
get like this
String[] array;
Intent intent = new Intent(MainActivity.this,MyDrawing.class);
Bundle bundle =new Bundle();
bundle.putStringArray("array",array);
intent.putExtras(bundle);
startActivity(intent);
100% working
please be specific with your question.Secondly ListView is outdated,my advise to you is to use Recycler view
private RecyclerAdapter ra;
private ArrayList<ModalClassName> yourarraylistname;
recyclerView = (RecyclerView) findViewById(R.id.recyclerdown);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
yourarraylistname =new ArrayList<ModalClassName>();
//make sure yourarraylistname has some value
ra = new DownloadAdapter(this,yourarraylistname);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(ra);
Please check my ListView Example project on github. Here is the link
https://github.com/SanjayKushwah0601/ListView-Example
You can pass the ArrayList via intent
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putStringArrayListExtra("list", addArray);
startActivity(intent);
And then you can fetch this ArrayList on another screen
// Now fetch the contents from intent
addArray = getIntent().getStringArrayListExtra("list");
ArrayAdapter<String> adapter = new ArrayAdapter<>(ListActivity.this, android.R.layout.simple_list_item_1, addArray);
list.setAdapter(adapter);
Use Below Code to do this. to send String array from one Activity to next Activity.
String[] stringArray = new String[10];
Intent intent = new Intent(MainActivity.this,MyDrawing.class);
Bundle bundle =new Bundle();
bundle.putStringArray("stringArray",stringArray);
intent.putExtras(bundle);
startActivity(intent);
And Retrive Array in Next Activity from Intent like below:
Bundle bundle = getIntent().getExtras();
String[] stringArray = bundle.getStringArray("stringArray");
You can pass Array List Directly to Intent
ArrayList<String> arraylist = new ArrayList<String>();
Intent intent = new Intent(MainActivity.this, MyDrawing.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("arraylist",arraylist);
intent.putExtras(bundle);
startActivity(intent);
And Retrieve like below:
Bundle bundle = getIntent().getExtras();
ArrayList<String> arraylist = bundle.getStringArrayList("arraylist");
I am having trouble passing an ArrayList<JSONObject> to a new activity.
In my Search activity I use
intent.putParcelableArrayListExtra("data", resultsArray);
But I get a Wrong Argument error.
I used this SO question as a reference.
Intent.putExtra List
public class SearchActivity extends AppCompatActivity {
List<JSONObject> resultsArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
//other stuff
resultsArray = new ArrayList<JSONObject>();
}
public void goToActivity(){
Intent intent = new Intent(SearchActivity.this, SearchResultsListActivity.class);
intent.putParcelableArrayListExtra("data", resultsArray);
startActivity(intent);
}
// ...
}
My SearchResultsListAcivity is just a list
public class SearchResultsListAcivity extends AppCompatActivity {
public ArrayList<JSONObject> searchResultsArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
// .. .
searchResultsArray = getStringArrayListExtra("data");
ArrayAdapter<JSONObject> adapter = new ArrayAdapter<JSONObject>(this, android.R.layout.simple_list_item_1, android.R.id.text1, searchResultsArray);
ListView lv = (ListView) findViewById(R.id.listViewSearchResults);
lv.setAdapter(adapter);
}
}
I also have toyed with the implmentation answer listed here How to pass ArrayList of Custom objects to new activity?:
Intent intent = new Intent(getApplicationContext(), displayImage.class);
Bundle bundleObject = new Bundle();
bundleObject.putSerializable("KEY", arrayList);
intent.putExtras(bundleObject);
But again I get wrong argument error.
I would just transform your JSON array into a String array and then pass that to your next activity using putStringArrayListExtra(). You can decode it back to JSON array in your SearchResultsListActivity activity.
i) Transform your JSON array (or list) into a String array
JSONArray arr = new JSONArray(yourJSONresponse);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).toString());}
ii) Pass it to your SearchResultsListActivity activity as extra
Intent intent = new Intent(SearchActivity.this, SearchResultsListActivity.class);
intent.putStringArrayListExtra("string_array", list);
startActivity(intent);
iii) Finally decode it in your next activity
Bundle stringArrayList = getIntent().getExtras();
ArrayList<String> list = stringArrayList.getStringArrayList("string_array");
JSONArray arr = new JSONArray(list);
I have not tried this code but at least it should give you an idea on how to solve your problem. You might have to make minor changes (the last line maybe replace it for a for loop if it doesn't work, etc)