I'm having issues where I have a button that is essentially a "favorites" button that saves a URL from a webview sesson and adds it to a listview in another class called favorites. It is doing this through sharedpreferences due to a lack of finding a better way to do it. The issue I'm having is when I try to save another URL it just overwrites the URL that is currently there and doesn't add another row. My code for webview that has the button is:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_share) {
shareURL();
Toast.makeText(this, getString(R.string.share),
Toast.LENGTH_SHORT).show();
}
if (id == R.id.action_favorite) {
changeIcon();
Snackbar.make(findViewById(android.R.id.content), "Saved for later", Snackbar.LENGTH_LONG).show();
String url = getIntent().getDataString();
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("URL", url );
edit.apply();
}
return super.onOptionsItemSelected(item);
}
// code for my "favorites" class is below:
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems = new ArrayList<String>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites_list);
ListView listView = (ListView) findViewById(R.id.favoritesList);
adapter = new ArrayAdapter<String>(this,
R.layout.custom_lv,
listItems);
listView.setAdapter(adapter);
SharedPreferences bb = getSharedPreferences("my_prefs", 0);
String m = bb.getString("URL", "");
listItems.add(m);
adapter.notifyDataSetChanged();
}
Any help would be greatly appreciated!
--- EDIT --
With FnR's code it's still only adding the latest "saved" url in favorites list view, updated code is below:
--Favorites code--
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites_list);
ListView listView = (ListView) findViewById(R.id.favoritesList);
adapter = new ArrayAdapter<String>(this,
R.layout.custom_lv,
listItems);
listView.setAdapter(adapter);
getListFromSharedPreferences();
}
private List<String> getListFromSharedPreferences() {
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
Set<String> set = prefs.getStringSet("URL", null);
List<String> urlList = new ArrayList<>();
if (set != null) {
urlList = new ArrayList<>(set);
listItems.add(String.valueOf(set));
adapter.notifyDataSetChanged();
}
Log.e("size",urlList.size()+"");
return urlList;
}
-- Webview code --
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_share) {
shareURL();
Toast.makeText(this, getString(R.string.share),
Toast.LENGTH_SHORT).show();
}
if (id == R.id.action_favorite) {
changeIcon();
Snackbar.make(findViewById(android.R.id.content), "Saved for later", Snackbar.LENGTH_LONG).show();
String url = getIntent().getDataString();
putSharedPreferences(url);
}
return super.onOptionsItemSelected(item);
}
private void putSharedPreferences(String url) {
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
Set<String> set = prefs.getStringSet("URL", null);
if (set != null) {
set.add(url);
edit.putStringSet("URL", set);
edit.apply();
}
}
You are using same SharedPreferences key that means when you add a new url you are overriding already existing url.You need to store urls in a list . For this you can use SharedPreferences.Editor.putStringSet. Example is here
Save ArrayList to SharedPreferences.
private void putSharedPreferences(String url) {
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
Set<String> set = prefs.getStringSet("key", null);
if (set != null) {
set.add(url);
edit.putStringSet("key", set);
edit.apply();
}
}
private List<String> getListFromSharedPreferences() {
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
Set<String> set = prefs.getStringSet("key", null);
List<String> urlList = new ArrayList<>();
if (set != null) {
urlList = new ArrayList<>(set);
}
Log.e("size",urlList.size()+"");
return urlList;
}
What you need to do is add the previous saved URLs to the new Set before adding to SharedPreference.
private void putSharedPreferences(String url) {
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
Set<String> previousSet = prefs.getStringSet("key", null);
Set<String> set = new HashSet<>();
if (previousSet != null) {
set.addAll(previousSet);
}
set.add(url);
edit.putStringSet("key", set);
edit.apply();
}
}
The reason behind adding all previous saved data to new HashSet is that modifying the returned instance will not guarantee the data consistency or if its been modified at all. You can see documentation here for more explanation.
Related
I've made registration and login activity in an android using shared preferences. User is able to registered and logged in successfully. But my problem is when new user is registered, it delete the previous user's registration details.
Here is my registration page:
public class Registration extends Activity implements
View.OnClickListener
{
SharedPreferences pref;
Editor editor;
TextView btn_registration , btn_formlogin;
EditText et_name, et_pass, et_email , et_phone ;
ImageView btn_upload ;
private static final int PICK_IMAGE_REQUEST = 0;
private Uri mImageUri;
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
et_name = (EditText) findViewById(R.id.edt_Name);
et_pass = (EditText) findViewById(R.id.edt_userPassword);
et_email = (EditText) findViewById(R.id.edt_userEmail);
et_phone = (EditText) findViewById(R.id.edt_Phone);
btn_registration = (TextView) findViewById(R.id.btn_registration);
btn_formlogin = (TextView) findViewById(R.id.btn_formlogin);
btn_upload = (ImageView)findViewById(R.id.img_upload);
Map<String,String> values = new HashMap<String,String>();
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
btn_upload.setOnClickListener(this);
SharedPreferences preference =
PreferenceManager.getDefaultSharedPreferences(this);
final String mImageUri = preference.getString("image", null);
btn_upload.setImageResource(R.drawable.adduser);
// creating an shared Preference file for the information to be stored
// first argument is the name of file and second is the mode, 0 is
private mode
pref = getSharedPreferences("USER_CREDENTIALS", 0);
// get editor to edit in file
editor = pref.edit();
// the tap of button we will fetch the information from four edittext
btn_registration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
boolean validName = true;
boolean validPass = true;
boolean validPhone = true;
boolean validEmail = true;
String name = et_name.getText().toString();
String email = et_email.getText().toString();
String pass = et_pass.getText().toString();
String phone = et_phone.getText().toString();
if (isEmpty(et_name)) {
et_name.setError("Enter the Name");
validName = false;
}
if (isEmpty(et_pass)) {
et_pass.setError("Password can't be null");
validPass = false;
}
if (isEmail(et_email) == false) {
et_email.setError("Enter valid email");
validEmail = false;
}
if (isValidMobile(et_phone) == false) {
validPhone = false;
}
final String required_email= pref.getString("Email",null);
final String required_phone=pref.getString("Phone",null);
if(et_email.equals(required_email)){
validEmail = true;
}
else if(et_phone.equals(required_phone)){
validPhone = true;
}
if (validName && validPass && validPhone && validEmail){
// as now we have information in string. Lets stored them
with the help of editor
editor.putString("Name" , name );
editor.putString("Email", email);
editor.putString("Password", pass);
editor.putString("Phone", phone);
editor.putString("image", String.valueOf(mImageUri));
editor.commit(); // commit the values
Toast.makeText(Registration.this, "Registration
Successful", Toast.LENGTH_LONG).show();
session = new SessionManager(getApplicationContext());
session.createLoginSession(name, email, mImageUri);
// after saving the value open next activity
Intent ob = new Intent(Registration.this,
DashBoard.class);
startActivity(ob);
}
else{
Toast.makeText(Registration.this, "Registration
unsuccessful! Please retry.", Toast.LENGTH_LONG).show();
}
}
});
I just want to know how to register multiple user using shared preferences file ?
If you will have multiple users, it is better to use a database(sqlite) than a shared preferences.
in shared preference you can save only single value in a object if you want to save multiple users in your device then you can use room database to store multiple user details in your device. Shared Preference can be used only for single information or if you want to store multiple values in shared preference then you can store arrayList in shared prefefrence.
save array list in shared preference:-
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static Set<String> getCamEval(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getStringSet("sdk_camEval", null);
}
public static void setCamEval(Context ctx, ArrayList<String> value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
Set<String> set = new HashSet<>();
set.addAll(value);
mPrefsEditor.putStringSet("sdk_camEval", set);
mPrefsEditor.commit();
}
public class ActivityEditParent extends AppCompatActivity {
private static final String TAG="ActivityEditParent";
CustomEditText etFirstName,etLastName,etEmail,etPhone;
public static ConnectionDetector detector;
private static final String URL = "http://hooshi.me.bh-in-13.webhostbox.net/index.php/parents/editprofile";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private CustomButton btnSave;
private String parentFirstName,parentLastName,parentPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_parent);
getSupportActionBar().hide();
detector = new ConnectionDetector(ActivityEditParent.this);
getUIComponents();
}
private void getUIComponents(){
etFirstName = (CustomEditText) findViewById(R.id.edit_first_name);
etLastName = (CustomEditText) findViewById(R.id.edit_last_name);
etEmail = (CustomEditText) findViewById(R.id.edit_email_address);
etPhone = (CustomEditText) findViewById(R.id.edit_phone_number);
btnSave = (CustomButton) findViewById(R.id.btn_save_parent);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editParent();
}
});
TextView title = (TextView) findViewById(R.id.toolbar_title);
ImageButton back = (ImageButton) findViewById(R.id.toolbar_back);
title.setText("Edit parent");
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goBack();
}
});
sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
String fName = sharedPreferences.getString(AppConstants.PARENT_FNAME,AppConstants.fName);
String lName = sharedPreferences.getString(AppConstants.PARENT_LNAME,AppConstants.lName);
String email = sharedPreferences.getString(AppConstants.PARENT_EMAIL,AppConstants.email);
String phone = sharedPreferences.getString(AppConstants.PARENT_MOBILE,AppConstants.mobile);
etFirstName.setText(fName);
etLastName.setText(lName);
etPhone.setText(phone);
etEmail.setText(email);
}
private void goBack() {
startActivity(new Intent(getApplicationContext(), ActivityEditDetails.class));
finish();
}
private void editParent(){
SharedPreferences preferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
JSONObject jsonParam = null;
parentFirstName = etFirstName.getText().toString().trim();
parentLastName = etLastName.getText().toString().trim();
parentPhone = etPhone.getText().toString().trim();
if (detector.checkInternet()){
jsonParam = new JSONObject();
JSONObject header = new JSONObject();
try {
jsonParam.put("parentId",preferences.getString(AppConstants.PARENT_ID,""));
jsonParam.put("parentFN",parentFirstName);
jsonParam.put("parentLN",parentLastName);
jsonParam.put("parentPhone",parentPhone);
jsonParam.put("apiAccessKey",preferences.getString(AppConstants.API_ACCESS_KEY,""));
header.put("parent",jsonParam);
Log.d("POST PARAMETERS:",""+header);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, header, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response:",""+response);
String json_status = null;
try {
json_status = response.getString("status");
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
}
}
In the response After getting success message I want save the edited details in in respective edit text fields please help.After success message I am moving to home screen through intent and again I get back to this screen it is showing the previous details only.
all happens here :
...
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
...
once you have a success response save the edited values on the preferences, for example etFirstName, save it is new value to the corresponding preference :
...
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
editor.putString(AppConstants.PARENT_FNAME, parentFirstName);
editor.apply(); //don't forget this
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
...
any way you're creating the editor but not using it.
you want to save data after download from network or after an edit in edit text fields was made??
if from network add some save method execution statement in code where you download data was successful
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
// here you have successful received data so u can map them to edit text or save in shared prefs
// add method to save data here
saveData(response);
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
private void saveData(JSONObject response) {
// use JSon response object save here to shared preferences
// see how to load data from json object
// https://processing.org/reference/JSONObject_getString_.html
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
sharedPreferences.putString(....).apply;
// or set edit text controls with JSon data
}
to save edit text changes you have two choices :
add to layout save button (you have one) button and set on click listener with method to save data:
btnSave = (CustomButton) findViewById(R.id.btn_save_parent);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData(v);
}
});
private void saveData(View view) {
// get root view
View rootView = view.getRootView();
// find edit text widget on root view
EditText etFirstName = (EditText) rootView.findViewById(R.id.edit_first_name);
// get string from edit text widget
String firstName = etFirstName.getString.toString();
// get shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
// save to shared prefs firstName wher NAME_KEY is string to identified your saved data for later use - to load
sharedPreferences.putString(NAME_KEY,firstName).apply;
}
private void loadDataFromSharedPredferences(View view) {
// get shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
// load data from shared prefs firstName wher NAME_KEY is string to identified data to load
String firstName = sharedPreferences.getString(NAME_KEY,firstName);
// get root view
View rootView = view.getRootView();
// find edit text widget on root view
EditText etFirstName = (EditText) rootView.findViewById(R.id.edit_first_name);
// set string to edit text widget
etFirstName.setText(firstName);
}
add on text change listener for edittext widgets
ps. you need to clarify - write a exactly steps of what you want to do achieve
load data from network ? then save ?
or save request date ?
or save result data ?
I have two strings that I want to save them I wrote the code as shown below
public class MainActivity extends Activity {
Button result;
EditText b951, b9511, sum95, t95, p95
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LoadPreferences();
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
}
public void close (View v){
SavePreferences("p2b951", b951.getText().toString());
SavePreferences("p2b9511", b9511.getText().toString());
finish();
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String p1b951 = sharedPreferences.getString("p2b951", "1");
String p1b9511 = sharedPreferences.getString("p2b9511", "1");
b951.setText(p1b951);
b9511.setText(p1b9511);
}
public void result (View v) {
try {
int ib951 = Integer.parseInt(b951.getText().toString());
int ib9511 = Integer.parseInt(b9511.getText().toString());
int iisum95 = (ib9511-ib951);
sum95.setText(String.valueOf(iisum95));
int isum95 = Integer.parseInt(sum95.getText().toString());
int ip95 = Integer.parseInt(p95.getText().toString());
int pp95 = (isum95*ip95);
t95.setText(String.valueOf(pp95));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
But it seems there is a problem with this two lines:
b951.setText(p1b951);
b9511.setText(p1b9511);
I tried this
b951.setText(String.valueOf.p1b951);
b9511.setText(String.valueOf.p1b9511);
Also the problems still exist
When I open the application and when the loadpreferences is called the app will force close
The logcat show me that the error is with this two lines for sure it's just with the first line coz he didn't get the second but they are the same so they are wrong wroted
Any help??
Change onCreate() as follows:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
result = (Button)findViewById(R.id.btn1);
b951 = (EditText)findViewById(R.id.b951);
b9511 = (EditText)findViewById(R.id.b9511);
sum95 = (EditText)findViewById(R.id.sum95);
p95 = (EditText)findViewById(R.id.p95);
t95 = (EditText)findViewById(R.id.t95);
LoadPreferences();
}
This is because you are using the EditTexts in the LoadPreferences() without calling findViewById() on the EditTexts.
You can follow and help from like codes. such as
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
it any confused about this then follow this link
In my app I have been using shared preferences for saving various types of data. I have been able to get the desired result using shared preferences before but I haven't been able to solve an issue with it.
I am saving an ArrayList in shared preferences in onPause method, getting saved data in OnCreate method and clearing the preferences in onBackPressed method. I have been able to finish this activity and still be able to get the ArrayList's data in Oncreate, but when I press the phone's back button twice and when the activity is created again I loose the data in ArrayList.
Here are parts of my code:
public class RecipientAddressActivity extends FragmentActivity {
private ArrayList<Person> prev_recArray;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipient_address);
prev_recArray = new ArrayList<Person>();
loadPreferences();
addListeners();
}
private void loadPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Gson gson = new Gson();
if (prev_recArray.size() == 0) {
int prev_recArraysize = sharedPreferences.getInt(
"Prev_Rec_Size", 0);
if (prev_recArraysize > 0) {
for (int i = 0; i < prev_recArraysize; i++) {
String json = sharedPreferences.getString(
"PrevRecList_" + i, "");
Person p = gson.fromJson(json, Person.class);
prev_recArray.add(p);
}
}
}
}
}
In a button's click event, I add an item in the prev_recArray:
{
Intent Recipient_info = new Intent();
Person recipient = new Person(edt_rec_name.getText().toString(),
edt_rec_addr1.getText().toString(), edt_rec_addr2.getText()
.toString(), edt_rec_city.getText().toString(), edt_rec_state
.getText().toString(), edt_rec_pcode.getText().toString(),
edt_rec_country.getText().toString());
prev_recArray.add(recipient);
// ...
finish();
}
private void showRecPicker() {
final RecipientPicker rec_picker = RecipientPicker
.newInstance("Select a Recipient");
Log.e("Before passing it to getAllRecipients Size", "RecPicker = "
+ prev_recArray.size());
rec_picker.getAllRecipients(prev_recArray);
if ((prev_recArray.size() == 0)) {
AlertDialog no_recipients = new AlertDialog.Builder(
RecipientAddressActivity.this).create();
no_recipients.setMessage("No previous recipients.");
no_recipients.setButton(RESULT_OK, "OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
});
no_recipients.show();
} else {
rec_picker.setListener(new RecipientPickerListener() {
#Override
public void onSelectRecipient(Person p) {
loadPersonValues(p);
rec_picker.dismiss();
}
});
rec_picker.show(getSupportFragmentManager(), "RECIPIENT_PICKER");
}
}
#Override
protected void onPause() {
Log.e("In RecipientAddress", "On Pause");
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
for (int i = 0; i < prev_recArray.size(); i++) {
String json = gson.toJson(prev_recArray.get(i));
editor.putString("PrevRecList_" + i, json);
}
editor.putInt("Prev_Rec_Size", prev_recArray.size());
editor.commit();
super.onPause();
}
#Override
public void onBackPressed() {
Log.e("Phone's back button is presed", "Clearing SP");
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
super.onBackPressed();
}
Can someone please point out if I'm doing something wrong or missing something.
I came across two problems.
1) How do I get my row.xml to show in my listview.xml?
In my java class I extend ListActivity and use the code:
ListView listView = (ListView)findViewById(R.id.list);
ArrayAdapter<?> arrayAdapter = new ArrayAdapter<?>(this, R.layout.row
I'm not sure how to finish this.
2) How do I load data I saved on my sharedPReference which is two string values into my row?
My code that saves the two stringvalues is:
String product = "Health Vitamins";
String category = "Nutrition";
savePreference("NAME", product);
savePreference("NUTRITION", category);
Then I use putString(key, value) and commit() in my savePreference method. When I want to load the data I simply use loadPreference() which will use getString("NAME", "") and getString("NUTRITION", "") and retrieve the data.
Problem is how do I actually put the data I retrieve into my listview row.xml? For example once loadPreference() method is invoked it is suppose to retrieve the two string values and place it in the row? Any Ideas?
String[] data = //load the array here.
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, data);
Whatever you want to put into your array. It could be your Shared Preference values. But then why would you be using Shared Preferences since it uses key value pairs. And you can't double up on keys meaning your list will always have 1 or at most 2 entries.
You can pass data to ListView from SharedPreferences using Intent
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText nameEditText, rollEditText, deptEditText, semesterEditText;
private Button submittButton;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameEditText = findViewById(R.id.nameEditTextID);
rollEditText = findViewById(R.id.rollEditTextID);
deptEditText = findViewById(R.id.deptEditTextID);
semesterEditText = findViewById(R.id.semesterEditTextID);
submittButton = findViewById(R.id.submitButtonID);
textView = findViewById(R.id.textViewID);
submittButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.submitButtonID) {
String userName = nameEditText.getText().toString();
String userRoll = rollEditText.getText().toString();
String userDept = deptEditText.getText().toString();
String userSemester = semesterEditText.getText().toString();
if (userName.equals("") && userRoll.equals("") && userDept.equals("") && userSemester.equals("")) {
Toast.makeText(getApplicationContext(), "Please enter data", Toast.LENGTH_SHORT).show();
} else {
SharedPreferences sharedPreferences = getSharedPreferences("Details", 0);
//SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userNameKey", userName);
editor.putString("userRollKey", userRoll);
editor.putString("userDeptKey", userDept);
editor.putString("userSemesterKey", userSemester);
editor.apply();
nameEditText.setText("");
rollEditText.setText("");
deptEditText.setText("");
semesterEditText.setText("");
Toast.makeText(getApplicationContext(), "Saved successfully", Toast.LENGTH_SHORT).show();
if (sharedPreferences.contains("userNameKey") && sharedPreferences.contains("userRollKey") && sharedPreferences.contains("userDeptKey")
&& sharedPreferences.contains("userSemesterKey")) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
/*if (sharedPreferences.contains("userNameKey") && sharedPreferences.contains("userRollKey") && sharedPreferences.contains("userDeptKey")
&& sharedPreferences.contains("userSemesterKey")) {
String name = sharedPreferences.getString("userNameKey", "Data not found");
String roll = sharedPreferences.getString("userRollKey", "Data not found");
String department = sharedPreferences.getString("userDeptKey", "Data not found");
String semester = sharedPreferences.getString("userSemesterKey", "Data not found");
Toast.makeText(getApplicationContext(), "Loaded successfully", Toast.LENGTH_SHORT).show();
textView.setText(name + "\n" + roll + "\n" + department + "\n" + semester);
}*/
}
}
}
public class ListDataActivity extends AppCompatActivity {
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_data);
listView = findViewById(R.id.listViewID);
SharedPreferences sharedPreferences = getSharedPreferences("Details", 0);
String name = sharedPreferences.getString("userNameKey", "Data not found");
String roll = sharedPreferences.getString("userRollKey", "Data not found");
String department = sharedPreferences.getString("userDeptKey", "Data not found");
String semester = sharedPreferences.getString("userSemesterKey", "Data not found");
Toast.makeText(this, "Roll is:" + roll, Toast.LENGTH_SHORT).show();
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add(name);
arrayList.add(roll);
arrayList.add(department);
arrayList.add(semester);
ArrayAdapter<String>arrayAdapter = new ArrayAdapter<String>(this,R.layout.list_item,R.id.sampleTextViewID,arrayList);
listView.setAdapter(arrayAdapter);
}
}