I'm new to Android Studio but I have programmed Java before.
I need to sum two numbers in one activity and then print the result in a new activity, the compiler it's ok but the app force close.
Where is my fault?
Here's my source:
public class MainActivity extends AppCompatActivity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OpenActivity2();
}
});
}
public void SumAB(TextView tva, TextView tvb, TextView tvsomma) {
double a, b, somma;
a = Double.parseDouble(tva.getText().toString());
b = Double.parseDouble(tvb.getText().toString());
somma = a + b;
tvsomma.setText(String.valueOf(somma));
}
public void OpenActivity2() {
TextView result = findViewById(R.id.textView4);
TextView var1 = findViewById(R.id.textView);
TextView var2 = findViewById(R.id.textView3);
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
SumAB(var1,var2,result);
}
}
You are calling SumAB() after you launch Activity2 with startActivity(intent); so when the tvsomma.setText() is executed it expects to find a tvsomma view but it's a part of the first activity which should be in background now.
I need to sum two numbers in one activity and then print the result in a new activity
You should remove SumAB() method and do the below behavior
Here your are trying to display the result at the same activity; if you want to display the result on the second activity, you've to send this sum using
double a, b, somma;
a = Double.parseDouble(tva.getText().toString());
b = Double.parseDouble(tvb.getText().toString());
somma = a + b;
intent.putExtra("SUM", somma);
startActivity(intent);
And receive this result at Activity2 using:
int somma = getIntet().getIntExtra("SUM", 0); // 0 is the default value
Then set this value to some TextView at Activity2 with
myTextView.setText(String.valueOf(somma));
You need to make changes in your code.
Create a separate java file for another activity.
setContentView(R.layout.activity_main) method inside onCreate() function in the
above mentioned Java file is used to set layout for activity one.
To set view for another activity, you need to create another java file say "sum.java". Here you need to mention again setContentView(R.layout.activity2_main) method inside onCreate() function. activity2_main represents the second activity where you want to print value of sum.
Instantiate all the UI widgets in a java files respectively.
In the java file, instantiate TextView var1, TextView var2 and button.
In the second java file, instantiate TextView result.
The aim here is, all the UI widgets that you are using in first activity should me
mentioned in first file and correspondingly second file should have widgets related to
second activity.
You also need to perform type casting while instantiating the variables like:
TextView var1 = (TextView)findViewById(R.id.textView); [Down casting is performed here].
You need to use following two functions if you want to send data from one activity to another.
putExtra() method is use for send the data, data in key value pair key is variable
name and value can be Int, String, Float etc.
getStringExtra() method is for get the data(key) which is send by above method.
according the data type of value there are other methods like getIntExtra(),
getFloatExtra()
Check out this link to get more insight on this topic- https://www.geeksforgeeks.org/android-how-to-send-data-from-one-activity-to-second-activity/
Related
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
How to pass an object from one activity to another on Android
(35 answers)
Closed 4 years ago.
I am currently working on a project for my programming class, it is a d&d character creator I've decided to do for my final project. I am nearly finished with it but have run into one problem. I want to take the user's data from a screen where they create a character and store it into a screen where they can view their created characters, but I am not sure how to do this. This is the code from the create a character screen:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_char_screen);
Button btnSave = (Button)findViewById(R.id.btnSaveChar);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkData())
startActivity(new Intent(NewCharScreen.this, HomeScreen.class));
}
});
Button btnEx = (Button)findViewById(R.id.btnExplanation);
btnEx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(NewCharScreen.this, ExplanationScreen.class));
}
});
}
private boolean checkData(){
final EditText charName = (EditText) findViewById(R.id.txtNameInput);
if (charName.getText().toString().isEmpty()){
charName.setError("Enter character name");
charName.requestFocus();
return false;
}
return true;
}
}
If there is a need for the rest of my code or the project itself here is a link to a repository on GitHub:
https://github.com/cbetlinski98/MAD105-final_project
If you want to pass data from one activity to another one, you should pass it inside the Intent object, so intead of creating it inside StartActivity you can create it outside as a normal object, and use putExtra() to put data inside it.
Intent intent = new Intent(getBaseContext(), DestinationActivity.class);
intent.putExtra("OBJECT_PARAM_NAME", your_object);
startActivity(intent);
To recover data on the other activity you can use
String sessionId= getIntent().getStringExtra("OBJECT_PARAM_NAME");
Pass basic types
If you need to pass basic objects like int, float, strings, you can always pass them with putExtra() but to take them in the destination activity there are relative methods like getStringExtra() or getIntExtra() and many others.
Pass your class
If your user is a class defined by you, you can implement Serializable in that class, put it inside the intent with putExtra() and recover it from the other activity with getIntent().getSerializableExtra("OBJECT_PARAM_NAME") and then just cast it to your class before putting it inside an object
In order to pass information across intents:
Intent i = new Intent(this, Character.class);
myIntent.putExtra("paramKey","paramValue1");
startActivity(i);
Then in your activity to obtain the parameters:
Intent i2 = getIntent();
i2.getStringExtra("paramKey");
startActivity(new Intent(CurrentActivity.this, AnotherActivity.class).putExtra(KEY, DATA));
I need to randomly generate a button and then grab elements from it from the activity that the button opens. Specifically the universal ID of a "character" that I have specified in PersistentData. (That whole class works fine, though. The problem is between this activity and the next.) The child activity has multiple activities that can call it. (There are several activities with lists made from different characters from a pool, and each list has these buttons that are shown below, which all point to the same activity that loads information from PersistentData based on the data that its supposed to pull from said button.) The following 1 block of code is in the onCreate method for this activity. (Automatically generated, I just added this in after I called the layouts from the XML file)
for (fID = 0; fID < PersistentData.fName.size(); fID++) {
if (PersistentData.fName.get(fID) != null) {
Button[] Btn = new Button[PersistentData.fName.size()];
Btn[fID].setHeight(200);
Btn[fID].setWidth(200);
Btn[fID].setTextSize(40);
Btn[fID].setText(PersistentData.fName.get(fID));
Btn[fID].setTag(fID);
Layout.addView(Btn[fID]);
Btn[fID].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int btnID = fID;
gotoActivity(v);
}
});
} else continue;
}
Here is gotoActivity(). (In the class, not onCreate)
public void gotoActivity(View view) {
Intent intent = new Intent(this, TargetActivity.class);
startActivity(intent);
intent.putExtra("btnClicked", /*IDK WHAT TO PUT RIGHT HERE*/);
}
I have put several things there, actually. Mostly, they have been various ways of declaring a variable on the creation of the button.
Here's the TargetActivity.class
public class Fighter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fighter);
Intent intent = getIntent();
Bundle bundle =
intent.getExtras(); //line ***
**
TextView viewName = (TextView) findViewById(R.id.fighterName);
viewName.setText(PersistentData.fName.get(fID));
}
}
What should I put in the other class that I should get here**? (fID) is the thing that I'm trying to get. I have tried putting and getting fID using the methods as described in the Create an Activity page from Android and it continued to give me a NullPointerException at line *** (I split the line to be precise.)
Any help is appreciated. I would not be surprised if there is a better way to do this, requiring me to scrap all my work and restart. I would prefer not to, though lol. I will be checking this post periodically throughout the day, so if you have any questions or require more detail, just post or message me. Thank you beforehand.
I think the reason you got a NullPointerException because you started the activity before persing the extra.
In the gotoActiviy, make sure the extra(s) method are called before you start the activity. that is
public void gotoActivity(View view) {
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("btnClicked", "Strings");
startActivity(intent);
}
As you can see, a string was the extra, you can put any variable type as the extra just make sure at the activity being called, the same variable type gets the extra.
as an example
String getValue = getIntent().getExtras().getString("btnClicked");
Int getValue = getIntent().getExtras().getInt("btnClicked");
/** If integer was the value activity extra */
I hope if someone help me in this ,
in my projet I am trying to open another avtivity used voice command Ex, say "one " it should compare if the string is equal to what I? have it should switch to another activity or external activity such as Phone call, Camera. What I did here, I store the recognized ward in Edittext and store it in string and compare it . my 2 projects counted on how to do this
Inside onCreate:
final Button btntx = (Button)findViewById(R.id.btn1);
final EditText edittxt1 = (EditText)findViewById(R.id.edttxt);
btntx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent (Intent.ACTION_DIAL); // sow the Dial window
intent.setData(Uri.parse("tel:"));
startActivity(intent);
);
}
////////////////////////// outside the onCreate //////// Function after I get the result from the Speech recognizer and call this function to see if the what it said is equal to my keyword . SO i need to call the button to open that activity
String gwdata= edtxt.getText().toString(); // data from EditText
if (gwdata.equals("One"))
{
Toast.makeText(getBaseContext(),"They are equal", Toast.LENGTH_SHORT).show();
// Here Do someting to go to another activity
}
Thnks guys in advance .
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 7 years ago.
how am i going to pass an integer value from the textview to the next activity?
currently im using string as my sharedpreferences and everytime im changing it to int my app force close.
here's my code on mainactivity
int scoreText=50;
public static final String PREFS_COIN= "MyPreferenceFile";
protected void onCreate(Bundle savedInstanceState) {
public void checkAnswer()
{ String answer=answerText.getText().toString();
if(isCorrect(answer))
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("What are you a GENIUS?!");
builder.setMessage("Nice one, Genius! You have P10!");
builder.setIcon(android.R.drawable.btn_star);
builder.setPositiveButton("View Trivia",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
scoreText+=10;
scoreNew=scoreText;
scoreTxt.setText(""+ scoreNew);
SharedPreferences settings2=getSharedPreferences(PREFS_COIN, 0);
SharedPreferences.Editor editor2=settings2.edit();
editor2.putString("coins", scoreTxt.getText().toString());
editor2.commit();
Intent intent=new Intent(getApplicationContext(), Luzon1Trivia.class);
startActivity(intent);
overridePendingTransition(R.animator.transition_fade_in, R.animator.transition_fade_out);
//startActivity(new Intent(Luzon1.this, Luzon2.class));
;} });
AlertDialog alert = builder.create();
alert.show(); // Show Alert Dialog
scoreTxt.setVisibility(View.GONE);
//disable all the buttons and textview
answerText.setEnabled(false);
answerButton.setClickable(false);
}
}
everytime the user guessed the correct answer, a +10 coin will be given. the problem is, in the second activity i cannot add/subtract the sharedpreference value since its declared as string. what happens is "60 +10" appears in the textview
here's my code in activity 2
public static final String PREFS_COIN= "MyPreferenceFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.luzon2);
scoreTxt = (TextView)findViewById(R.id.score);
SharedPreferences settings2=getSharedPreferences(PREFS_COIN, 0);
scoreTxt.setText(settings2.getString("coins", ""));
You shouldn't use Shared Preferences to pass information between activities, Shared Preferences is inteded to be used to store persistent information when the Application is destroyed.
To pass information between activities you should use an Intent (the same Intent that is used to start the "destiny" activity)
Intent newActivityIntent = new Intent(originActivity.this, destinyActivity.class);
newActivityIntent.putExtra(KEY_STRING, integerValue);
this.startActivity(newActivityIntent);//Assuming you're starting an activity from another one
Edit: This has been also answered here and here. I would recommend you to search before posting a question.
You have to parse the string and get a float/integer value.
int myNewInt = Integer.parseInt("theString");
in your case you have to do :
int myNewInt = Integer.parseInt(settings2.getString("coins", ""));
And I think you need to set the default value as 0 in your
settings2.getString("coins", "0")
Just use a static variable to hold this. It's much easier to implement since all you have to do is call it instead of passing it around to other intents like a mad man.
public static int coins;
To call it use your class instance name:
MyClass.coins;
So to add:
MyClass.coins+=10;
scoreTxt.setText(Integer.toString(MyClass.coins));
MyClass is your class. If your class is called MainActivity then it will be that (MainActivity).
.coins is the variable inside that class, your just making a reference to that variable.
The nice thing about static is using it as a learning tool. It's a great way to explore instances and references.
Or you can add all of this to every activity, and don't forget about handling device rotations:
Intent i = new Intent(getApplicationContext(), MyClass.class);
i.putExtra("coins","value");
startActivity(i);
To retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
coins = Integer.parseInt(extras.getString("coins"));
}
To set:
coins+=10;
scoreTxt.setText(coins);
Device rotation: Passing Extras and screen rotation
I want to save some variables after exiting activity which are set during the lifetime of my android activity and show them when I launch activity again but I don't seem to manage to get things working. Here's how I do it:
I created an integer variable "test":
public class MainActivity extends Activity {
int test = 1;
Then I write a method to change this varibale's value by pressing a button:
public void changeValueTest(View view) {
this.test = 2;
}
Then I use onSaveInstanceState() method to save the changed value:
static final String TEST = "test variable";
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt(TEST, this.test);
super.onSaveInstanceState(savedInstanceState);
}
Then in onCreate() method I put this code to get and show the changed "test" value:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
this.test = savedInstanceState.getInt(TEST);
TextView textView1 = (TextView)findViewById(R.id.textView1);
textView1.setText("Current test value is: " + test);
}
}
So I open the application, press the button to change the "test" value from 1 to 2, then exit the application, wait until it's properly removed from memory (when Application Manager doesn't show it in "Cached processes" window), start the application again and textView1 view shows 1 instead of 2. What am I doing wrong? Please help! Thanks!
What am I doing wrong?
Nothing. Instance state does not cover the scenario that you are describing.
Mostly, instance state is used in configuration changes (e.g., screen rotation). Secondarily, instance state is used if the user leaves your app by means other than "exit" (by which I assume you mean BACK) and returns to you via means like the recent-tasks list.
As documented in Developer.android , Saved instance only saves your Activity state, It will not save your variable as you wanted,
I would suggest you to use SharedPreference instead.