Save LinearLayout with multiple TextView. Android - java

I have method. They add a new number (with different colors and gravity), each time you press the button. After some clicks i have LinearLayout with multiple TextView. And i dont understand, how to save it. After closing the application, it opens with a blank layout. But i need to save previous TextView's.
public void someText(String message) {
TextView message = new TextView(MainActivity.this);
message.setText(message);
message.setBackgroundResource(R.drawable.textsmallest);
message.setTextColor(getResources().getColor(R.color.black));
message.setGravity(Gravity.START);
messageLayout.addView(message);
(I am really sorry, english is not my native language.)

You can use SharedPreferences save message or other value to xml.
Link this:
Context ctx = MainActivity.this;
SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("STRING_KEY", "string");
editor.putInt("INT_KEY", 0);
editor.putBoolean("BOOLEAN_KEY", true);
editor.commit();

Related

SharedPreferences If/Else Statement does not work correctly when I force close app

Summary of problem: When I force close the app by opening task window and swiping it closed my if/else statement is not working properly. I have the Name Selection Activity as the Default Launcher Activity. The name selection Activity should only pop up if there are no Shared Prefs, meaning the user has not selected a name yet from the spinner. But even after the user has selected a name and it is stored in Share Prefs, when I force close the app I still get returned to the name selection activity
What I have tried I have tried if (stringNamePackage.equals("")) and if (stringNamePackage == "") and if (NAME.equals("")) and if (NAME == "") At first I thought it was because maybe my Shared Prefs was not saving the name correctly but it is not that, the name still appears correctly when I force close it. But when I try to add the if/else statment it always just sends me back to the name selection activity regardless if I have a name saved in Shared Prefs or not. I have spent 4 hours trying to get this to work and I am at my wits end. I also spent hours looking at different stack articles of how to save and retrieve Shared Pref data. I even tried how to check the SharedPreferences string is empty or null *android and it is still not working.
NameSelectionActivity
public class NameSelection extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner nameSpinner;
String stringNamePackage;
Button bSaveSelection;
Context context;
public ArrayAdapter<CharSequence> adapter;
public static String SHARED_PREFS = "sharedPrefs";
public static String NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_selection);
context = this;
nameSpinner = findViewById(R.id.horizonNameSpinner);
stringNamePackage = "";
//Create the list to populate the spinner
List<String> nameList = new ArrayList<>();
nameList.add("01");
nameList.add("02");
nameList.add("03");
//Array Adapter for creating list
//adapter = ArrayAdapter.createFromResource(this, R.array., android.R.layout.simple_spinner_item);
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, nameList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
nameSpinner.setAdapter(adapter);
nameSpinner.setOnItemSelectedListener(this);
//If User has not selected name, start this activity to allow user to pick Name, else, send user to Main Activity
//else start MainActivity
if (stringNamePackage .equals("")) {
Toast.makeText(this, "Welcome, please select Name", Toast.LENGTH_LONG).show();
} else {
Intent sendToMainActIntent = new Intent(this, MainActivity.class);
startActivity(sendToMainActIntent);
}
//Save Selection Button Code
bSaveSelection = findViewById(R.id.bSaveSelection);
bSaveSelection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), MainActivity.class);
//Saves name to SharedPrefs
saveName();
//Sends user to MainActivity
startActivity(myIntent);
finish();
}
});
}
//Stores name selected in SharedPreferences
public void saveName() {
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = app_preferences.edit();
editor.clear();
//Stores selection in stringNamePackage
editor.putString(NAME, stringNamePackage );
editor.commit();
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//Put user selection into String text
String text = adapterView.getItemAtPosition(i).toString();
stringNamePackage = text;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
Main Activity
The purpose of this activity case is to send the user back to the name Selection screen when they hit the "Test" button which will erase the shared prefs and hence, trigger the if/else statement and making the user pick a name. This is how I get and set the Name in Main Activity:
in onCreate
Getting name
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(context);
nameSharedPref = app_preferences.getString(NAME, "");
name.setText(nameSharedPref);
Clearing Name
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = mPrefs.edit();
editor.clear();
editor.commit();
finish();
What I expect: I expect the user to have to pick a name the first time they boot up the app. Then, every time they open the app an if/else statement will check if the user has a name or not in Shared Prefs. If they have a name they will go directly to the Main Activity. If they don't then they will go back to the Name Selection Activity.
To get data and store data to your SharedPreferences you use this:
SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
PreferenceManager.getDefaultSharedPreferences(context) is used to build "Settings" screens or similar, the first one you use it to store/retrieve arbitrary data not necessarily binded to UI.
Even more if you want to organize your SharedPreferences you could append to getPackageName() different keys like:
getSharedPreferences(getPackageName() + ".booleans", Context.MODE_PRIVATE);
getSharedPreferences(getPackageName() + ".flags", Context.MODE_PRIVATE);
getSharedPreferences(getPackageName() + ".keys", Context.MODE_PRIVATE);
each one of them is different file that stores shared preferences, you can ommit the prepending dot ., but for naming consistency it'll be better to keep it, there is no really need for the extra keys, but if you have some sort of OCD, that might be "relaxing" ;-).
Then you can use your Android Studio's Device Explorer to browse the shared preferences, they are located under "data/data/your.package.name/shared_prefs"

Using a combination of SQLite and SharedPreferences

I have ran into a problem. So I am trying to get data from my SQLite database based on the primary key and then I will display the row of data in separate textviews on another activity. Now, I have this working using Intents, but the problem is that I do not want to use "startactivity(intent)" for example as I do not want to go to the activity, I just want to send the data.
So, in context, I have 3 activities. the first activity the user fills in the information and click "verify" button(which saves to the db). this brings them to the second activity which will have an "Information" button on it and when this button is clicked on the next activity this is where I want to display the data I have retrieved from the database.
I have read and tried multiple posts, but does anyone know what the best option is for me to use? I am currently trying to use a combination of SQLite and SharedPreferences.
Code for activity 1 to get and save the data:
Button Progress1 = (Button) findViewById(R.id.progressBar);
Progress1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
res = myDb.getProgressBar1(); //gets the data from the database
if (res.moveToFirst()) {
String LTget = res.getString(res.getColumnIndex("LINETYPE"));
String PT = res.getString(res.getColumnIndex("PACKAGETYPE"));
String QTY = res.getString(res.getColumnIndex("QUANTITY"));
String DUR = res.getString(res.getColumnIndex("DURATION"));
String ST = res.getString(res.getColumnIndex("STARTTIME"));
String ET = res.getString(res.getColumnIndex("ENDTIME"));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(LTkey, LTget);
editor.putString(PTkey, PT);
editor.putString(qtykey,QTY);
editor.putString(durkey, DUR);
editor.putString(STkey, ST);
editor.putString(ETkey, ET);
editor.commit();
Intent intent = new Intent(Dashboard.this, Actforfragmentname.class); //takes me to the second activity
startActivity(intent);
Code to retrieve data: (unsure about getting from sharedpref so tried one line)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verify_line);
myDb = new DatabaseHelper(this);
sqLiteDatabase = myDb.getReadableDatabase();
TextView LTTextView = (TextView) findViewById(R.id.textViewspinner1);
TextView PTTextView = (TextView) findViewById(R.id.textViewspinner2);
TextView QTYTextView = (TextView) findViewById(R.id.textViewQuantity);
TextView DURTextView = (TextView) findViewById(R.id.textViewDuration);
TextView STTextView = (TextView) findViewById(R.id.textViewStartTime);
TextView ETTextView = (TextView) findViewById(R.id.textViewendtime);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String LT =(sharedPreferences.getString(LTkey, LTget));
LTTextView.setText(LT);
PTTextView.setText(PT);
QTYTextView.setText(QTY);
DURTextView.setText(DUR);
STTextView.setText(ST);
ETTextView.setText(ET);
}
Can anyone help me out??
Thanks
You should use either Shared Preferences or SQLite database, the first one if you have a small amount of datas. The second one if it is bigger.
So You should push informations in database on button click in Activity 1, and retrieve them in Activity 3.
I got it working by using the method that I was trying out and that was using both SQLite and Shared Preferences together. I had to change the line of code that I was getting the sharedpreferences so to retrieve the data I know have:
SharedPreferences sharedPreferences = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
String LT = sharedPreferences.getString(LTkey, null);
String PT = sharedPreferences.getString(PTkey, null);
String QTY = sharedPreferences.getString(qtykey, null);
String DUR = sharedPreferences.getString(durkey, null);
String ST = sharedPreferences.getString(STkey, null);
String ET = sharedPreferences.getString(ETkey, null);

Saving changed Activity background colour on button click

I have this code which allows me to change the background colour of my activity and I call this on a button click.
View someView = findViewById(R.id.mainLayout);
View root = someView.getRootView();
root.setBackgroundColor(0xFF00FF00);
How can I save the background colour so that it stays changed whenever the app is restarted.
If you need to persist this setting across multiple starts by the user use SharedPreferences as described here:
http://developer.android.com/training/basics/data-storage/shared-preferences.html
If you only want to keep this setting when re-created by the system because of orientation changes for example, use onSaveInstanceState() and check for a Bundle in onCreate() as described here:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
Save to SharedPref.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(KEY, Value);
editor.commit();
Read from SharedPref.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int i = sharedPref.getInt(KEY, defaultValue);
Set Flag in sharedPreferences by
Editor editor = sharedpreferences.edit();
editor.putString(Flag, "Y");
And while loading the screen in Oncreate check for the flag by
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Flag))
{
name.setText(sharedpreferences.getString(Flag, ""));
}

SharedPreferences with OnCreate

I'm trying to achieve a goal which is adding some kind of wizard like this:
App launches for the first time > User follows wizard > Final wizard step saves some data into the SharedPreferences and continues to the activity that the user choosed > App Quits > App Relaunches > App shows activity that the user choose via the wizard data in SharedPreferences.
I know I can save data into the SharedPreferences space but how should I achieve this.
The user gets to see a view via an Android:OnClick action.
My App only has 1 main java class with different view actions like this:
public void myapp_confirmsetup(View view) {
setContentView(R.layout.activity_my_app_confirmsetup);
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("MyApp", "app_off").commit();
}
I think that from now on I only have to load the string with the OnCreate method but I'm unsure how I can do that.
Can someone push me into the right direction?
use this to store the string...
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("Stringval", "xxxxxxx");
editor.commit();
to get the value from SharedPreference use below code:-
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref2.getString("Stringval", null);
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref1.getString("Stringval", null);
if(str1.equals("app_off")){
//do something
}else(str1.equals("app_on")){
//do something else
}

how to persist data in editText using Shared Preferences in android

I have simple editText in which user enters number or string.
I want to persist that number or string when user again enters the app.
1.first save this into preference like this
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString(MY_NAME, edittext.getText().toString());
prefsEditor.putString(MY_WALLPAPER, "f664.PNG");
prefsEditor.commit();
2.Now second time you will get through whenever you get use this
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String prefName = myPrefs.getString(MY_NAME, 0);
String wallPaper = myPrefs.getString(MY_WALLPAPER, null);
It looks like you could do something similar to this: Counting Chars in EditText Changed Listener
Then, once you have detected that the text has changed, you can save it to your SharedPreferences.
Alternatively, if you only want to persist when the user leaves/enters the app, then you could just override the onPause() method of your Activity to save to your SharedPreferences. Just use <EditText>.getText() to get the String entered and then save that. Override onResume() and then use <EditText>.setText(<String from SharedPreference>) to restore it upon entering your app.
I'm assuming you know how to use SharedPreferences, but let me know if you don't.
This code will persist the data when the user removes focus from the EditText Box using the OnFocusChangeListener;
EditText userInput = (EditText)findViewById(R.id.ID_HERE);
SharedPreferences pref = this.getPreferences(this.MODE_PRIVATE);
String data_key = "data";
View.OnFocusChangeListener persistData = new View.OnFocusChangeListener(){
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
EditText e = (EditText)v;
SharedPreferences.Editor edit = pref.edit();
edit.putString(data_key,e.getText().toString());
edit.commit();
}
}
};
userInput.setOnFocusChangeListener(persistData);

Categories

Resources