Unable to Pass an ArrayList of JSONObjects to new Activity - java

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)

Related

How to add a new varible (from previous activity) to a list to display on listview in android studio?

public class Main2Activity extends AppCompatActivity {
ListView simpleList;
String[] thoughtList = {" "};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
String newThought = intent.getStringExtra(MainActivity.EXTRA_TEXT);
thoughtList.add(newThought); //error comes herer hich wont allow add
simpleList = (ListView)findViewById(R.id.simpleListView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
simpleList.setAdapter(arrayAdapter);
}
}
that is my code on second page it brings over varible (saved as newThought) from the previous activity which i then want to add to thoughtList to display in ListView but won't let me add the new varible to the list. does my code need tweaking or should i start again to achieve varible brougth over from previous activity to add into list view on activity 2
Have you tried using an ArrayList instead of an string array?
String array has a fixed size when array list does not.
That may be your problem.

Recover an ArrayList in others activity

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!!

How to Save to an Array and display array in listview

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");

Pass Json Object from ViewHolder to Fragment

I have a RecyclerView and a Fragment. I want to pass a JSONObject from RecyclerView to Fragment. So, I created an Interface and implemented it on Fragment and on RecyclerView. I initialized the variable and access the method in the fragment passing the JSONObject to it, however I am getting a NPE when trying to access the method:
public class ProductResultsListFragment extends Fragment implements ProductResultAdapterInterface{
//code here
#Override
public void showResultsInMap(JSONObject mapObject)
{
openMapFragment(mapObject);
}
In my RV class I have the following:
public class ProductSearchAdapter extends RecyclerView.Adapter<ProductSearchAdapter.ViewHolder> {
public ProductResultAdapterInterface mProductResultsListener;
.....
if (mapObjects.length()>0)
{
mProductResultsListener.showResultsInMap(mapObjects);
}
The if statement is inside my viewHolder in my RecyclerView class but the instance is made public.
I have tried casting my mProductResultsListener but dont know what class to cast it into.
public ProductResultAdapterInterface mProductResultsListener=((ProductResultAdapterInterface ) ?????);
Just a quick comment: the mapObject (JsonObject) is created on a onClick method inside a button in ViewHolder, I cannot pass bundle on OnCreate method.
this.btnMarkItemMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
switch (v.getId())
{
case (R.id.markProductinMap):
String mapObj=null;
if (mapObjects !=null)
{
String positionDescription=String.valueOf(position);
String productLatLngValue=txtProductPrice.getText().toString()+";"+ txtItemLanLong.getText().toString();
//tring mapPosition=
mapObj=mapObjects.optString(String.valueOf(position));
if (mapObj!="") //Button not click remove from map
{
btnMarkItemMap.setColorFilter(Color.rgb(0, 0, 0));
btnMarkItemMap.setTag(Color.rgb(0, 0, 0));
mapObjects.remove(positionDescription);
}
else //Button Click add to Map
//
{
btnMarkItemMap.setColorFilter(Color.rgb(255, 51, 102));
btnMarkItemMap.setTag(position);
try {mapObjects.put(positionDescription, productLatLngValue);}catch (JSONException ex){}
if (mapObjects.length()>0)
{
mProductResultsListener.showResultsInMap(mapObjects);
}
}
}else{
mapObjects=new JSONObject();
}
break;
}
}
});
where have you assigned the variable mProductResultsListener?
you need to assign this to the object of the fragment by passing it into the adapter. Otherwise its value is null and you will get a NullPointeException if you call a function on a null object.
If you have, then please update the question with that code.
You can pass the data using bundles like this
SomeFragment someFragment = new SomeFragment();
Bundle bundle = new Bundle();
bundle.putString("value1", "2");
bundle.putString("value2", "23");
bundle.putString("value3", "276");
bundle.putString("value4", "27");
bundle.putBoolean("flag", true);
someFragment.setArguments(bundle);
And in SomeFragment
Bundle bundle = getArguments();
strValue1 = bundle.getString("value1");
strValue2 = bundle.getString("value2");
and so on for getting all the passed data from bundle
ProductResultsListFragment yourFragment = new ProductResultsListFragment();
Bundle bundle = new Bundle();
bundle.putString("yourJsonObject", yourJsonObject.toString);
yourFragment.setArguments(bundle);
public class ProductResultsListFragment...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle savedInfo = this.getArguments();
String savedJsonString = savedInfo.getString("yourJsonObject");
JSONObject myJsonObject = new JSONObject(savedJsonString);
//....
On my Fragment adapter init, I added:
ProductResultAdapterInterface mProInterface=(ProductResultAdapterInterface) this;
mAdapter = new ProductSearchAdapter(R.layout.product_results_cardlist,getActivity(),productListFeed,mProInterface);
on my adapter constructor I changed the signature to accept the Interface as a parameter passed from the Fragment
public ProductSearchAdapter (int rowLayout, Context context,List<Product> feedList,ProductResultAdapterInterface mProductResultsListener) {
this.feedItemLists=feedList;
this.rowLayout = rowLayout;
this.mContext = context;
this.mProductResultsListener=mProductResultsListener;
}
Then I was able to access the method and not getting NPE. thanks all

Unable to start activity ComponentInfo.....java.lang.IllegalStateException: Already attached

I m getting that error ,as you can see i m adding the data that i grabbed from the first activity and storing it into the my array in the second activity .
Then i use the array to populate the list view .So the problem is whenever i click to the save button on the first view
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
super.onCreate(savedInstanceState);
// setContentView(Your_Layout);
//Bundle extras = null;
//if(getIntent().getExtras() != null){
// extras = getIntent().getExtras();
//}
Intent intent = getIntent();
// ListView lv = (ListView) findViewById(R.id.View);
String data = intent.getStringExtra("data");
String first = intent.getStringExtra("stringOne");
String second = intent.getStringExtra("stringTwo");
String Third = intent.getStringExtra("stringThree");
String Fourth = intent.getStringExtra("stringFour");
String Fifth = intent.getStringExtra("stringFive");
String Sixth = intent.getStringExtra("stringSix");
// Find the ListView resource.
ListView lv = (ListView) findViewById( R.id.View );
// Create and populate a List of planet names.
String[] dataUser = new String[] { first,second,Third,Fourth,Fifth,Sixth};
ArrayList<String> dataList = new ArrayList<String>();
dataList.addAll(Arrays.asList(dataUser));
// Create ArrayAdapter using the planet list.
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
// Set the ArrayAdapter as the ListView's adapter.
lv.setAdapter(listAdapter);
}
}
You have 2 super.onCreate(savedInstanceState); in your code, remove one of them.
So I did remove the extrat super.onCreate(savedInstanceState); that i had but it looks like one of my edit text is passing a nul value .So i went trough every line but as you can see all the edixtext are passing a diffrent of null
http://pastebin.com/mys3R8QQ

Categories