Sending data to Listview of another activity - java

After pressing the button I would like to go to the second activity, enter the data in the second activity and then return to the main activity, but having data in ListView. This is my code:
MainActivity:
public class MainActivity extends AppCompatActivity {
Button button;
ListView listView;
String name;
private static final int REQUEST_CODE = 1;
ArrayAdapter<String> adapter;
ArrayList<String> nameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button2);
listView = findViewById(R.id.CarList);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(i, REQUEST_CODE);
}
});
nameList = new ArrayList<String>();
nameList.addAll(Arrays.asList(name));
adapter = new ArrayAdapter<String>(this, R.layout.element, nameList);
listView.setAdapter(adapter);
}
protected void onActivityResult(int requestCode, int resultCode, Intent i){
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
name = i.getStringExtra("name");
}
}
}
And this is my SecondActivity:
public class SecondActivity extends AppCompatActivity {
EditText editText;
Button button2;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
editText = findViewById(R.id.editText);
button2 = findViewById(R.id.button);
}
public void finish() {
Intent i = new Intent();
name = editText.getText().toString();
i.putExtra("name", name);
setResult(RESULT_OK, i);
super.finish();
}
}
What could I change to make the application work? Because now I only get the message that: app has stopped, but I don't receive information about any error.

After pressing the button I would like to go to the second activity, enter the data in the second activity and then return to the main activity, but having data in ListView.
What could I change to make the application work? Because now I only get the message that: app has stopped, but I don't receive information about any error.
This is simply because you've incorrectly thinking that Activity.finish() is always called whenever you close the activity. But it never be called by the Android. Take a look for this Lifecyle picture from Activity-lifecycle concepts:
you can see that only onStop() then onDestroy() is called when activity is closed.
You need to call the finish() method manually to send your intent. Or, the better way, create a method that only build and set the intent for the result. Something like this:
private void prepareResult(String name) {
Intent i = new Intent();
i.putExtra("name", name);
setResult(RESULT_OK, i);
}
then call it whenever you want to close your activity:
String name = editText.getText().toString();
prepareResult(name);
finish();
Or you can override the onBackPressed() to also handing the back pressed, like the following:
#Override
public void onBackPressed() {
Intent i = new Intent();
name = editText.getText().toString();
i.putExtra("name", name);
setResult(RESULT_OK, i);
// The default implementation simply finishes the current activity
// see the documentation.
super.onBackPressed();
}

Related

App crashes if I try going to a specific 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!

how to save EditText's value after performing an other activity

i have my first activity with two EditText fields with hint's as first name and last name, when ever i go to my second activity and return to my first activity by a widget button the EditText fields in my first activity gets reset.
SIMPLY i want my EditText fields to remain same in my first activity as i re-visit my first activity from my second activity.
MY MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButton1Click(View v)
{
Intent intent = new Intent (this,MainActivity2.class);
startActivity(intent);
}
}
My MainActivity2.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
SOLUTION - i changed my second activity to this. just added reference to my Button and applied an onClickListener with onBackPressed(); code.
setContentView(R.layout.activity_main2);
Button button = (Button)findViewById(R.id.button3); //gave reference of button in second activity
button.setOnClickListener(new View.OnClickListener() { //and applied an onClickListener with code onBackpressed();
public void onClick(View v) {
onBackPressed();
// Code here executes on main thread after user presses button
}
});
}
Really Really thnx to #Narendra Sorathiya for his guidance.
Open secondActivity like below,
Intent i = new Intent(A.this,B.class);
startActivity(i);
finish();
to
Intent i = new Intent(A.this,B.class);
startActivityForResult(i,1);
do not open 1st Activity from 2nd Activity, just need to back press.
try this
declare all variavle at top of activity
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String FNAME = "fname";
public static final String LNAME = "lname";
SharedPreferences sharedpreferences;
write this code when you move to your next activity
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// store login data in sharedpreferences
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(FNAME, edittext.getText());
editor.putString(LNAME, edittext2.getText());
editor.commit(); //save data in sharedpreferences
write this code in your oncreate method after you bind your controls
and get data from sharedprefrence like this
String fname= prefs.getString(FNAME, "");
String fname= prefs.getString(LNAME, "");
than set it to your editext like this
editext.setText(fname);
editext2.setText(lname);
let me know in case of any query

App Crashes upon receiving data from intent

I have two activities that I would like to send data between. I would like to send two strings from the second activity to the first, where the strings will be manipulated and applied to the code. Here is the intent I have in the second activity to send the strings to the first activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
phoneNum = (EditText)findViewById(R.id.phoneNum);
msgCounter = (EditText)findViewById(R.id.msgCount);
apply = (Button)findViewById(R.id.butto);
save = (Button)findViewById(R.id.butt);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pass = new Intent();
pass.putExtra("value", phoneNum.getText().toString());
pass.putExtra("cost",msgCounter.getText().toString());
startActivity(pass);
}
});
And here is the intent I have in the first acitivity to receive the data:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_messages);
request_code = 1;
FloatingActionButton button = (FloatingActionButton) findViewById(R.id.but);
assert button != null;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TextMessages.this,Settings.class);
startActivityForResult(intent, request_code);
Intent a = new Intent(TextMessages.this,Settings.class);
startActivityForResult(a, recode);
}
});
Intent pass = getIntent();
String address = pass.getStringExtra("value");
String string2 = pass.getStringExtra("cost");
However, the app always crashes when I start it. So I can not use any of the data. Thanks in advance to any help I may receive.
In the first activity you should get your strings from onActivityResult. You shouldn't use startActivity in second activity.
Checkout this link for more information
https://developer.android.com/training/basics/intents/result.html
In your second activity you should use setResult method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
phoneNum = (EditText)findViewById(R.id.phoneNum);
msgCounter = (EditText)findViewById(R.id.msgCount);
apply = (Button)findViewById(R.id.butto);
save = (Button)findViewById(R.id.butt);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pass = new Intent();
pass.putExtra("value", phoneNum.getText().toString());
pass.putExtra("cost",msgCounter.getText().toString());
setResult(Activity.RESULT_OK,pass);
finish();
}
});
In your first activity you should get Intent data inside the onActivityResult method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == request_code) {
if(resultCode == Activity.RESULT_OK){
String value=data.getStringExtra("value");
String cost=data.getStringExtra("cost");
//handle value and cost.
}
}
}
I think it's because you missed out to put the target Activity class when you instantiate your intent. It should be like this:
Intent pass = new Intent(TargetActivity.class);
pass.putExtra("value", phoneNum.getText().toString());
pass.putExtra("cost",msgCounter.getText().toString());
startActivity(pass);
Hope it helps.
EDIT: But I agree with Abdullah. Since the first activity started the second activity, use onActivityResult to pass values to the first activity.
My guess is, the app starts into the second code block you posted. There is no value for String address = pass.getStringExtra("value"); or String string2 = pass.getStringExtra("cost"); when you start your app - only when the second activity sends these to the first activity. I would recommend finding a way to determine if its the second activity creating the first activity or creating a method to set these values in the first activity and call it in the second activity. Also, your second activity should be:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
phoneNum = (EditText)findViewById(R.id.phoneNum);
msgCounter = (EditText)findViewById(R.id.msgCount);
apply = (Button)findViewById(R.id.butto);
save = (Button)findViewById(R.id.butt);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pass = new Intent(SecondActivity.this, FirstActivity.class);
pass.putExtra("value", phoneNum.getText().toString());
pass.putExtra("cost",msgCounter.getText().toString());
startActivity(pass);
}
});

Android: onActivityResult() local data is missing

I have two activities(Activity1 and Activity2). Activity1 starts Activity2 for get some data. Whenever I back to Activity1 onCreate method is runing before the onActivityResult().And all data is gone. Why onCreate method is runing second time and data is missing?
You can check example code at below to see sample scenario. In this case a value of var1 should be 5 in onActivityResult method but its 0.
public class MainActivity1 extends ActionBarActivity
{
TextView textView1;
Button button1;
int var1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity1);
textView1 = (TextView) findViewById(R.id.textView1);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
var1 = 5;
Intent intent = new Intent(MainActivity1.this, MainActivity2.class);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
}
});
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
String message = data.getStringExtra("MESSAGE");
textView1.setText("value =" + var1);
}
}
}
public class MainActivity2 extends ActionBarActivity {
EditText editText1;
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
editText1=(EditText)findViewById(R.id.editText1);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String message=editText1.getText().toString();
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(2,intent);
finish();//finishing activity
}
});
}
}
You're doing it wrong. You're saving a String in the intent.
Then in the onActivityResult method you retrieve the String from the intent, and then set the TextView's text to "value =" var1, but you didn't load var1 from the Intent.
You should save the value var1 in the intent in MainActivity2, and then retrieve it from the intent in the onActivityResult method.
In Settings > Developer Options there is a setting called "Don't keep activities". Make sure this isn't enabled, or the activity would be destroyed as soon as you start the second activity, and you would be recreating the first activity upon returning to it.

sending text from editText to ListView (2 activities)

i am new to Andriod and programming. i am trying to make a to do list app, which will contain a listView, Button(add) in the main layout. when i click add i want it to go to another activity which will contain a editText and a add button. when i click the add button i want to update the list in my main activity. Now i was able to get the information from the second activity but when i try to add it in my list it over writes it.
How can i update my list as soon as my main activity appears again.
Here's what i have so far :
MainActivity class :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
add = (Button) findViewById(R.id.bAdd);
list = (ListView) findViewById(R.id.lvList);
addItems(); // i think this is the error but i dont know how to fix it.
alList = new ArrayList<String>();
aaList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, alList);
list.setAdapter(aaList);
}
public void clickAdd(View v) { //when clicking the add button(add)
Intent intent = new Intent(MainActivity.this, AddItem.class);
startActivity(intent);
}
private void addItems(){
String s = getIntent().getStringExtra("item");
aaList.add(s);
aaList.notifyDataSetChanged();
}
AddItem class :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_layout);
et = (EditText) findViewById(R.id.etAdd);
bt = (Button) findViewById(R.id.badd);
}
public void add(View v){ //when clicking the add button(bt)
edit = et.getText().toString();
Intent intent = new Intent(AddItem.this, MainActivity.class);
intent.putExtra("item", edit);
startActivity(intent);
}
Can you please tell me where and why i am going wrong? Thank You
First of all, you should use startACtivityForResult
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
Then in your second Activity
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
And back in your fist one:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
and then, your addItem should do the trick:
private void addItems(String s){
aaList.add(s);
aaList.notifyDataSetChanged();
}

Categories