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"));
}
Related
I have two activities. When an item in a RecyclerView is selected, it takes the user to the second activity and fills in the details with the related RecyclerView item.
In the second RecyclerView activity, there is a Spinner. Depending on the item selected in the spinner, different RecyclerViews become visible/invisible to the user on the second activity.
How do I make it work so that the information is sent from the first activity to command the spinner on what to do?This is how Second Activity looks
SecondActivity.java
public class SecondActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private TextView tv_title, tv_description;
private ImageView PartiesThumbnailImg,PartiesCoverImg;
private RecyclerView RvPartyMembers;
private PartyMembersAdapter partyMembersAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parties_detail);
Spinner spinner = findViewById(R.id.spnConstituencies);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.constituencies, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
//ini views
iniViews();
//Setting up members list
setupRvPartyMembers();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
void iniViews() {
RvPartyMembers = findViewById(R.id.rv_party_members);
String partiesTitle = getIntent().getExtras().getString("title");
String partiesDescription = getIntent().getExtras().getString("description");
int imageResourceId = getIntent().getExtras().getInt("imgURL");
int imagecover = getIntent().getExtras().getInt("imgCover");
PartiesThumbnailImg = findViewById(R.id.detail_members_img);
Glide.with(this).load(imageResourceId).into(PartiesThumbnailImg);
PartiesThumbnailImg.setImageResource(imageResourceId);
PartiesCoverImg = findViewById(R.id.detail_members_cover);
Glide.with(this).load(imagecover).into(PartiesCoverImg);
tv_title = findViewById(R.id.tvPartyTitle);
tv_title.setText(partiesTitle);
tv_description = findViewById(R.id.tvPartyDesc);
tv_description.setText(partiesDescription);
}
void setupRvPartyMembers(){
List<PartyMembers> mdata = new ArrayList<>();
mdata.add(new PartyMembers("name",R.drawable.members_brendangriffin_fg));
mdata.add(new PartyMembers("name",R.drawable.members_brendangriffin_fg));
mdata.add(new PartyMembers("name",R.drawable.members_brendangriffin_fg));
partyMembersAdapter = new PartyMembersAdapter(this,mdata);
RvPartyMembers.setAdapter(partyMembersAdapter);
RvPartyMembers.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
}
These are the important pieces of code of the FirstActivity.java
#Override
public void onPartiesItemClick(PartiesOireachtas partiesOireachtas, ImageView partiesImageView) {
Intent intent = new Intent(getContext(),PartiesDetailActivity.class);
intent.putExtra("title", partiesOireachtas.getTitle());
intent.putExtra("description",partiesOireachtas.getDescription());
intent.putExtra("imgURL", partiesOireachtas.getThumbnail());
intent.putExtra("imgCover",partiesOireachtas.getCoverPhoto());
and
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//RecyclerView Setup
//int data
lstPartiesOireachtas = new ArrayList<>();
lstPartiesOireachtas.add(new PartiesOireachtas("Fianna Fáil", "example1", R.drawable.fianna_fail_logo,R.drawable.fianna_fail_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Sinn Féin", "example2", R.drawable.sinn_fein_logo,R.drawable.sinn_fein_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Fine Gael", "example4", R.drawable.fine_gael_logo,R.drawable.fine_gael_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Green Party", "example9", R.drawable.green_party_logo,R.drawable.green_party_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Social Democrats", "example3", R.drawable.soc_dems_logo,R.drawable.soc_dems_cover));
lstPartiesOireachtas.add(new PartiesOireachtas("Independent", "example2", R.drawable.independent_party_logo,R.drawable.independent_party_cover));
As you probably noticed an activity doesn't have a default constructor, but uses an onCreate(Bundle savedInstanceState) method. This means you should pass your information using this Bundles, or use something like SharedPreferences / SQLite. Since SharedPreferences / SQLite is a bit overkill for this in my opinion, you can add the object upon creating an intent.
Intent intent = new Intent();
intent.putExtra("name", parcelableObject);
If you want to pass a custom object you have to implement the Parcelable interface, this is pretty straightforward since you can basically auto generate all code for this in Android studio (just hit alt-enter a few times). For more information you can check out the following link.
https://developer.android.com/reference/android/os/Parcelable
In the receiving activity you can do the following:
Bundle bundle = getIntent().getExtras();
Object object = bundle.getObject("name"); //Don't forget to cast!
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!!
I have problem with my android coding. I want to make an update process. But first of all, I'm trying to collect all the data from edit text, spinner and image. But I have problem with spinner and image, could not get the previous data. How to get the previous data using spinner and image? Ex.. Image1
shows the complete retrieve process when user click on Submit Button, then it will go to this View Activity interface. While in Image2
shows the Edit Activity interface where the user can update all the data from there when the user click on Edit Button. The issue now is, I can not collect the previous data using spinner and image for editing/updating purposes as shown in the Image 2. Really hope someone can help me.. Thanks in advance...
Coding as follows:
1) Coding from View Activity:-
EditAdsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent editAds = new Intent(ViewAdsActivity.this, EditAdsActivity.class);
startActivity(editAds);
String tn = ViewTuitionName.getText().toString();
String pn = ViewProviderName.getText().toString();
String pg = getIntent().getStringExtra("PG");
Intent i = new Intent(ViewAdsActivity.this, EditAdsActivity.class);
i.putExtra("TN", "" +tn); // Collected from EditText or any other source
i.putExtra("PN", "" +pn);
i.putExtra("PG", "" +pg);
startActivity(i);
}
});
2) Coding from Edit Activity (onCreate method):-
Intent i = getIntent();
String tn = i.getStringExtra("TN");
String pn = i.getStringExtra("PN");
String pg = getIntent().getStringExtra("PG");
EditTuitionName.setText(tn);
EditProviderName.setText(pn);
EditProviderGender.setSelection(pg);
Here is a solution:
Constant.java
public class Constant {
public static final String[] GENDER = {"Male", "Female", "Other"};
}
ViewAdsActivity.java
public class ViewAdsActivity extends AppCompatActivity {
private CircleImageView avatar;
private EditText name;
private Spinner gender;
private Button next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_ads);
avatar = findViewById(R.id.avatar);
name = findViewById(R.id.edit_text_name);
gender = findViewById(R.id.spinner_gender);
next = findViewById(R.id.button_next);
// Render avatar
String imageUrl = "https://vignette.wikia.nocookie.net/spiritedaway/images/6/69/Chihiro.jpg/revision/latest?cb=20170308090934";
avatar.setTag(imageUrl);
Picasso.get()
.load(imageUrl)
.into(avatar);
// Render spinner
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Constant.GENDER);
gender.setAdapter(adapter);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ViewAdsActivity.this, EditAdsActivity.class);
intent.putExtra("imageUrl", (String) avatar.getTag());
intent.putExtra("genderPosition", gender.getSelectedItemPosition());
intent.putExtra("name", name.getText().toString());
startActivity(intent);
}
});
}
}
EditAdsActivity.java
public class EditAdsActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_ads);
CircleImageView avatar = findViewById(R.id.avatar);
EditText nameEditText = findViewById(R.id.edit_text_name);
Spinner gender = findViewById(R.id.spinner_gender);
String imageUrl = getIntent().getStringExtra("imageUrl");
int genderPosition = getIntent().getIntExtra("genderPosition", 0);
String name = getIntent().getStringExtra("name");
// Render image view
Picasso.get()
.load(imageUrl)
.into(avatar);
// Render spinner
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Constant.GENDER);
gender.setAdapter(adapter);
gender.setSelection(genderPosition);
// Render edit text
nameEditText.setText(name);
}
}
For the spinner you can use
Spinner mySpinner = (Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();
And then place the text in the intent like the other objects.
An image is trickier because you don't want to serialize the bitmap for the intent since serialization is on the main thread and the app would probably stutter or hang a bit. Instead you could store the bitmap in a class that is accessible from both activities, or if the image is already stored on the device you can pass the URI and just reopen it in the next activity.
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 have simple page to start up the app that has a spinner,editText, and a button. When the user clicks the button I want the app take the selection of the spinner and text and set them to text views in the new class. I tried using getters but when I try this the app crashes.
First Class:
public class MainActivity extends AppCompatActivity {
String pullerName;
String storeName;
Spinner spinner;
EditText etPuller;
public String getStoreName(){
return storeName;
}
public String getPullerName(){
return pullerName;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.store_list, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Button create = (Button) findViewById(R.id.btnCreate);
etPuller = (EditText) findViewById(R.id.editText);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pullerName = etPuller.getText().toString();
storeName = spinner.getSelectedItem().toString();
Intent i = new Intent(MainActivity.this,MainActivity2.class);
startActivity(i);
}
});
}
}
Second Class:
public class MainActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_main);
MainActivity main = new MainActivity();
TextView user = (TextView) findViewById(R.id.tvUser);
TextView store = (TextView) findViewById(R.id.tvStore);
user.setText(main.getPullerName());
store.setText(main.getStoreName());
When this code runs it crashes as soon as i click the button to move to the next activity.
To pass data to a new Activity you need to use Intent.
This is what you need to do:
MainActivity.class:
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pullerName = etPuller.getText().toString();
storeName = spinner.getSelectedItem().toString();
Intent i = new Intent(MainActivity.this,MainActivity2.class);
i.putExtra("puller-name", pullerName);
i.putExtra("store-name", storeName);
startActivity(i);
}
});
In the MainActivity2.class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_main);
TextView user = (TextView) findViewById(R.id.tvUser);
TextView store = (TextView) findViewById(R.id.tvStore);
Intent intent = getIntent();
if(intent != null){ //I always check this to avoid Exceptions
String pullerName = intent.getStringExtra("puller-name");
String storeName = intent.getStringExtra("store-name");
if(pullerName != null) user.setText(pullerName);
if(storeName != null) store.setText(storeName);
}
}
You was creating a new instance of MainActivity in MainActivity2. So, when you called the getters of this mainActivity will return null, because these values were never setters. If you want to use your method, you need to pass the same instance of the activity to MainActivity2, but this is not recommended. The official method to pass data to another activity is via intent. To learn more about Intent learn the official Android documentation: https://developer.android.com/training/basics/firstapp/starting-activity.html
You have used wrong way to get values from MainActivity to MainActivity2. Simply you can pass values using the technique below.
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("pullerName", pullerName);
To use this value pullerName in MainActivity2 class, just use the technique below.
String value = getIntent().getExtras().getString("pullerName");`