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);
Related
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"
Hello everyone i trying a create small application. This application will keep max 3 users on it. I'm using a Sharedpreferencesfor save data. But i can't save multiple users i don't have any idea how can i do this. After creating users i want to swap between them and i don't using password for users so system will always can changeable between users.
There is my MainActivity.
public class MainActivity extends AppCompatActivity {
EditText nameText;
EditText dateText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameText = (EditText) findViewById(R.id.nameText);
dateText = (EditText) findViewById(R.id.dateText);
}
public void saveInfo(View view) {
SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username",nameText.getText().toString());
editor.putString("date",dateText.getText().toString());
editor.apply();
}
}
Thanks for your advice.
How about using a number in array to achieve this? probably something like this:
public void saveInfo(View view,User[] userList)
{
SharedPreferences sharedPref = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
for (int i = 0, i < userList.count){
User user = userList[i]
editor.putString("username-"+i,user.username);
editor.putString("date-"+i,user.date);
editor.apply();
}
}
With this, you can save three users and then call them from the sharedpreferences with username-(number of the user)
so have you tried to set different name for the sharedPreference database for each user?
public void saveInfo(View view,User[] userList)
{
for (int i = 0, i < userList.count){
User user = userList[i];
// I am creating a new shared prefence for each user!
// by their username.
SharedPreferences sharedPref = getSharedPreferences("userInfo_"+user.username.trim(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username",user.username);
editor.putString("date",user.date);
editor.apply();
}
}
After that, to get data for a specific user, you just need their username:
SharedPreferences sharedPref = getSharedPreferences("userInfo_"+user.username.trim(), Context.MODE_PRIVATE);
String userDate = sharedPref.getString("date", "unknown");
I think you should create your own Class that will hold in fields data that you will need. Also, I suggest you to create an List object instead of using array to have more comfortable options like List.size():
UserData userData = new UserData(View view, List<User> users);
Then hold it in Map with your custom unique key to easy get UserData in various usage needs:
private Map<String, UserData> userDataMap = new HashMap<>();
I'm trying to make a pretty simple app to help my girlfriend feel safer.
Im really bad at this, and a little help would go a long way. I've been trying to work with intents, and I really feel as if I'm super close to the solution at hand, I just need a little help.
So, the opening page is supposed to wait until you have data in your shared Preferences and then it will act on it.
The second page is supposed to take some data from EditTexts and store it in your intent. For some reason though, my data is not being stored, and when I pull something from the intent it is "".
CLASS 1:
public void ActivateAlarm(View view){
Bundle myBundle = getIntent().getExtras();
if(myBundle == null){
Log.i("The bundle is empty!", "Smashing success!");
}
else{
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
String NumberToCall = sharedPreferences.getString("CallNumber", "");
String TextOne = sharedPreferences.getString("1Text", "");
String TextTwo = sharedPreferences.getString("2Text", "");
String TextThree = sharedPreferences.getString("3Text", "");
Button myButton = (Button) findViewById(R.id.button);
myButton.setText(TextOne);
Log.i("MY NUMBER TO CALL", NumberToCall);
/*Take in the data from the settings. Check it for consistency.
1)Are the numbers empty?
2)Is the number 911 or a 7 digit number?
3)Do they have a passcode?
4)Is the number real? No philisophical BS
*/
}
}
CLASS 2:
public void GoToAlarm(View view){
EditText NumberToCall = (EditText) findViewById(R.id.callNumber);
EditText text1 = (EditText) findViewById(R.id.textNumOne);
EditText text2 = (EditText) findViewById(R.id.textNumTwo);
EditText text3 = (EditText) findViewById(R.id.textNumThree);
Intent intent = new Intent(this, AlarmActive.class);
intent.putExtra("callNumber", NumberToCall.getText().toString());
intent.putExtra("1Text", text1.getText().toString());
intent.putExtra("2Text", text2.getText().toString());
intent.putExtra("3Text", text3.getText().toString());
startActivity(intent);
}
I think the problem is coming from a bit of a mix-up between Intents and SharedPreferences.
An Intent is a way to pass data from one activity to another. You're passing data correctly in Class 2, but you're not retrieving it in Class 1. Here's how you can do that:
String NumberToCall = intent.getStringExtra("CallNumber");
String TextOne = intent.getStringExtra("1Text");
String TextTwo = intent.getStringExtra("2Text");
String TextThree = intent.getStringExtra("3Text");
SharedPreferences are a way to save user data. If you want to save data in addition to passing it between activities, you'll need to add it to SharedPreferences with the following code:
SharedPreferences preferences = this.getSharedPreferences("com.example.jackson.distressalarm", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("callNumber", NumberToCall.getText().toString());
editor.putString("1Text", text1.getText().toString());
editor.putString("2Text", text2.getText().toString());
editor.putString("3Text", text3.getText().toString());
editor.apply();
You can retrieve the values with the code you were using in Class 1.
So my question might have been asked many times but i couldnt find an answer anywhere on the internet to it .
. What i want to do is store a textview using sharedprefeences .
In my first class (xp) i,m sending the textview to another class (feedback)
Now the feedback is reciving the textview with no single problem , but never saves it. How can i store that textview in the (feedback) class even after closing the app ??
Here's the class which is intenting the textview
public class Xp extends Activity {
Button accept;
TextView textV;
TextView xbnum;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.xp);
accept = (Button) findViewById(R.id.accept);
textV = (TextView) findViewById(R.id.textV);
xbnum = (TextView) findViewById(R.id.xpnum);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value1 = extras.getString("intent_xp");
final String value = extras.getString("intent_extra");
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putString(PREFS_NAME, value);
edit.putString(PREFS_NAME,value1);
textV.setText(value);
xbnum.setText(value1);
edit.commit();
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(Xp.this, feedback.class);
i.putExtra("intent_extra", textV.getText().toString());
startActivity(i);
finish();
}
});
}
}
}
And here is the class which will recive the intent and save the textview (As supposed )
public class feedback extends Activity {
TextView test1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feedback);
test1 = (TextView) findViewById(R.id.test1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("intent_extra");
SharedPreferences settings = getSharedPreferences("intent_pref", 0);
SharedPreferences.Editor edit = settings.edit();
edit.putString("intent_pref",value);
test1.setText(value);
edit.apply();
}
}
}
The class is reciving the text , and everything is okay . Only when i close the app and open it , everything is cleared out ..
May be I'm wrong but it seems that you missunderstood how shared preferences works.
If you want to store several values in a preferences file an access it in others classes you have to create one instance of a SharedPreferences.
In your case it means create in both "feedback" and "Xp" a SharedPreferences instance like this :
SharedPreferences settings = getSharedPreferences("MyPrefsFile", SharedPreferences.MODE_PRIVATE);
and then use this instance to store your datas with an editor.
Be careful if you can't store several value for the same key.
You can also store your value in several files as you are actually doing. But if you want to set your textview with the value of your preferences file you have to get it with the getString("key_of_your_value") method on your shared preferences instance.
I need the user to choose a restaurant, got a pretty large list with different selections.
I then need to save that choice, preferably in something like sharedPreferences. And use it in another activity to display some data from an excel document.
currently my code looks like this:
in onCreate:
resturantSpinner = (Spinner) findViewById(R.id.resturantSpinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.resturant_arrays, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
resturantSpinner.setAdapter(adapter);
onItemSelected:
public void onItemSelected(View view) {
int userChoice = resturantSpinner.getSelectedItemPosition();
SharedPreferences sharedPref = getSharedPreferences("resturantFile",0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("userChoiceSpinner", userChoice);
prefEditor.commit();
}
And retrieving the data, in another activity:
resturantTextView = (TextView) findViewById(R.id.resturantChoice);
Intent intent = getIntent();
SharedPreferences sharedPref = getSharedPreferences("resturantFile",MODE_PRIVATE);
int resturantChoice = sharedPref.getInt("userChoiceSpinner",-1);
resturantTextView.setText("" + resturantChoice);
I just use the textView to see what it saves like, and currently it just shows -1
edit: might as well just add this, userChoice value is 0.
Try this:
Add like this SharedPreferences sharedPref = getSharedPreferences("resturantFile",Activity.MODE_PRIVATE) instead of
SharedPreferences sharedPref = getSharedPreferences("resturantFile",0).
For example: The way to save
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", yourIntValue);
editor.commit();
The way to retrieve data in another activity:
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", -1);
If that is not working for you then try this one:
Change the default value -1 to 0,
int myIntValue = sp.getInt("your_int_key", 0);
For more information use this question.