how to pass data from activity to adapter? - java

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

Related

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 read context of two spinners and send both to next activity?

I have two spinners and I want to grab the values that the user chooses and send it to the next activity. My first activity is titled IO and I create the spinners and get the data from the selections in my onCreate.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_io);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Spinner locationSpinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(IO.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.busStops));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
locationSpinner.setAdapter(myAdapter);
location = locationSpinner.getSelectedItem().toString();
Spinner destinationSpinner = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> myAdapter2 = new ArrayAdapter<String>(IO.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.busStops));
myAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
destinationSpinner.setAdapter(myAdapter2);
destination = destinationSpinner.getSelectedItem().toString();
}
I tried sending the data in another method titled sendRoutes where I created an intent but it didn't work and I was wondering how to do this.
Assuming that you want to open your activity on a button click then,
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String destination = destinationSpinner.getSelectedItem().toString();
String location = locationSpinner.getSelectedItem().toString();
Intent intent = new Intent(CurrentActivity.this,NextActivity.class);
intent.putExtra("destination",destination);
intent.putExtra("location",location);
startActivity(intent);
}
});
You are passing destination and location values to NextActivity by intent.
in IO Activity definition Intent :
Intent intent = new Intent(IO.this,SecondActivity.class);
location = locationSpinner.getSelectedItem().toString();
destination = destinationSpinner.getSelectedItem().toString();
intent.putExtra(KEY_DEST,destination);
intent.putExtra(KEY_LOC,location);
startActivity(intent);
in SecondActivity get two parameters in onCreate :
String destination = getInetent().getExtras.getString(KEY_DEST);
String location = getInetent().getExtras.getString(KEY_LOC);

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

Passing Views to Listview\RecyclerView

What am trying to accomplish here is create a listview or recyclerview if you like, to set UI views on the screen instead of using a scrollview, this concept is pretty popular among iOS developers where they create a table view and pass it views in an NSArray. I have done that part so far, problem is the listeners don't work if they are set in the activity before putting them in an arraylist to be passed to the list/recycler, here's my code so far.
recyclerView = (RecyclerView) findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
views = new ArrayList<>();
d = new DatePicker(this);
views.add(d);
e = new TextInputEditText(this);
e.addTextChangedListener(this);
views.add(e);
ee = new TextInputEditText(this);
ee.addTextChangedListener(this);
// views.add(ee);
Button b = new Button(this);
b.setText("hi btn");
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "hi", Toast.LENGTH_SHORT).show();
}
});
views.add(b);
Adapter adapter = new Adapter(views, this);
recyclerView.setAdapter(adapter);

Adding items in ListView

I have problems with my list . I had an Activity I get some Data from.
The data must accessed in variables in my class :
Mylist.java class
public String Job,Ship,Location,Shift,Date;
public String workingHour;
Mylist(String job,String loc,String shp,String shft,String dat,String wh){
Job=job;
Location=loc;
Ship=shp;
Shift=shft;
Date=dat;
workingHour=wh;
}
and by pressing Save Button The list must add an item.My problem is when I add another items the list have only one item How to fix this ?
Adding Class :
AddOredit.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_oredit);
final ArrayList<Mylist>list =new ArrayList<>();
final ArrayList<String> Job=new ArrayList<>();
String selecteditem1, selecteditem2,getlocation,getship,getdate,gethours;
Spinner type=(Spinner)findViewById(R.id.s1);
Spinner shift=(Spinner)findViewById(R.id.s2);
EditText location=(EditText)findViewById(R.id.loc);
EditText ship=(EditText)findViewById(R.id.ship);
EditText date=(EditText)findViewById(R.id.date);
EditText workinghours=(EditText)findViewById(R.id.hours);
Button Save = (Button) findViewById(R.id.editbtn);
Button cancel = (Button) findViewById(R.id.cancelbtn);
selecteditem1 = type.getSelectedItem().toString(); //for first spinner
selecteditem2 = shift.getSelectedItem().toString();//for second spinner
getlocation=location.getText().toString();
getship=ship.getText().toString();
getdate=date.getText().toString();
gethours=workinghours.getText().toString();
list.add(new Mylist(selecteditem1,getlocation,getship,selecteditem2,getdate,gethours));
Log.e(TAG, String.valueOf(list.size()));
for(int i=0;i<list.size();i++){
Job.add("Job "+(i+1));
}
//When pressing save Button
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//list.add(new Mylist(selecteditem1, getlocation, getship, selecteditem2, getdate, gethours));
Intent intent = new Intent(AddOredit.this, MainActivity.class);
intent.putStringArrayListExtra("MyList", Job);
startActivity(intent);
}
});
}
MainActivity.java this class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv= (ListView) findViewById(R.id.listView);
Button ADD=(Button)findViewById(R.id.addbtn);
Button DELETE=(Button)findViewById(R.id.deletebtn);
Button PROFILE=(Button)findViewById(R.id.profilebtn);
Intent intent=getIntent();
ArrayList<String> Job ;
Job=intent.getStringArrayListExtra("MyList");
if(Job!=null){
ListAdapter adapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Job);
lv.setAdapter(adapter);
//when user click on add button
}
ADD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//go to AddOreditpage
Intent i = new Intent(MainActivity.this, AddOredit.class);
startActivity(i);
}
});
**Note :- ** Add Button is for Adding items in the list and Save Button is for saving data entered at AddOredit class.
**Note :- ** By clicking Add Button , getting to the AddOredit Activity .
By Clicking Save Button, getting back to the main activity with the item added
You are assigning a new List for list object on your second activity created. Try to assign the list with an existing object and add your new object.
EDIT:
Try to Declare this globally as,
private static ArrayList list =new ArrayList<>();
and with in onCreate() remove it. Let me know if it still do not work.

Categories