How can I prevent null from displaying in the TextView? - java

Very new to Android, and I'm honestly stumped by this.
So I have my MainActivity receiving some strings from a second activity, CallAnActivity.
I've made an intent to pass the strings back to the main activity, and they are displayed in a TextView. But before I enter any information, I would like for this text view to contain nothing and look blank.
But when the MainActivity is first launched, the text view, displayMessageActivity, is displaying multiple null values. As there are three strings being sent, it just repeats the word null three times.
The code for the MainActivity is:
//callAnActivityButton to open second activity of app
Button callAnActivityButton = findViewById(R.id.callActivityButton);
callAnActivityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v ) {
Intent intent = new Intent(MainActivity.this, CallAnActivity.class);
startActivity(intent);
}
});
Intent intent = getIntent();
String emailAddress = intent.getStringExtra("emailAddress") + "\n";
String emailSubject = intent.getStringExtra("emailSubject") + "\n";
String emailBody = intent.getStringExtra("emailBody");
//TextView to display text from second activity
TextView displayMessageText = findViewById(R.id.displayMessageText);
displayMessageText.setText(emailAddress + emailSubject + emailBody);
The code for the second activity, CallAnActivity, is:
public void sendText(){
String emailAddress = mEditTextAddress.getText().toString();
String emailSubject = mEditTextSubject.getText().toString();
String emailBody = mEditTextBody.getText().toString();
Intent intent = new Intent(CallAnActivity.this, MainActivity.class);
intent.putExtra("emailAddress", emailAddress);
intent.putExtra("emailSubject", emailSubject);
intent.putExtra("emailBody", emailBody);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call_an);
mEditTextAddress = findViewById(R.id.emailAddressText);
mEditTextSubject = findViewById(R.id.emailSubjectText);
mEditTextBody = findViewById(R.id.emailBodyText);
Button sendTextButton = findViewById(R.id.sendMailButton);
sendTextButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View v) {
sendText();
}
});
}

Just surround your setText call with an if block:-
if (intent.getStringExtra("emailAddress") != null) {
displayMessageText.setText(emailAddress + emailSubject + emailBody);
}

Change your content like below. Your getExtra syntaxs are wrong
String emailAddress = intent.getExtras().getStringExtra("emailAddress") + "\n";
String emailSubject = intent.getExtras().getStringExtra("emailSubject") + "\n";
String emailBody = intent.getExtras().getStringExtra("emailBody");

Related

Passing an Integer to a different activity to add to main score via textview (android studio)

This is my first project in Android studio. code is a little messy. Im creating a score keeping app for a card game I play with family members.
Im having a problem adding score to main activity from bid activity. how would you store the textview to continue to add to?
Score_activity java code:
public class score_activity extends AppCompatActivity {
// creating an object of the text view
TextView scoreA;
TextView scoreB;
TextView tvA;
TextView tvB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
// assigning the outputs of the user to the object
scoreA = (TextView) findViewById(R.id.scoreA);
scoreB = (TextView) findViewById(R.id.scoreB);
tvA = (TextView) findViewById(R.id.nameA);
tvB = (TextView) findViewById(R.id.nameB);
Bundle bundle = getIntent().getExtras();
String text1 = bundle.getString("Team A");
String text2 = bundle.getString("Team B");
String text3 = getIntent().getStringExtra("ScoreA");
String text4 = getIntent().getStringExtra("ScoreB");
// setting the fetched data to the corresponding text views
tvA.setText(text1);
tvB.setText(text2);
scoreA.setText(text3);
scoreB.setText(text4);
// this method is the logic that increases the value in the text
view by one on every click for team A
}
Bid Activity code
public void scoreTotal(View view) {
String nameA = tvTeamA.getText().toString();
String nameB = tvTeamB.getText().toString();
int bida = Integer.parseInt(bidA.getText().toString());
int tricksTotalA =
Integer.parseInt(tricksA.getText().toString());
int totalB = 25 - tricksTotalA;
int totalScoreBA = mentionteamA + tricksTotalA;
int totalScoreBB = mentionteamB + totalB;
if (bida > totalScoreBA) {
scoreA2 = (bida * -1);
String scoreBoardA = String.valueOf(scoreA2);
String scoreBoardB = String.valueOf(totalScoreBB);
Intent i = new Intent(bid_activity.this,
score_activity.class);
i.putExtra("Team A", nameA);
i.putExtra("Team B", nameB);
i.putExtra("ScoreA", scoreBoardA);
i.putExtra("ScoreB", scoreBoardB);
// starting the activity
startActivity(i);
}
if (bida <= totalScoreBA) {
scoreA2 = totalScoreBA;
String scoreBoardA = String.valueOf(scoreA2);
String scoreBoardB = String.valueOf(totalScoreBB);
Intent i = new Intent(bid_activity.this,
score_activity.class);
i.putExtra("Team A", nameA);
i.putExtra("Team B", nameB);
i.putExtra("ScoreA", scoreBoardA);
i.putExtra("ScoreB", scoreBoardB);
// starting the activity
startActivity(i);
}
if (tricksTotalA == 25) {
scoreA2 = totalScoreBA;
int displayB = 0;
String scoreBoardA = String.valueOf(scoreA2);
String scoreBoardB = String.valueOf(displayB);
Intent i = new Intent(bid_activity.this,
score_activity.class);
i.putExtra("Team A", nameA);
i.putExtra("Team B", nameB);
i.putExtra("ScoreA", scoreBoardA);
i.putExtra("ScoreB", scoreBoardB);
// starting the activity
startActivity(i);
}
One idea is to call
startActivityForResult(i)
instead of
startActivity(i)
Then you can pass a result in BidActivity and capture it in ScoreActiivty's onActivityResult call.
I am just showing how to pass data from your bid activity to score activity.
bid activity
Intent i = new Intent(bid_activity.this, score_activity.class);
i.putExtra("ScoreA2", scoreA2);
i.putExtra("ScoreB2", scoreB2);
startActivity(intent);
score activity
int scoreA2 = getIntent().getIntExtra("ScoreA2");
int scoreB2 = getIntent().getIntExtra("scoreB2");
And for double click, you can follow this thread.

Android Java - using intent to pass value to second activity [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 3 years ago.
I'm writing an android app that tracks your weight and BMI. In order to update or set the two values for the first time, there is a second activity that allows me to input the values that should then pass to the first activity.
I've tried to achieve this in a few ways, the closest I got is the code below:
Second Activity: (UpdateProgressActivity.java)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_body_progress);
Intent intentWeight = getIntent();
String WeightText = intentWeight.getStringExtra(EXTRA_MESSAGE);
TextView messageWeight = findViewById(R.id.weight);
messageWeight.setText(WeightText);
Intent intentBMI = getIntent();
String BMIText = intentBMI.getStringExtra(EXTRA_MESSAGE);
TextView messageBMI = findViewById(R.id.bmi);
messageBMI.setText(BMIText);
updateButton = findViewById(R.id.updateBodyProgress);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivityUpdateProgress();
}
});
}
First Activity: (BodyProgressActivity.java)
public class UpdateProgressActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_progress);
Button confirmProgress;
confirmProgress = findViewById(R.id.confirmBodyStatus);
confirmProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
returnToActivityProgress();
}
});
}
protected void returnToActivityProgress() {
Intent intent = new Intent(this, BodyProgressActivity.class);
startActivity(intent);
}
public void createStatus(View view) {
EditText messageWeight = findViewById(R.id.textNewWeight);
String textWeight = messageWeight.getText().toString();
Intent intentWeight = new Intent(Intent.ACTION_SEND); intentWeight.setType("text/plain");
intentWeight.putExtra(Intent.EXTRA_TEXT, textWeight);
String textWeigthTemp = getString(R.string.currentWeight);
Intent chosenIntentWeight = Intent.createChooser(intentWeight, textWeigthTemp);
startActivity(chosenIntentWeight);
EditText messageBMI = findViewById(R.id.textNewWeight);
String textBMI = messageBMI.getText().toString();
Intent intentBMI = new Intent(Intent.ACTION_SEND); intentBMI.setType("text/plain");
intentWeight.putExtra(Intent.EXTRA_TEXT, textBMI);
String textBMITemp = getString(R.string.currentBMI);
Intent chosenIntentBMI = Intent.createChooser(intentWeight, textBMITemp);
startActivity(chosenIntentBMI);
}
}
I'm getting the values from "textNewWeight" and "textNewBMI" from the second activity and must pass them to "weight" and "bmi" on the first activity.
What I'm getting in the first activity is just blank.
In the first activity. Use this code. We are using putExtra method to send the data to next activity through key and value. Key is the 1st parameter and value is the 2nd parameter. Key name can be your choice and it is used to retrieve the data in the 2nd activity. Value is the data which you want ti send to next activity.
Intent i=new Intent(firstactivity.this,secondactivity.class);
String weight=messageWeight.getText().toString();
i.putExtra(“weight”,weight);
startActivity(i);
In the second activity,use this to recieve the data.
Bundle b=getIntent().getExtras();
String recievedWeight=b.getString(“weight”);
the parameter name in the b.getString(“”) must be same as which you have declared in the 1st activity.

How can I create two activities (one or the other) dynamically via button click?

I have an activity that loads text views into it. I add a click listener to these text views and want them to open up an activity with different values based on what I click. It ends up that no matter which I click, the same results show up, and more precisely, I use the same info in creating it - which I don't want to do.
public void setTextToTextView (JSONArray jsonArray)
{
RelativeLayout layout = (RelativeLayout) findViewById(R.id.activity_main);
String s = "";
for (int i = 0; i < jsonArray.length(); i++) {
TextView info = new TextView(this); //actually really confused as to what the context I'm setting is - why this? Just saw other people do it like so
JSONObject json = null;
try {
json = jsonArray.getJSONObject(i);
s = s + "ID : " + json.getString("Id") + " Parent: " + json.getString("Parent") +
" Content: " + json.getString("Content") + " User: " + json.getString("User") +
" Timestamp: " + json.getString("Timestamp") + "\n\n";
} catch (JSONException e) {
e.printStackTrace();
}
info.setText(s);
try {
info.setId(Integer.parseInt(json.getString("Id")));
} catch (JSONException e) {
e.printStackTrace();
}
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this,
NewActivity.class);
myIntent.putExtra("key", v.getId()); //this is always the same
startActivity(myIntent);
}
});
layout.addView(info);
}
}
Using two text views, this results in the ID of the second view to always be the value of the key,value pair in the activity I start. I'm not sure what I'm doing wrong at the moment. I believe my problem is in this section, as I can't see where else it might come from.
Any help or suggestions on my code in general would be welcomed. Thank you.
This still isn't solved, so I'll focus on the problem area:
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this,
NewActivity.class);
myIntent.putExtra("key", v.getId()); //this is always the same
startActivity(myIntent);
}
});
No matter what changes I make, this will always give me the exact same v.getId/v.getTag - every time.
I create a new project with your code but the result is correct just as what you hope.Are you sure that your third TextView does not cover the previous ones?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout)findViewById(R.id.activity_main);
int [] a = {1,2};
String [] s = {"textView1","textView2"};
for(int i =0; i <a.length; i++)
{
TextView info = new TextView(this); //actually really confused as to what the context I'm setting is - why this? Just saw other people do it like so
info.setText(s[i]);
info.setId(a[i]);
info.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(),
"clicked:"+v.getId(),Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(MainActivity.this,
NewActivity.class);
myIntent.putExtra("key", v.getId()); //this is always the same
startActivity(myIntent);
}
});
layout.addView(info);
}
The gif:
As a first step, I would move the OnclickListener to outsdie the loop, as it always does the same thing:
View.OnClickListener view_ocl = new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent myIntent = new Intent(MainActivity.this, NewActivity.class);
myIntent.putExtra("key", v.getId()); //this is always the same
startActivity(myIntent);
}};
for(int i =0; i <jsonArray.length(); i++)
{
// ... as before
info.setOnClickListener(view_ocl);
layout.addView(info);
}
As you do, you need to explicitly set the Id, or in some way put an identifier in the view so that your onClick code (which is the same for each View), knows which View has been clicked. At the moment you are reliant on whatever arbitrary Id the system gives to the view.

setText on button from another activity android

I have a problem, I want to click on the list, calling a new activity and rename the button to another name.
I tried several things, nothing worked, can someone please help me?
My class EditarTimes:
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
t = times.get(pos);
CadastroTimes cad = new CadastroTimes();
CadastroTimes.salvar.setText("Alterar");
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
startActivity(intent);
}
};
public class CadastroTimes extends AppCompatActivity {
private Time t;
private timeDatabase db;
private EditText edID;
private EditText edNome;
public Button salvar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cadastro_times);
edID = (EditText) findViewById(R.id.edID);
edNome = (EditText) findViewById(R.id.edNome);
db = new timeDatabase(getApplicationContext());
salvar = (Button) findViewById(R.id.btnCadastrar);
salvar.setText("Cadastrar");
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("Alterar");
}
} else {
newString= (String) savedInstanceState.getSerializable("Alterar");
}
//button in CadastroTimes activity to have that String as text
System.out.println(newString + " AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
salvar.setText(newString);
}
public void salvarTime(View v) {
t = new Time();
t.setNome(edNome.getText().toString());
if (salvar.getText().equals("Alterar")) {
db.atualizar(t);
exibirMensagem("Time atualizado com sucesso!");
} else {
db.salvar(t);
exibirMensagem("Time cadastrado com sucesso!");
}
Intent intent = new Intent(this, EditarTimes.class);
startActivity(intent);
}
private void limparDados() {
edID.setText("");
edNome.setText("");
edNome.requestFocus();
}
private void exibirMensagem(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}
public class EditarTimes extends AppCompatActivity {
private Time t;
private List<Time> times;
private timeDatabase db;
private ListView lvTimes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editar_times);
lvTimes = (ListView) findViewById(R.id.lvTimes);
lvTimes.setOnItemClickListener(selecionarTime);
lvTimes.setOnItemLongClickListener(excluirTime);
times = new ArrayList<Time>();
db = new timeDatabase(getApplicationContext());
atualizarLista();
}
private void excluirTime(final int idTime) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Excluir time?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("Deseja excluir esse time?")
.setCancelable(false)
.setPositiveButton(getString(R.string.sim),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (db.deletar(idTime)) {
atualizarLista();
exibirMensagem(getString(R.string.msgExclusao));
} else {
exibirMensagem(getString(R.string.msgFalhaExclusao));
}
}
})
.setNegativeButton(getString(R.string.nao),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create();
builder.show();
atualizarLista();
}
private void atualizarLista() {
times = db.listAll();
if (times != null) {
if (times.size() > 0) {
TimeListAdapter tla = new TimeListAdapter(
getApplicationContext(), times);
lvTimes.setAdapter(tla);
}
}
}
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
t = times.get(pos);
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
String strName = "Alterar";
intent.putExtra("Alterar", strName);
startActivity(intent);
}
};
private AdapterView.OnItemLongClickListener excluirTime = new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
excluirTime(times.get(pos).getId());
return true;
}
};
private void exibirMensagem(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
public void telaCadastrar(View view) {
Intent intent = new Intent(this, CadastroTimes.class);
startActivity(intent);
}
public void botaoSair(View view) {
Intent intent = new Intent(this, TelaInicial.class);
startActivity(intent);
}
}
You can pass the button caption to CadastroTimes with intent as
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("buttontxt","Changed Text");
startActivity(intent);
Then in CadastroTimes.java set the text of the button to the new value that you passed. The code will look like:
button = (Button)findViewById(R.id.button); // This is your reference from the xml. button is my name, you might have your own id given already.
Bundle extras = getIntent().getExtras();
String value = ""; // You can do it in better and cleaner way
if (extras != null) {
value = extras.getString("buttontxt");
}
button.setText(value);
Do remember to do it in onCreate after setContentView
//From Activity
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("change_tag", "text to change");
startActivity(intent);
//To Activity
public void onCreate(..){
Button changeButton = (Button)findViewById(R.id.your_button);
// Button to set received text
Intent intent = getIntent();
if(null != intent &&
!TextUtils.isEmpty(intent.getStringExtra("change_tag"))) {
String changeText = intent.getStringExtra("change_tag");
// Extracting sent text from intent
changeButton.setText(changeText);
// Setting received text on Button
}
}
1: Use intent.putExtra() to share a value from one activity another activity, as:
In ActivityOne.class :
startActivity(
Intent(
applicationContext,
ActivityTwo::class.java
).putExtra(
"key",
"value"
)
)
In ActivityTwo.class :
var value = ""
if (intent.hasExtra("key")
value = intent.getStringExtra("key")
2: Modify button text programatically as:
btn_object.text = value
Hope this will help you
For changing the button text:
Use a static method to call from the other activity to directly modify the button caption.
Use an intent functionality, which is preferable.
Use an Interface and implement it, which is used for communicating between activities or fragment in a manner of fire and forget principle.
Now, i got you:
Your EditarTimes activity with listview:
//set setOnItemClickListener
youtListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent(EditarTimes.this, CadastroTimes.class);
//text which you want to display on the button to CadastroTimes activity
String strName = "hello button";
i.putExtra("STRING_I_NEED", strName);
}
});
In CadastroTimes activity,
under onCreate() method, get the text string as:-
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
//button in CadastroTimes activity to have that String as text
yourButton.setText(newString);
Ok, so the first step would be to take the button you want and make it a public static object (and put it at the top of the class).
public static Button button;
Then you can manipulate that using this in another class:
ClassName.button.setText("My Button");
In your case it is
CadastroTimes.salvar.setText("Alterar");
if you want to change value from that do not do not go the activity via intent you can use file to save value to file or you have multiple values the use database and access
the value oncreate to set the value of text....
In my case, I had to send an EditText value from a Dialog styled Activity, which then got retrieved from a Service.. My Example is similar to some of the above answers, which are also viable.
TimerActivity.class
public void buttonClick_timerOK(View view) {
// Identify the (EditText) for reference:
EditText editText_timerValue;
editText_timerValue = (EditText) findViewById(R.id.et_timerValue);
// Required 'if' statement (to avoid NullPointerException):
if (editText_timerValue != null) {
// Continue with Button code..
// Convert value of the (EditText) to a (String)
String string_timerValue;
string_timerValue = editText_timerValue.getText().toString();
// Declare Intent for starting the Service
Intent intent = new Intent(this, TimerService.class);
// Add Intent-Extras as data from (EditText)
intent.putExtra("TIMER_VALUE", string_timerValue);
// Start Service
startService(intent);
// Close current Activity
finish();
} else {
Toast.makeText(TimerActivity.this, "Please enter a Value!", Toast.LENGTH_LONG).show();
}
}
And then inside my Service class, I retrieved the value, and use it inside onStartCommand.
TimerService.class
// Retrieve the user-data from (EditText) in TimerActivity
intent.getStringExtra("TIMER_VALUE"); // IS THIS NEEDED, SINCE ITS ASSIGNED TO A STRING BELOW TOO?
// Assign a String value to the (EditText) value you retrieved..
String timerValue;
timerValue = intent.getStringExtra("TIMER_VALUE");
// You can also convert the String to an int, if needed.
// Now you can reference "timerValue" for the value anywhere in the class you choose.
Hopefully my contribution helps!
Happy coding!
Accessing view reference of another Activity is a bad practice. Because there is no guarantee if the reference is still around by the time you access it (considering the null reference risk).
What you need to do is to make your other Activity read values (which you want to display) from a data source (e.g. persistence storage or shared preferences), and the other Activity manipulates these values. So it appears as if it changes the value of another activity, but in reality it takes values from a data source.
Using SharedPreferences:
Note: SharedPreferences saves data in the app if you close it but it will be lost when it has been deleted.
In EditarTimes.java:
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
t = times.get(pos);
SharedPreferences.Editor editor = getSharedPreferences("DATA", MODE_PRIVATE).edit();
editor.putString("btnText", "Your desired text");
editor.apply();
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
startActivity(intent);
}
};
In CadastroTimes.java
public Button salvar;
salvar.setText(getSharedPreferences("DATA", MODE_PRIVATE).getString("btnText", ""));
//note that default value should be blank
As far as my thoughts go, I can realize that the problem is not with the code you provided as it seems to be implemented correctly. It is possible that you have saved the activityState somewhere in your actual code and because it is not implemented properly, the savedInstanceState found in the onCreate method is not null but the required information is missing or not correct. That's why newString is getting null and salvar textview is getting blank.
Here, I need to know which one is more useful to you - information from getIntent() or from savedInstanceState? The code you provided insists me to assume that savedInstanceState has got the preference.
If you prefer savedInstanceState, then you may use SharedPreferences like this to get the same value you want:
private SharedPreferences mPrefs;
private String newString;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
// try to get the value of alterarValue from preference
mPrefs = getSharedPreferences("MyData", MODE_PRIVATE);
newString = mPrefs.getString("alterarValue", "");
if (newString.equals("")){
// we have not received the value
// move forward to get it from bundle
newString = getIntent().getStringExtra("Alterar");
}
// now show it in salvar
salvar.setText(newString);
}
protected void onPause() {
super.onPause();
// you may save activity state or other info in this way
SharedPreferences.Editor ed = mPrefs.edit();
ed.putString("alterarValue", newString);
ed.commit();
}
Or if you don't need to get it from savedInstanceState, please use it:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
// try to get the value of alterarValue from bundle
String newString = getIntent().getStringExtra("Alterar");
// now show it in salvar
salvar.setText(newString);
}
That's all I know. Hope it will help. If anything goes wrong, please let me know.

How do I set intent data to current activity editText?

I'm trying to transfer two numerical inputs from one activity to another's UI but when I click the button to change intent it crashes.
I get the following in logcat: http://pastebin.com/zkWPcSNZ , which suggests a problem with the way I parsed the data to the editTexts in CalcResult.
My question is what is wrong with the way I'm trying to pass the data to the CalcResult editText.Is there an alternative method of acheiving this?
My two classes look like this for reference:
public class MainActivity extends Activity implements OnClickListener {
//variables for xml objects
EditText offsetLength,offsetDepth,ductDepth;
Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting the variables to the xml id's and setting the click listener on the calc button
offsetLength = (EditText)findViewById(R.id.offLength);
offsetDepth = (EditText)findViewById(R.id.offDepth);
ductDepth = (EditText)findViewById(R.id.ductDepth);
calculate = (Button)findViewById(R.id.calc);
calculate.setOnClickListener(this);//don't cast the listener to OnClickListener
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
String getoffsetlength = offsetLength.getText().toString();
String getoffsetdepth = offsetDepth.getText().toString();
String getductdepth = ductDepth.getText().toString();
double tri1,tri2;
double marking1,marking2;
double off1 = Double.parseDouble(getoffsetlength);
double off2 = Double.parseDouble(getoffsetdepth);
double off3 = Double.parseDouble(getductdepth)
;
marking1 = Math.pow(off1,2) + Math.pow(off2,2);
tri1 = (float)off2/(float)off1;
tri2 = (float)off3/Math.atan((float)tri1);
marking2 = (float)off3/Math.atan(tri2);
Intent myIntent = new Intent(MainActivity.this, CalcResult.class);
myIntent.putExtra("numbers", marking1);
myIntent.putExtra("numbers", marking2);
startActivity(myIntent);
} catch (NumberFormatException e) {
// TODO: handle exception
System.out.println("Must enter a numeric value!");
}
}
}
This is the activity that I'm passing the data to:
public class CalcResult extends MainActivity
{
EditText result1,result2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
result1 = (EditText)findViewById(R.id.mark1);
result2 = (EditText)findViewById(R.id.mark2);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
double mark1 = bundle.getDouble("number1");
double mark2 = bundle.getDouble("number2");
int a = Integer.valueOf(result1.getText().toString());
int b = Integer.valueOf(result2.getText().toString());
result1.setText(a + " ");
result2.setText(b + " ");
}
}
When you start your second activity, both editText are empty
So when you do :
int a = Integer.valueOf(result1.getText().toString());
int b = Integer.valueOf(result2.getText().toString());
it's equivalent to :
int a = Integer.valueOf("");
int b = Integer.valueOf("");
which throws the exception
Caused by: java.lang.NumberFormatException: Invalid int: ""
If you want to set them the values you passed through both activities, you can just do :
double mark1 = bundle.getDouble("number1");
double mark2 = bundle.getDouble("number2");
result1.setText(mark1 + " ");
result2.setText(mark2 + " ");
The error is that you are putting your extras with same key "numbers" , and you are trying to retreive them by another keys "number1" and "number2". your code should be like this :
Intent myIntent = new Intent(MainActivity.this, CalcResult.class);
myIntent.putExtra("number1", marking1);
myIntent.putExtra("number2", marking2);
and to retreive them you should use :
Intent intent = getIntent();
double mark1 = intent.getDoubleExtra("number1", 0);
double mark2 = intent.getDoubleExtra("number2", 0);
And then , set the variables on your EditTexts like this :
result1 = (EditText)findViewById(R.id.mark1);
result2 = (EditText)findViewById(R.id.mark2);
result1.setText(mark1+"");
result2.setText(mark2+"");
you are using the same name for your extras when sending the intent, try correcting them.

Categories