Intent is sending back info blank - java

I'm writing an app to take a survey and tally's the answers. The app has a default question "Do you like the Vikings", which works fine. I added in the feature to edit the question & buttons but now both are blank by default. Worse, no matter what I put in the edit activity, it stays blank!
public class MainActivity extends ActionBarActivity {
private Button mYesButton;
private Button mNoButton;
private Button mResultsButton;
private TextView mQuestionTextView;
private Button mEditButton;
private TextView EditQuestion;
private Button YesButtonEdit;
private Button NoButtonEdit;
int YesTimes;
int NoTimes;
public static final String EXTRA_EDIT_QUESTION = "com.example.surveyapp.EditActivity.edit_this_question";
//private SurveryQuestion[] mQuestionBank = new SurveryQuestion[] {
// new SurveryQuestion(R.string.question_1),
// new SurveryQuestion()
//};
String[] mSurveyArray = {
new String("hello"), //More questions coming soon!
new String("Hello1"),
//new String(R.string.question_1)
};
int mCurrentIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mYesButton = (Button)findViewById(R.id.yes_button); //Yes/NoButton modified from LMGTFY app
mYesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YesTimes += 1;
mCurrentIndex = (mCurrentIndex + 1) % mSurveyArray.length;
// Coming soon!
}
});
mNoButton = (Button)findViewById(R.id.no_button);
mNoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NoTimes += 1;
}
});
mResultsButton = (Button)findViewById(R.id.result_button);
mResultsButton.setOnClickListener(new View.OnClickListener() {
//Here we make toast!
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), //Discovered getApplicationContext from stackoverflow
mYesButton + ": " + YesTimes + mNoButton + ": " + NoTimes, Toast.LENGTH_SHORT).show();
}
});
mEditButton = (Button)findViewById(R.id.edit_button); //This is the button that lets you edit the survey
mEditButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, EditActivity.class);
startActivity(i);
}
});
Intent intent = getIntent();
String EditQuestion = intent.getStringExtra("sendBack");
String YesButtonEdit = intent.getStringExtra("sendBack2");
String NoButtonEdit = intent.getStringExtra("sendBack3");
TextView mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
Button mYesButton = (Button)findViewById(R.id.yes_button);
Button mNoButton = (Button)findViewById(R.id.no_button);
mQuestionTextView.setText(EditQuestion);
mYesButton.setText(YesButtonEdit);
mNoButton.setText(NoButtonEdit);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the second activity where you add in your edited responses.
package com.example.surveyapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class EditActivity extends Activity {
private Button mCompleteButton;
private EditText mEditText1;
private EditText mEditText2;
private EditText mEditText3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mCompleteButton = (Button)findViewById(R.id.CompleteButton);
mCompleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText mEditText1 = (EditText) findViewById(R.id.editText1);
EditText mEditText2 = (EditText) findViewById(R.id.editText2);
EditText mEditText3 = (EditText) findViewById(R.id.editText3);
Intent i = new Intent(EditActivity.this, MainActivity.class);
i.putExtra("SendBack", mEditText1.getText().toString()); //This is supposed to use EXTRA to send back the data
i.putExtra("SendBack2", mEditText2.getText().toString());
i.putExtra("SendBack3", mEditText2.getText().toString());
startActivity(i);
}
});
}
}
I've tried several approaches and I've gotten nothing. Does anyone know the answer?

I think that the problem might be that when you call startActivity with an intent to make a new MainActivity, android recognizes that there is already an instance of this activity, so it just brings it to the front.
One way to get around this would be to first make a public method that you can use to edit the fields in your MainActivity, and you can call this method just before you would like to send the user back to this activity from the edit activity. Also, instead of creating a new activity, just close the edit activity and android will resume the main activity.
If this doesn't work, post any logcat data you have from testing your app.

For clean and clearer code, initialize all your button objects in the onCreate() method. Now try putting the following code in the onResume callback method like this
#Override
public void onResume()
{
super.onResume();
Intent intent = getIntent();
String EditQuestion = intent.getStringExtra("sendBack");
String YesButtonEdit = intent.getStringExtra("sendBack2");
String NoButtonEdit = intent.getStringExtra("sendBack3");
TextView mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
Button mYesButton = (Button)findViewById(R.id.yes_button);
Button mNoButton = (Button)findViewById(R.id.no_button);
mQuestionTextView.setText(EditQuestion);
mYesButton.setText(YesButtonEdit);
mNoButton.setText(NoButtonEdit);
}
remove this code from your onCreate(...) method and place it in your onResume method. When you clcik the edit button and want to get the data in the edit activity, do like so from the callling activity
mEditButton = (Button)findViewById(R.id.edit_button); //This is the button that lets you edit the survey
mEditButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, EditActivity.class);
i.putExtra("sendBack","send back value");
i.putExtra("sendBack2","send back 2 value");
startActivity(i);
}
});
with this, you should now be able to modify and pass in the values you wish to modify in your EditActivity

Related

Cant get an int value from on class to another class : android studio

I'm kind of new to android. I want to get an int value id(id of dynamically generated buttons) from class MainPage into class Note when a button is clicked. but the value of id always turns to zero in Note class.
here's the summerized code:
MainPage class:
public class MainPage extends AppCompatActivity {
public int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int j=0; j<allnotes.size(); j++) {
//generating buutons
final Button preview_text = new Button(this);
preview_text.setId(j)
preview_text.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//getting id of the clicked button
id=v.getId();
startActivity(new Intent(MainPage.this, Note.class));
}
});
}
}
}
Notes class:
public class Note extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
MainPage obj=new MainPage();
int id=obj.id
View parentLayout = findViewById(android.R.id.content);
Snackbar mySnackbar = Snackbar.make(parentLayout,Integer.toString(id) , 10000);
mySnackbar.show();
}
in snackbar message, id is always zero.
You need to add the id to the Intent you use to start the Note activity. You do this by using Intent.putExtra(...) and in Note you retrieve it via getIntent().getIntExtra(...)
Here I implemented #Riccully Answer in your code.
MainPage.java
preview_text.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//getting id of the clicked button
id = v.getId();
Intent intent = new Intent(MainPage.this, Note.class);
intent.putExtra("id_value", id);
startActivity(intent);
}
});
Note.java
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
int id = getIntent().getIntExtra("id_value", 0);
View parentLayout = findViewById(android.R.id.content);
Snackbar mySnackbar = Snackbar.make(parentLayout, Integer.toString(id), 10000);
mySnackbar.show();
}
we can do this via intent Because Android Intent is the message that is passed between components such as activities, content providers, broadcast receivers, services, etc.
In Our case, we can send the v.getId() to Note.java, viaputExtra
intent.putExtra("view_id",v.getId());
and receive the value in Note.java by using
getIntent().getIntExtra("view_id", 0);

Database is saved on click but not going to the next class when clicked

public class JobSignup extends AppCompatActivity {
private Button btn;
private ImageView imageview;
private static final String IMAGE_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job_signup);
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReferenceFromUrl("https://rozgarinepal100.firebaseio.com/");
final TextView userName = (TextView) findViewById(R.id.userName);
final EditText writeName = (EditText) findViewById(R.id.writeName);
ImageButton sendDataToFirebase = (ImageButton) findViewById(R.id.sendDataToFirebase);
final TextView dateOfBirth = (TextView) findViewById(R.id.dateOfBirth);
final EditText enterDateOfBirth = (EditText) findViewById(R.id.enterDateOfBirth);
if ( writeName.getText().toString().length() == 0)
{
writeName.setError("Username Compulsory");
}
// if( TextUtils.isEmpty(writeName.getText())) {
// /**
// * You can Toast a message here that the Username is Empty
// **/
//
// writeName.setError("First name is required!");
//
// }
sendDataToFirebase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myRef.child("0").child(userName.getText().toString()).setValue(writeName.getText().toString());
//myRef.child("NAME:").setValue("Kathmandu University");
myRef.child("0").child(dateOfBirth.getText().toString()).setValue(enterDateOfBirth.getText().toString());
}
});
}
public void onClick(View v) {
Intent i = new Intent(this, HomeActivity.class);
startActivity(i);
}
}
My code is running fine and database is also saved on click but on click it is not going to the next class using intent.Here in the onclick listener function i have added link for database when the button is clicked on android.Database is running fine on click operation but i am not able to go the next class which i have created.I have the only problem to go the next class when the same button is clicked.I am trying to enable the database and goto the next class using same button.
Try this, It will work...
sendDataToFirebase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myRef.child("0").child(userName.getText().toString()).setValue(writeName.getText().toString());
//myRef.child("NAME:").setValue("Kathmandu University");
myRef.child("0").child(dateOfBirth.getText().toString()).setValue(enterDateOfBirth.getText().toString());
Intent i = new Intent(JobSignup.this, HomeActivity.class);
startActivity(i);
}
});

How to delete individual elements from textview on Android studio

I am doing this project, can anyone help me to delete individual elements from the text view?enter image description here
here's i implemented the 'button' to insert and 'button2' to delete, and here's the code down bellow
public class MainActivity extends Activity {
private EditText editText;
private Button button;
private TextView textView;
private static final String TAG = "MainActivity";
// To hold all data in different mode : Portrait and landscape
private final String text_context = "TX";
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: in");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.editText);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById((R.id.textView));
textView.setText(""); // make it no text at runtime, but text at view
textView.setMovementMethod(new ScrollingMovementMethod()); // make it scrolling
editText.setText("");
final View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String result = editText.getText().toString();
result += "\n";
textView.append(result);
editText.setText(""); // text on EDITTEXT will disappear as soon as we click the button
}
};
final View.OnClickListener onClickListener1 = new View.OnClickListener() {
#Override
public void onClick(View view) {
}
};
if(editText != null)
button.setOnClickListener(onClickListener);
Log.d(TAG, "onCreate:out");
}
}
Please help me TO IMPLEMENT DELETE ACTION VIA BUTTON2....
Right now your onclick listeners are generically listening for clicks on any view.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Handle button events
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Handle button2 events
}
});
Or better yet implement View.OnClickListener() on your activity
Use regex
String input = editText.getText().toString();
String regex = "\\b" + input + "\\b";
String tvText = textView.getText().toString();
tvText = tvText.replaceAll(regex, "");
textView.setText(tvText);
Put this code in
final View.OnClickListener onClickListener1 = new View.OnClickListener() {
#Override
public void onClick(View view) {
//code goes here
}
};
if(editText != null)
// add this onclick to your button2
button2.setOnClickListener(onClickListener1);
Log.d(TAG, "onCreate:out");
}

Displaying data in main Activity from two other Activities

I'm very new to Android Studio. I am trying to get data from my EditMessage and EditSendTo activities to my TestExplicitIntents activity. This is a school project, but all I was required to do was create the EditSendTo activity and display the phone number in the TestExplicitIntents activity.
I can do this following lessons on the other activities, but I would like to learn how to display the data from both Edit activities. I have tried several approaches but everything I try ends with either the EditMessage or the EditSendTo producing null results once the Done button is pressed.
public class TestExplicitIntents extends Activity {
public static final String CLASS_TAG = "TestExplicitIntents";
public static final int NEW_MESSAGE_REQUEST = 1;
public static final int NEW_PHONE_REQUEST = 1;
private String message = "";
private String phone = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_explicit_intents);
// Getting to the views defined in the XML files.
TextView tvMessageDetails = (TextView) findViewById(R.id.tvMessageDetails);
tvMessageDetails.setBackgroundColor(Color.GREEN);
tvMessageDetails.setMovementMethod(new ScrollingMovementMethod());
message ="Is it St. Patricks Day?";
phone = "";
setSummary();
// Responding to an event - the onClick for the Edit Message Button
// Using a named inner class
Button btnEditMessage;
btnEditMessage = (Button) this.findViewById(R.id.btnEditMessage);
HandleButtonEditMessageOnClick buttonEditMessageOnClick;
buttonEditMessageOnClick = new HandleButtonEditMessageOnClick();
btnEditMessage.setOnClickListener(buttonEditMessageOnClick);
// Responding to an event - the onClick for the Edit Send To Button
// Using a named inner class
Button btnEditSendTo;
btnEditSendTo = (Button) this.findViewById(R.id.btnEditSendTo);
HandleButtonEditSendToOnClick buttonEditSendToOnClick;
buttonEditSendToOnClick = new HandleButtonEditSendToOnClick();
btnEditSendTo.setOnClickListener(buttonEditSendToOnClick);
}
/**
* Put together a summary of the phone and message and display it.
*/
private void setSummary() {
StringBuilder summary;
summary = new StringBuilder("Sending To:\n");
summary.append(phone);
summary.append("\n\nMessage:\n");
summary.append(message);
TextView tvMessageDetails = (TextView) findViewById(R.id.tvMessageDetails);
tvMessageDetails.setText(summary);
}
/**
* Handle Edit Button OnClick by starting the activity This is an example of
* starting another activity using an explicit Intent.
*
*/
#SuppressWarnings("rawtypes")
public class HandleButtonEditMessageOnClick implements OnClickListener {
public static final String CLASS_TAG = "HandleButtonEditMessageOnClick";
public void onClick(View v) {
Log.i(CLASS_TAG, "onClick started...");
// Example of an EXPLICIT intent, as we are naming the java class to use
// (EditMessage.class)
Intent editIntent;
Activity sourceActivity;
Class destinationClass;
sourceActivity = TestExplicitIntents.this;
destinationClass = EditMessage.class;
editIntent = new Intent(sourceActivity, destinationClass);
// Sending information to the intent receiver through the Intent object
editIntent.putExtra("CURRENT_MESSAGE", TestExplicitIntents.this.message);
//startActivity(editIntent);
startActivityForResult(editIntent, NEW_MESSAGE_REQUEST);
}
}
#SuppressWarnings("rawtypes")
public class HandleButtonEditSendToOnClick implements OnClickListener {
public static final String CLASS_TAG = "HandleButtonEditSendToOnClick";
public void onClick(View v) {
Log.i(CLASS_TAG, "onClick started...");
Intent editSendIntent;
Activity startActivity;
Class endClass;
startActivity = TestExplicitIntents.this;
endClass = EditSendTo.class;
editSendIntent = new Intent(startActivity, endClass);
// Sending information to the intent receiver through the Intent object
editSendIntent.putExtra("CURRENT_PHONE", TestExplicitIntents.this.phone);
//startActivity(editIntent);
startActivityForResult(editSendIntent, NEW_PHONE_REQUEST);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
String newMessage = getIntent().getStringExtra("NEW_MESSAGE");
String curMessage = getIntent().getStringExtra("CURRENT_MESSAGE");
String newPhone = getIntent().getStringExtra("NEW_PHONE");
String curPhone = getIntent().getStringExtra("CURRENT_PHONE");
// Check which request we're responding to
if (requestCode == NEW_MESSAGE_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
message = newMessage;
phone = curPhone;
setSummary();
}
}
if (requestCode == NEW_PHONE_REQUEST) {
if (resultCode == RESULT_OK) {
message = curMessage;
phone = newPhone;
setSummary();
}
}
}
}
Here is EditMessage:
public class EditMessage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_message);
// Get the intent for this activity. Every activity has an intent and
// set the EditText contents to the string in the extra info that comes with
// the intent
Intent editIntent;
EditText etMessage;
editIntent = this.getIntent();
String theMessage;
theMessage = editIntent.getStringExtra("CURRENT_MESSAGE");
etMessage = (EditText) this.findViewById(R.id.etMessage);
etMessage.setText(theMessage);
// Get an event handler going for the Done button so that we can return the
// new message
Button btnDone = (Button) this.findViewById(R.id.btnDone);
btnDone.setOnClickListener(new ButtonDoneOnClickHandler());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_edit_message, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Handles the Button Done onClick event by creating a resulting Intent and
* finishing
*/
private class ButtonDoneOnClickHandler implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("NEW_MESSAGE", ((EditText) findViewById(R.id.etMessage)).getText().toString());
setResult(RESULT_OK, intent);
finish();
}
}
}
Here is EditSendTo:
public class EditSendTo extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_send_to);
// Get the intent for this activity. Every activity has an intent and
// set the EditText contents to the string in the extra info that comes with
// the intent
Intent editIntent;
EditText etPhone;
editIntent = this.getIntent();
String thePhone;
thePhone = editIntent.getStringExtra("CURRENT_PHONE");
etPhone = (EditText) this.findViewById(R.id.etPhone);
etPhone.setText(thePhone);
// Get an event handler going for the Done button so that we can return the
// new message
Button btnDone = (Button) this.findViewById(R.id.btnDone);
btnDone.setOnClickListener(new ButtonDoneOnClickHandler());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_edit_send_to, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Handles the Button Done onClick event by creating a resulting Intent and
* finishing
*/
private class ButtonDoneOnClickHandler implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("NEW_PHONE", ((EditText)
findViewById(R.id.etPhone)).getText().toString());
setResult(RESULT_OK, intent);
finish();
}
}
}
I tried to figure this out for a few days and have had no luck finding an answer.
I would really appreciate a pointer in the right direction.
Your code should be like below :
TestExplicitIntents.java
public class TestExplicitIntents extends Activity {
public static final String CLASS_TAG = "TestExplicitIntents";
public static final int NEW_MESSAGE_REQUEST = 1;
public static final int NEW_PHONE_REQUEST = 2;
private String message = "";
private String phone = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_explicit_intents);
// Getting to the views defined in the XML files.
TextView tvMessageDetails = (TextView) findViewById(R.id.tvMessageDetails);
tvMessageDetails.setBackgroundColor(Color.GREEN);
tvMessageDetails.setMovementMethod(new ScrollingMovementMethod());
message = "Is it St. Patricks Day?";
phone = "";
setSummary();
// Responding to an event - the onClick for the Edit Message Button
// Using a named inner class
Button btnEditMessage;
btnEditMessage = (Button) this.findViewById(R.id.btnEditMessage);
HandleButtonEditMessageOnClick buttonEditMessageOnClick;
buttonEditMessageOnClick = new HandleButtonEditMessageOnClick();
btnEditMessage.setOnClickListener(buttonEditMessageOnClick);
// Responding to an event - the onClick for the Edit Send To Button
// Using a named inner class
Button btnEditSendTo;
btnEditSendTo = (Button) this.findViewById(R.id.btnEditSendTo);
HandleButtonEditSendToOnClick buttonEditSendToOnClick;
buttonEditSendToOnClick = new HandleButtonEditSendToOnClick();
btnEditSendTo.setOnClickListener(buttonEditSendToOnClick);
}
/**
* Put together a summary of the phone and message and display it.
*/
private void setSummary() {
StringBuilder summary;
summary = new StringBuilder("Sending To:\n");
summary.append(phone);
summary.append("\n\nMessage:\n");
summary.append(message);
TextView tvMessageDetails = (TextView) findViewById(R.id.tvMessageDetails);
tvMessageDetails.setText(summary);
}
/**
* Handle Edit Button OnClick by starting the activity This is an example of
* starting another activity using an explicit Intent.
*/
#SuppressWarnings("rawtypes")
public class HandleButtonEditMessageOnClick implements View.OnClickListener {
public static final String CLASS_TAG = "HandleButtonEditMessageOnClick";
public void onClick(View v) {
Log.i(CLASS_TAG, "onClick started...");
// Example of an EXPLICIT intent, as we are naming the java class to use
// (EditMessage.class)
Intent editIntent;
Activity sourceActivity;
Class destinationClass;
sourceActivity = TestExplicitIntents.this;
destinationClass = EditMessage.class;
editIntent = new Intent(sourceActivity, destinationClass);
// Sending information to the intent receiver through the Intent object
editIntent.putExtra("CURRENT_MESSAGE", TestExplicitIntents.this.message);
//startActivity(editIntent);
startActivityForResult(editIntent, NEW_MESSAGE_REQUEST);
}
}
#SuppressWarnings("rawtypes")
public class HandleButtonEditSendToOnClick implements View.OnClickListener {
public static final String CLASS_TAG = "HandleButtonEditSendToOnClick";
public void onClick(View v) {
Log.i(CLASS_TAG, "onClick started...");
Intent editSendIntent;
Activity startActivity;
Class endClass;
startActivity = TestExplicitIntents.this;
endClass = EditSendTo.class;
editSendIntent = new Intent(startActivity, endClass);
// Sending information to the intent receiver through the Intent object
editSendIntent.putExtra("CURRENT_PHONE", TestExplicitIntents.this.phone);
//startActivity(editIntent);
startActivityForResult(editSendIntent, NEW_PHONE_REQUEST);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check which request we're responding to
if (requestCode == NEW_MESSAGE_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
message = data.getStringExtra("NEW_MESSAGE");
setSummary();
}
} else if (requestCode == NEW_PHONE_REQUEST) {
if (resultCode == RESULT_OK) {
phone = data.getStringExtra("NEW_PHONE");
setSummary();
}
}
}
}
EditSendTo class:
public class extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_send_to);
// Get the intent for this activity. Every activity has an intent and
// set the EditText contents to the string in the extra info that comes with
// the intent
Intent editIntent;
EditText etPhone;
editIntent = this.getIntent();
String thePhone;
thePhone = editIntent.getStringExtra("CURRENT_PHONE");
etPhone = (EditText) this.findViewById(R.id.etPhone);
etPhone.setText(thePhone);
// Get an event handler going for the Done button so that we can return the
// new message
Button btnDone = (Button) this.findViewById(R.id.btnDone);
btnDone.setOnClickListener(new ButtonDoneOnClickHandler());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.menu_edit_send_to, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Handles the Button Done onClick event by creating a resulting Intent and
* finishing
*/
private class ButtonDoneOnClickHandler implements View.OnClickListener {
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("NEW_PHONE", ((EditText)
findViewById(R.id.etPhone)).getText().toString());
setResult(RESULT_OK, intent);
finish();
}
}
}
EditMessage class:
public class EditMessage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_message);
// Get the intent for this activity. Every activity has an intent and
// set the EditText contents to the string in the extra info that comes with
// the intent
Intent editIntent;
EditText etMessage;
editIntent = this.getIntent();
String theMessage;
theMessage = editIntent.getStringExtra("CURRENT_MESSAGE");
etMessage = (EditText) this.findViewById(R.id.etMessage);
etMessage.setText(theMessage);
// Get an event handler going for the Done button so that we can return the
// new message
Button btnDone = (Button) this.findViewById(R.id.btnDone);
btnDone.setOnClickListener(new ButtonDoneOnClickHandler());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_edit_message, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Handles the Button Done onClick event by creating a resulting Intent and
* finishing
*/
private class ButtonDoneOnClickHandler implements View.OnClickListener {
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("NEW_MESSAGE", ((EditText) findViewById(R.id.etMessage)).getText().toString());
setResult(RESULT_OK, intent);
finish();
}
}
}

Android - Passing an ArrayList of Custom Objects to Another Activity

So, I've been struggling on this for a while and have searched on here for hours without finding anything that really helped. I have a custom class Streak. When the user creates a new Streak in my Main Activity, I want for that streak to be added to a list of total streaks, which I would then access from an AllStreaks activity. I have tried using Gson, but received errors. What I have below is working for the time being, but since my global variable has to be declared as new. I don't really want to use a MySQL database as this info needs to be quickly editable and I don't want to have to constantly connect to that to potentially change just one detail.
Sorry if my code is a mess or this makes no sense, I'm coming to realize I'm really shitty at programming anyway.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private String userID;
private int streakCounter;
private int mainStreakCounter;
private RelativeLayout quickAdd;
private EditText quickSubmitStreak;
private Button quickSubmitButton;
private Button mainStreak1;
private Button mainStreak2;
private Button mainStreak3;
private Button mainStreak4;
private Button allStreaks;
private Button addStreak;
private Dialog pickDialog;
private Button healthButton;
private Button mentalButton;
private Button personalButton;
private Button professionalButton;
private Button socialButton;
private Button submitStreakButton;
private TextView todaysDate;
private EditText chooseDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*
Creates shared preferences and editor
*/
prefs = getSharedPreferences("carter.streakly", MODE_PRIVATE);
editor = prefs.edit();
// Checks if it's the first time the user opens the app. If so, generates a unique user ID and stores it in shared prefs
if (prefs.getBoolean("firstTime", true)){
userID = UUID.randomUUID().toString();
editor.putString("user", userID);
editor.putBoolean("firstTime", false);
editor.commit();
}
streakCounter = 0; // CHANGE TO streakCounter = prefs.getInt("streakCounter", 0) later
mainStreakCounter = 0; // CHANGE TO mainStreakCount = prefs.getInt("mainStreakCounter", 0) later
quickSubmitStreak = (EditText) findViewById(R.id.enter_goal);
quickSubmitButton = (Button) findViewById(R.id.submit_button);
mainStreak1 = (Button) findViewById(R.id.main_goal_1);
mainStreak2 = (Button) findViewById(R.id.main_goal_2);
mainStreak3 = (Button) findViewById(R.id.main_goal_3);
mainStreak4 = (Button) findViewById(R.id.main_goal_4);
allStreaks = (Button) findViewById(R.id.main_goal_5);
addStreak = (Button) findViewById(R.id.add_streak_button);
/*
if (streakCounter > 4){
quickAdd.setVisibility(View.INVISIBLE);
}
mainStreak1.setText(prefs.getString("mainKeyOne", ""));
mainStreak2.setText(prefs.getString("mainKeyTwo", ""));
mainStreak3.setText(prefs.getString("mainKeyThree", ""));
mainStreak4.setText(prefs.getString("mainKeyFour", ""));
/*
Sets the text to the lowest unused main streak to the inputted streak name
Stores the streak name in shared prefs so it will be there for next time app opens
Increases the total streak count
*/
quickSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mainStreakCounter < 4){
switch(mainStreakCounter){
case 0:
mainStreak1.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyOne", quickSubmitStreak.getText().toString()).commit();
break;
case 1:
mainStreak2.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyTwo", quickSubmitStreak.getText().toString()).commit();
break;
case 2:
mainStreak3.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyThree", quickSubmitStreak.getText().toString()).commit();
break;
case 3:
mainStreak4.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyFour", quickSubmitStreak.getText().toString()).commit();
break;
default:break;
}
}
mainStreakCounter++;
AllStreaks.streakList.add(new Streak(quickSubmitStreak.getText().toString()));
// ADD THESE TO SHARED PREFERENCES AT SOME POINT
}
});
/*
Brings user to the All Streaks activity, and passes the LinkedList<Streak> streakList
*/
allStreaks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AllStreaks.class);
startActivity(intent);
}
});
/*
Shows an Alert Dialog that allows users to enter in the type of streak they want
*/
addStreak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createCustomDialog();
}
});
}
private void createCustomDialog(){
pickDialog = new Dialog(MainActivity.this);
pickDialog.setContentView(R.layout.dialog_add_streak);
final EditText chooseName = (EditText) pickDialog.findViewById(R.id.dialog_acitivty_name);
healthButton = (Button) pickDialog.findViewById(R.id.dialog_health);
mentalButton = (Button) pickDialog.findViewById(R.id.dialog_mental);
personalButton = (Button) pickDialog.findViewById(R.id.dialog_personal);
professionalButton = (Button) pickDialog.findViewById(R.id.dialog_professional);
socialButton = (Button) pickDialog.findViewById(R.id.dialog_social);
submitStreakButton = (Button) pickDialog.findViewById(R.id.dialog_submit_button);
todaysDate = (TextView) pickDialog.findViewById(R.id.dialog_today);
chooseDate = (EditText) pickDialog.findViewById(R.id.dialog_input_date);
pickDialog.show();
healthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 0).commit();
editor.putString("Category", "Health");
editor.commit();
recolorCategory();
}
});
mentalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 1).commit();
editor.putString("Category", "Mental");
editor.commit();
recolorCategory();
}
});
personalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 2).commit();
editor.putString("Category", "Personal");
editor.commit();
recolorCategory();
}
});
professionalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 3).commit();
editor.putString("Category", "Professional");
editor.commit();
recolorCategory();
}
});
socialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 4).commit();
editor.putString("Category", "Social");
editor.commit();
recolorCategory();
}
});
todaysDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
todaysDate.setTextColor(Color.rgb(51,51,255));
chooseDate.setTextColor(Color.rgb(0,0,0));
editor.putInt("todayOrChosen", 1).commit();
}
});
chooseDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseDate.setTextColor(Color.rgb(51,51,255));
todaysDate.setTextColor(Color.rgb(0,0,0));
editor.putInt("todayOrChosen", 2).commit();
}
});
submitStreakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*
If the user selected today's date, enter the days kept as 0. If the user selected how long they've kept the streak for, enter the days kept as chooseDate
*/
if(prefs.getInt("todayOrChosen", 1) == 1){
//streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
//new SimpleDateFormat("dd-MM-yyyy").format(new Date()), 0));
AllStreaks.streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
new SimpleDateFormat("dd-MM-yyyy").format(new Date()), 0));
}
else {
//streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
//new SimpleDateFormat("dd-MM-yyyy").format(new Date()), Integer.parseInt(chooseDate.getText().toString())));
AllStreaks.streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
new SimpleDateFormat("dd-MM-yyyy").format(new Date()), Integer.parseInt(chooseDate.getText().toString())));
}
/*
Update streakList in Shared Preferences
*/
/*
Display an Alert Dialog indicating that a streak has been added
*/
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Streak Added")
.setPositiveButton("OK", null)
.create()
.show();
pickDialog.dismiss();
}
});
}
/*
Highlights which category is currently chosen
*/
private void recolorCategory(){
Button[] categoryList = {healthButton, mentalButton, personalButton, professionalButton, socialButton};
int recolorIndex = prefs.getInt("AddCategory", 0);
categoryList[recolorIndex].setTextColor(Color.rgb(51,51,255));
for (int i = 0; i < 5; i++){
if (i != recolorIndex) categoryList[i].setTextColor(Color.rgb(153, 255, 102));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
AllStreaks.java:
public class AllStreaks extends AppCompatActivity {
public static ArrayList<Streak> streakList = new ArrayList<>();
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private ArrayList<Streak> allStreakList;
private TableLayout mTableLayout;
private TableRow mTableRow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_streaks);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*
if (streakList == null){
Button streakButton = new Button(this);
streakButton.setText("Try again");
}
else{
for (int j = 0; j < streakList.size(); j++){
allStreakList.add(streakList.get(j));
}
}*/
prefs = getSharedPreferences("carter.streakly", MODE_PRIVATE);
editor = prefs.edit();
mTableLayout = (TableLayout) findViewById(R.id.all_streak_table);
int i = 0;
while (i < streakList.size()){
if (i % 2 == 0){
mTableRow = new TableRow(this);
mTableLayout.addView(mTableRow);
}
Button streakButton = new Button(this);
streakButton.setText(String.valueOf(streakList.get(i).getDaysKept()));
streakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AllStreaks.this, EnlargedActivity.class);
startActivity(intent);
}
});
mTableRow.addView(streakButton);
i++;
}
}
}
you cannot pass object directly.you have to parcelable or serialize it. but in parecelable is part of android where serialzation is part of java so i suggest you to use parcelable.
you can make model class to parcelable from this link if you dont want to code for parcelabel.
parcelable creator
you can achieve like this.
class Car implements Parcelable {
public int regId;
public String brand;
public String color;
public Car(Parcel source) {
regId = source.getInt();
brand = source.getString();
color = source.getString();
}
public Car(int regId, String brand, String color) {
this.regId = regId;
this.brand = brand;
this.color = color;
}
public int describeContents() {
return this.hashCode();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(regId);
dest.writeString(brand);
dest.writeString(color);
}
public static final Parcelable.Creator CREATOR
= new Parcelable.Creator() {
public Car createFromParcel(Parcel in) {
return new Car(in);
}
public Car[] newArray(int size) {
return new Car[size];
}
};}
And you can pass it like below.
ArrayList carList = new ArrayList();
carList.add(new Car('1','Honda','Black');
carList.add(new Car('2','Toyota','Blue');
carList.add(new Car('3','Suzuki','Green');
Intent i = new Intent(getApplicationContext(), CarDetailActivity.class);
i.putParcelableArrayListExtra("cars", carList);
this.startActivity(i);
you can get it like below:
Intent i = this.getIntent();
ArrayList<Car> carList = (ArrayList<Car>)i.getParcelableArrayListExtra("cars");`
You need to use Parcelable or Serializable interface.
and the pass it with intent
Intent mIntent = new Intent(context, ResultActivity.class);
mIntent.putParcelableArrayListExtra("list", mArraylist);
startActivity(mIntent);
fetch it in ResultActivity
Bundle bundle = getIntent().getExtras();
mArraylist1 = bundle.getParcelableArrayList("list");
Check this thread for reference
Do this on your Streak class and try,
Streak implements Parcelable
Since your modal class has not serialized, it may not able to pass via bundle. You can do that by implementing the Parcelable interface.
Parcelable is an Android specific interface where you implement the
serialization yourself. It was created to be far more efficient that
Serializable, and to get around some problems with the default Java
serialization scheme.
Serializable is a standard Java interface. You simply mark a class
Serializable by implementing the interface, and Java will
automatically serialize it in certain situations.
Courtsy

Categories