android SharedPreferences pass integer to next activity [duplicate] - java

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

Related

Transfer data from one screen to another [duplicate]

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));

Pass a string from first activity to last activity but running another activity before starting last activity

I'm very new in Android, if the question is repeated please avoid and send the link.
There are three activities A, B and C. Activity A gets a username which I want to get displayed in activity C, but I want to run Activity B first and then run Activity C. The problem using intent is that I have to run C first. If singleton, bundle, or parcelable is the solution can you please provide the code?
Activity A
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText nameText = findViewById(R.id.nameText);
nameText.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
String name = nameText.getText().toString();
return true;
}
});
}
Activity B
public class qPage2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q_page2);
android.os.SystemClock.sleep(500);
}
}
Activity C
public class lastPage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last_page);
}
}
It's easy than you thought. For example if you want to send a Tasif string from A to C via B.
In activity A
Intent intent = new Intent(A.this, B.class);
intent.putExtra("username", "Tasif");
startActivity(intent);
In activity B
Intent intent = new Intent(B.this, C.class);
intent.putExtras(getIntent()); // Add this line, it will copy all data in intent which starts activity B (including `username`).
startActivity(intent);
In activity C
String username = getIntent().getStringExtra("username");
Declare the String inside Activity "A" as public static and store the string in it from Activity "A" .
eg: Activity A.java
public static String first = "hello";
Then in Activity "C" call it like
Actiivity C.java
String last = A.first;
There are many options for this :
You can use intent as you mentioned
You can make a static Class and declare a static variable with type string
and access it in the C activity .
Code For first option :
For adding value to intent
Intent n = new Intent(FirstActivity.class,SecondActivity.class);
n.putExtra("name" , name);
n.startActivity();
For retrieving it :
Intent intent = getIntent();
String name = intent.getStringExtra("name");
2.Create a static class member and acess it
class static StaticClass{
static name = " ";
}
Update this variable in the first activity and retrive it in last activity
You can store that string in SharedPreferences and can access that string anywhere in your project. If you are not familiar with SharedPreferences read the documentation from this SharedPrefernces Link
A simple and clean approach is to use SharedPreferences data storage option. It is used to save a small collection of data like Key-Value pair.
Save the username in SharedPreferences as below in Activity A:
SharedPreferences sharedPref = getSharedPreferences(
getString("MyKeyPairFileName"), Context.MODE_PRIVATE);
sharedPref.edit().putString("userKey", "Your username").apply;
Read the value from any Activity(B or C or D or...Z) as below:
SharedPreferences sharedPref = getSharedPreferences(
getString("MyKeyPairFileName"), Context.MODE_PRIVATE);
String username = sharedPref.getString("userKey", null);
/*null is the default value, if value for the key is not available*/);
Be careful when using getSharedPreferences vs getPreferences from Activity. You can read more on SharedPreferences here

How to refer to a randomly generated button's elements

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 */

How do you pass a string from one activity to another? [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 9 years ago.
I'm wondering how to pass and read a string that is in one activity from another activity. I have two activities. I'll call them Activity1 and Activity2. I have a string in Activity1 called course. I want to read that string in Activity2.
I've tried doing this but the string came out empty.
public class Activity2 extends Activity1 {
I've seen people use the Intent function but I couldn't figure out how to use it.
Any suggestions? Thanks!
Pass values using intents.
In your first activity
Intent i= new Intent("com.example.secondActivity");
i.putExtra("key",mystring);
// for explicit intents
// Intent i= new Intent(ActivityName.this,SecondActivity.class);
// parameter 1 is the key
// parameter 2 is the value
// your value
startActivity(i);
In your second activity retrieve it.
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//get the value based on the key
}
To pass custom objects you can have a look at this link
http://www.technotalkative.com/android-send-object-from-one-activity-to-another-activity/
your first activity, Activity1
public class Activity1 extends Activity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
btn=(Button) findViewById(R.id.payBtn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(Activity1.this,Activity2.class);
intent.putExtra("course", "courseValue");
startActivity(intent);
}
});
}
}
Activity2
public class Activity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
String course=getIntent().getExtras().getString("course").toString();
Log.d("course",course);
}
}
Hope this will help you.
You're on the right track - you're using an intent to launch the second activity. All you have to do is add intent.putExtra("title", stringObject); where stringObject is the string you want to pass, and title is the name you want to give that object. You use that name to refer the object passed in the second activity as follows:
String s = (String)getIntent().getExtras().getSerializable("title");
From Activity 1 call something like this :
Intent intent= new Intent("path.secondActivity");
intent.putExtra("keyString",sampleString);
startActiivty(intent);
and in activity 2 try something like this :
Bundle values = getIntent().getExtras();
if (values != null) {
String keyString = values.getString("keyString");
}
In your MainActivity
Intent i= new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("key",yourstring);
startActiivty(i);
In your second activity onCreate()
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
}
Try this
public class Activity2 extends Activity1

Make my class take an argument

Well I have a main Screen with 5 buttons. Each time a press a button I want to go a new screen. So far I have other 5 classes (each for each screen) and 5 xmls. But Iam sure that there will be a better way beacuse this screen and the xmls are the same, and what I want to do is change some texts and some data I fetch from a database. I am sure that I can ony another class and only one xml and then pass the values that I want as arguments. (Imagine that in its final state my app must have 15 buttons, so I think it is too mych waste of space and unnecessary to have 15 .java files and 15 xml files that look the same and only some values of images and textviews change). My code for main activity is:
public class MyActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
main2Theme();}
private void main2Theme() {
setContentView(R.layout.main_new);
Button Button100 = (Button)findViewById(R.id.Button100);
Button113.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(this, OtherScreenName.class);
startActivity(i);
}
}); //and so on for 15 buttons
My OtherScreenName.class is:
public class OtherScreenName extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Theme();
}
#SuppressWarnings("null")
private void Theme() {
Log.d("SnowReportApp","Do first thing");
setContentView(R.layout.otherscreenname); //THIS CHANGES IN EVERY CLASS DEPENDING ON THE ID OF THE BUTTON
String result = "";
InputStream is = null;
StringBuilder sb=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();//() before
nameValuePairs.add(new BasicNameValuePair("ski_id","OtherScreenName"));
TextView text1 = (TextView) findViewById(R.id.otherscreenname_1);
//THESE 2 CHANGE DEPERNDING ON THE BUTTON PRESSED
//perform action.....
//AND ALSO HERE I NEED THE ID OF THE BUTTON
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(OtherScreenName.this,MyActivity.class);
startActivity(i);
}
});
Can anyone suggest how to give arguments to my class and what it should be the type of them?
If I understand your question correctly, you want to pass arguments to the activity. Normally it would be done through the class constructor, however, activities can't have user defined constructors, only the default one; they can be instantiated only indirectly via intent creation. If you need to pass data between activities, do it by putting extras to bundles, for example:
bundle.putInt("intName",intValue);
then you can extract the data from bundle by
int intValue = bundle.getInt("intName");
Put extras before starting the activity:
Intent i = new Intent(this, YourActivity.class);
Bundle b = new Bundle();
b.putInt("intName",intValue);
i.putExtras(b);
startActivity(i);
and then read the extras in the onCreate method:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
int intValue;
if (b != null)
{
intValue= b.getInt("intName");
}
}
The same way you can pass other data types as String boolean etc. If this is not sufficient and you need to pass some more complex data, then use Parcelable interface.
You can pass parameters with an Intent by adding extra's to it, something like the following:
Intent i = new Intent(this, MyActivity.class);
i.putExtra("paramName", "value");
startActivity(i);
In your activity you can use the getIntent() method to retrieve the Intent and extract your parameter(s) from it:
Intent i = getIntent();
Bundle extras = i.getExtras();
String param = extras.getString("paramName", "default value");
You can place all the different text and data in your Intent, but you can also decide based on the value of an Intent parameter which data and text to retrieve. If it is a lot of data or text you are probably better off using the second approach.
If you want to pass object instead of simple data, you must use parcelable objects as it´s explained in: [http://developer.android.com/reference/android/os/Parcelable.html][1]
Reading and writing with parcelable objects is very similar to the way with a simple data
Intent intent = new Intent(this ,newthing.class);
Bundle b = new Bundle();
b.putParcelable("results", listOfResults);
intent.putExtras(b);
startActivityForResult(intent,0);
Intent i = getIntent();
Bundle extras = i.getExtras();
String param = extras.getParcelable("results");

Categories

Resources