Call another class and getText - android

public class ustawienia extends MainActivity {
EditText kryptonim;
public String test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ustawienia);
kryptonim = (EditText) findViewById(R.id.edit_kryptonim);
test = kryptonim.getText().toString();
}
public String call_back(){
return test;
}
}
When call call_back() from another class I've got error: Unable to start activity ComponentInfo. What's wrong with that?

When you close an activity all data from it is lost, so unless both activities are runing at the same time you can't retrieve data. You could use shared prefrences instead.
// IN ORDER TO WRITE TO A FILE
SharedPreferences.Editor prefs = getSharedPreferences("PrefsName", MODE_PRIVATE).edit();
prefs.putString("test", kryptonim.getText().toString());
prefs.apply(); // use prefs.commit(); if this doesn't work
In order to read data
SharedPreferences prefsR = getSharedPreferences("PrefsName", MODE_PRIVATE); // you could also write 0 instead MODE_PRIVATE
String restoredText = prefsR.getString("test", null);
Ofcourse you need to import SharedPrefs , and put this in oncreate or wherever you want... let me now if it works :)

Related

SharedPreferences saves state between android activities but not upon restarting the app

I'm running to a really weird behavior with SharedPreferences. I'm wondering if I'm running into a synchronization issue.
It seems like the app can remember the preference changes in between activities but not when I restart the app. The state always returns back to the very first instance I created a preference. I've followed several examples, tutorials, and android documentation that all suggest similar code layout. I also watched how the preference.xml file changed while interacting with my code using the debugger and I confirmed it looked like the key value pair updated.
Could I be experiencing a synchronization issue with my emulator? I tried using both the editor.apply() method and editor.commit() method with the same results.
The only thing I've found that fixes my problem is using the editor.clear() method, but this feels a bit hacky...
note: please forgive the variable names, I'm making a pokedex...
public class SecondActivity extends AppCompatActivity {
private boolean caught;
private Set<String> pokemonCaught;
private String pokemonName;
public SharedPreferences sharedPreferences;
public static final String SHARED_PREFERENCES = "shared_preferences";
public static final String PREF_KEY = "inCaughtState";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
/*SKIPPING THE VIEW SETUP*/
/*SKIPPING BUTTON VIEW ATTRIBUTES*/
//variables required for changing button state
pokemonName = (String) nameTextView.getText();
caught = false;
//Loading in sharedPreferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
pokemonCaught = sharedPreferences.getStringSet(PREF_KEY, new HashSet<String>());
if (pokemonCaught.contains(pokemonName)) {
toggleCatch(catchButton);
}
}
public void toggleCatch (View view) {
//Editing and updating preferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (caught == true) {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = false;
pokemonCaught.remove(pokemonName);
}
else {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = true;
pokemonCaught.add(pokemonName);
}
editor.clear(); //This is my hacky solution...
editor.putStringSet(PREF_KEY, pokemonCaught);
editor.apply();
}
}
Try to use SharedPreferences this way:
To save data
SharedPreferences.Editor editor = getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("stringName", "stringValue");
editor.apply();
To retrieve data
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PREFS", MODE_PRIVATE);
String name = preferences.getString("stringName", "none"));
Note that this "none" is in case to string "stringName" be null.

How can I store values from an activity so that I can use them later?

I would like to store a few values from an Activity so that when I navigate away from the activity, they still appear there.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
Button AddButton = (Button) findViewById(R.id.AddButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText firstNumEditText = (EditText) findViewById(R.id.firstNumEditText);
EditText secondNumEditText = (EditText) findViewById(R.id.secondNumEditText);
TextView ResultTxtView = (TextView) findViewById(R.id.ResultTxtView);
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 + num2;
ResultTxtView.setText(result + "");
}
});
In this case, I only want to save the values of num1, num2 and result. I would like it so that if I navigate back to the main menu, or if I go and do some other app and come back tomorrow, that the values would still be there.
You can store these values by using SharedPreferences.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
Button AddButton = (Button) findViewById(R.id.AddButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText firstNumEditText = (EditText) findViewById(R.id.firstNumEditText);
EditText secondNumEditText = (EditText) findViewById(R.id.secondNumEditText);
TextView ResultTxtView = (TextView) findViewById(R.id.ResultTxtView);
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 + num2;
ResultTxtView.setText(result + "");
// You can store these values here
// ...
}
});
protected void onResume() {
// And read these values here and set to your ResultTxtView.
// ...
}
You can use shared preferences in your app for saving the data and for using the same data later as mentioned below:
SharedPreferences sp = getSharedPreferences("Data",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name", "Alex");
editor.putString("Email", "alex#gmail.com");
editor.commit();
And then if you want to get the same data in another activity you do this as mentioned below:
SharedPreferences sp= ActvivityA.this.getSharedPreferences("Data",Context.MODE_PRIVATE);
String name = sp.getString("Name");
String email = sp.getString("Email");
This data will be saved till you will not clear the cache of the application or you will not install a new update of the app so in this way you can use this data anywhere in the app.
In this case, I only want to save the values of num1, num2 and result. I would like it so that if I navigate back to the main menu, or if I go and do some other app and come back tomorrow, that the values would still be there.
When you need the values to be persisted across app launches, then Shared Preferences or a data store like SQLite/Room would be the way to go.
Shared Preferences : If the values stored are key value pairs and are limited in size and does not have to scale, then Shared Preference would suit your need.
SqLite : If the data that you store would scale and would become larger in time, then you need to look at a data store like SQLite where you can do Async operations.
create on class which extends Application and create variable to hold specific value and register that class in manifest
in manifest in application tag specify your application class name
public class MyApplication extends Application {
private MyApplication sInstance;
int result;
//write getter setter for result variable same for num1 and num2
#Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public static MyApplication getInstance() {
return sInstance;
}
}
in onClick set that variable value like MyApplication.getInstnce().setResult();
and in onCreate of set textview value with MyApplication.getInstance().getResult();
Use Following methods for save/retrieve string using SharedPreferences
public static int getIntPreferences(Context context,String key) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
int savedPref = sharedPreferences.getInt(key, null);
return savedPref;
}
public static void saveIntPreferences(Context context,String key, int value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
Save num1,num2 and result using saveIntPreferences when you leave 1st Activity.
After getting back on 1st Activity, you can get saved value using getIntPreferences

Roboelectric assertion fails with shared preferences android

Referring this SO question, I tried to save shared preferences, but my assertion fails.
This is my test class
#Test
public void testSharedPreferences(){
activity=actController.create().get();
loginButton=(Button)activity.findViewById(R.id.loginButton);
userName=(EditText)activity.findViewById(R.id.userName);
userPassword=(EditText)activity.findViewById(R.id.userPassword);
sharedPrefs = ShadowPreferenceManager.getDefaultSharedPreferences(Robolectric.application.getApplicationContext());
sharedPrefs.edit().putString("userName", "user1").commit();
assertThat(userName.getText().toString(),equalTo("user1"));
}
This is the code in the class under test-
public class LoginActivity extends Activity {
private EditText userName,userPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
SharedPreferences sharedPreferences =PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor=sharedPreferences.edit();
String name = sharedPreferences.getString("userName", "");
if (!"".equalsIgnoreCase(name)) {
userName.setText(name);
}
}
Assertion fails and it says expected "user1" but found "".
Your test is creating the activity first (and triggering onCreate() too early), so your changes to the SharedPrefs have no effect. Try this instead:
#Test
public void testSharedPreferences() {
// First set up the shared prefs
sharedPrefs = ShadowPreferenceManager.getDefaultSharedPreferences(Robolectric.application.getApplicationContext());
sharedPrefs.edit().putString("userName", "user1").commit();
// Create the activity - this will call onCreate()
activity=actController.create().get();
loginButton=(Button)activity.findViewById(R.id.loginButton);
userName=(EditText)activity.findViewById(R.id.userName);
userPassword=(EditText)activity.findViewById(R.id.userPassword);
// Verify text
assertThat(userName.getText().toString(),equalTo("user1"));
}

how to pass extra intent to two activities

i have an app that on the first activity asks the persons name on the second page it displays the name in a sentence i want to use the name in the third fourth or 9th activity how do i properly declare it (public?) and call it when and where ever i need it? this is my code sending it
Main
public class MainActivity extends Activity {
Button ok;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.editText);
Typeface font_a = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
name.setTypeface(font_a);
ok=(Button)findViewById(R.id.button);
Typefacefont_b=Typeface.createFromAsset(getAssets(),
"fonts/SignPaintersGothicShaded.ttf");
ok.setTypeface(font_b);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("NAMEDATA",nameStr);
startActivity(intent);
}
});
}
and this is activity 2 receiving it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
String n = this.getIntent().getStringExtra("NAMEDATA");
t.setText(n);
so please how would i reuse this?
Use SharedPreferences to save the name or whatever variable you need, then read whenever you need it. First, create global in MainActivity which will be used as preference file name:
public static final String PREFS_NAME = "MyPrefsFile";
Then, to save:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", name);
editor.commit();
to load:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String name = settings.getString("name", "John");
Once saved, the prefs are accessible for every activity.
So in your case, save the name when ok button is pressed:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", nameStr);
editor.commit();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
});
Then read it:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String n = settings.getString("name", "defaultName");
t.setText(n);
You can do similarly in every activity you need it. See docs here.
You have a number of different approaches to share data between activities. I would say which one you use depends on the ultimate source and destination of the data.
Pass through intents - This is the method you are currently using. To proceed, just keep passing the name to the next intent.
Save to SharedPreference - This method you save the information to the "preference" file of the application. This is useful if the the user is setting up a profile or other semi-fixed information.
Write it to a DB - Here you would create a a new SQLite table for user information and write new rows to it for the name, password, and other info. This has way more overhead and is really only useful if you have multiple users in the same application
Save to a singleton - In this case you create a static class with public properties that can be set. This would be least favorable all the information is lost on application close, but could be useful for temporary creation and retention across many activities. Be warned: bad programming can make singletons a nightmare
Create class extending from Application class.
Implement setter and getter inside that class like,
public class GlobalClass extends Application {
//create setters and getters here
public void setUserInfo(String userInfo) {
}
public void getUserInfo() {
return userInfo;
}
}
then you can use this from any activity like,
GlobalClass app = (GlobalClass ) getApplication();
app.getUserInfo();

How to use Shared Preferences?

I am new to android..and I'm developing an application using Json. I want to pass a string value from my main activity to another class without starting the activity class. I heard there is some way using shared preferences. I just tried.. but didn't worked..i got null point exception.. here is my code...
confirm = check.AuthenticateUser(name, passwd);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name",confirm);
editor.commit();
here is the place i want to send the value of "confirm" (string variable)
and below code shows where i want to get that preference..actually that class named "ShortList".
here is the code where i trying to get the value
public class ShortList extends Activity {
//ArrayList<HashMap<String, String>> arl;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String cargivr = preferences.getString("Name","");
please some one help me..
public static String CREDENTIALS_FILENAME = "com.myapp.credentials";
public static String PIN = "pin";
public static void writeCredentials(Context c,String pin) {
SharedPreferences credentialsPref = c.getSharedPreferences(CREDENTIALS_FILENAME, 0);
SharedPreferences.Editor editor = credentialsPref.edit();
editor.putString(PIN, pin);
editor.commit();
}
public static String readCredentials(Context c,String pin) {
SharedPreferences credentialsPref = c.getSharedPreferences(CREDENTIALS_FILENAME, 0);
SharedPreferences.Editor editor = credentialsPref.edit();
return credentialsPref.getString(PIN, "default value");
}
MainActivity.java
SharedPreferences pref = getApplicationContext().getSharedPreferences("New",Context.MODE_PRIVATE);
Editor edit = pref.edit();
edit.putString("SomeKey", "SomeValue");
edit.commit();
SecondActivity.java
SharedPreferences prefs = getApplicationContext().getSharedPreferences("New",Context.MODE_PRIVATE);
String value = prefs.getString("SomeKey","DefaultValue");
Also make sure that you have added the second activity details in your android manifest file -
<activity
android:name="com.example.projectName.SecondActivity"
android:parentActivityName="com.example.sharedpref.MainActivity">
</activity>
public class ShortList extends Activity {
//ArrayList<HashMap<String, String>> arl;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String cargivr = preferences.getString("Name","");
Here it seems you're initializing member variables.
You cannot use an Activity as a Context until onCreate() in the activity lifecycle. Member variable initialization is too early and will usually lead to NPE in getBaseContext().
Move the initialization of preferences and cargivr to onCreate() or later.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ShortList.this);
String cargivr = preferences.getString("Name","");

Categories

Resources