I am unable to retrieve the second value in Shared Preference - android

In my example, i am entering mobile no., message content in one activity. Before leaving that activity i am saving that info in "Shared Preference". In other activity i am trying to get those mob no,message,i am able to get no but unable to getting that message(second value).please help me to solve the issue.
DefaultDetails.java
package com.example.nirbhaya;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DefaultDetails extends Activity implements OnClickListener{
Button save,reset;
EditText dMob,dMsg,dEmail;
String defMobNo,defMsg,defEmail;
SharedPreferences DefaultData;
private static final String TAG = "DD-Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.defaultdetails);
initializing();
}
private void initializing() {
// TODO Auto-generated method stub
save = (Button)findViewById(R.id.bsave1);
reset = (Button)findViewById(R.id.bReset);
dMob = (EditText)findViewById(R.id.etDefMobNo);
dMsg = (EditText)findViewById(R.id.etDefMsg);
dEmail = (EditText)findViewById(R.id.etDefEmail);
save.setOnClickListener(this);
reset.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId())
{
case R.id.bsave1:
defMobNo = dMob.getText().toString();
defMsg = dMsg.getText().toString();
defEmail = dEmail.getText().toString();
Log.i(TAG,"DONE");
DefaultData = getSharedPreferences("defMobileNo",0);
SharedPreferences.Editor store = DefaultData.edit();
store.putString("defMobileNo", defMobNo);
store.putString("defMessgae", defMsg);
store.putString("defEMail", defEmail);
store.commit();
Intent openStartingPoint = new Intent (getApplicationContext(), CurrentDetails.class);
startActivity(openStartingPoint);
break;
case R.id.bReset:
((EditText) findViewById(R.id.etDefMobNo)).setText("");
((EditText) findViewById(R.id.etDefEmail)).setText("");
((EditText) findViewById(R.id.etDefMsg)).setText("");
break;
}
}
}
DefSMS.java
package com.example.nirbhaya;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class DefSms extends Activity{
Button buttonSend;
String defNo,defMsg;
SharedPreferences DefaultData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.defsms);
DefaultData = getSharedPreferences("defMobileNo",0);
final String defNo = DefaultData.getString("defMobileNo","Couldn't load data");
DefaultData = getSharedPreferences("defMessgae",0);
final String defMsg = DefaultData.getString("defMessgae","Couldn't load data");
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(defNo, null, defMsg, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}
Here def no getting message as Couldn't load data
please help me

Replace with this:
DefaultData = getSharedPreferences("defMobileNo",0);
final String defNo = DefaultData.getString("defMobileNo","Couldn't load data");
final String defMsg = DefaultData.getString("defMessgae","Couldn't load data");

This is how basically sharedpreference work
To Store the values
SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","myNameisnothing");
editor.commit();
To get the values
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String name = prfs.getString("Name", "");
This way it'd return the value of the name as myNameisnothing.
PS.Correct me if im wrong.

You are wrongly using
DefaultData = getSharedPreferences("defMessgae",0); in DefSMS.java
Please remove this and it will work fine.
You were trying to get shared preference named defMessgae which doesnot even exist. So when you try to access it, android will create a new preference with default value. That is why you were getting "Couldn't load data"

Related

SharedPreference is not working in checkbox

I want to fill the TextView of another activity based on preference on checkBox event but its working please help me to sort the issue..It is forcefully stopping.Please help in the if else statement part .what we need to write in activity 2 to select based on the checkBox in activity 1
Activity 1:
package com.example.rajatanurag.shoppingsites;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
public class Book extends AppCompatActivity {
Button b1,b2;
public static CheckBox cb1,cb2,cb3;
TextView tv1,tv2,tv3;
SharedPreferences sp1;
ImageView iv1,iv2,iv3;
String x,y,z;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
b1=(Button)findViewById(R.id.b1);
b2=(Button)findViewById(R.id.b2);
cb1=(CheckBox)findViewById(R.id.cb1);
cb2=(CheckBox)findViewById(R.id.cb2);
cb3=(CheckBox)findViewById(R.id.cb3);
tv1=(TextView)findViewById(R.id.tv4);
tv2=(TextView)findViewById(R.id.tv2);
tv3=(TextView)findViewById(R.id.tv3);
iv1=(ImageView)findViewById(R.id.iv1);
iv2=(ImageView)findViewById(R.id.iv2);
iv3=(ImageView)findViewById(R.id.iv3);
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
}
public void OnClick1(View view)
{
SharedPreferences.Editor editor = sp1.edit();
if(cb1.isChecked()==true) {
editor.putString("price1", tv1.getText().toString());
editor.putBoolean("x",true);
}
if(cb2.isChecked()==true)
{
editor.putString("price2",tv2.getText().toString());
editor.putBoolean("y",true);
}
if(cb3.isChecked()==true)
{
editor.putString("price3",tv3.getText().toString());
editor.putBoolean("z",true);
}
editor.commit();
Intent i=new Intent(this,MyCart.class);
startActivity(i);
}
}
2.Activity
package com.example.rajatanurag.shoppingsites;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MyCart extends AppCompatActivity {
SharedPreferences sp1;
TextView tv4,tv5,tv6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_cart);
tv4=(TextView)findViewById(R.id.tv4);
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
if(Book.cb1.isChecked()==true){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
if(Book.cb1.isChecked()==true){
String price21=sp1.getString("price2","");
tv5.setText(price21);
}
if(Book.cb1.isChecked()==true){
String price31=sp1.getString("price3","");
tv6.setText(price31);
}
}
}
You shouldn't be using static variables for view members because you might get memory leaks. Also the views you are referencing are destroyed when activity is destroyed, so they are not accessible in your second activity. You can send checkboxes checked values as intent extras.
Put this in your Activity 1 in OnClick1() method:
Intent i=new Intent(this,MyCart.class);
i.putExtra("cb1", cb1.isChecked());
i.putExtra("cb2", cb2.isChecked());
i.putExtra("cb3", cb3.isChecked());
startActivity(i);
This is how you get values in Activity 2 (in onCreate() method):
Intent intent = getIntent();
if(intent.getBooleanExtra("cb1", false)){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
if(intent.getBooleanExtra("cb2", false)){
String price21=sp1.getString("price2","");
tv5.setText(price21);
}
if(intent.getBooleanExtra("cb3", false)){
String price31=sp1.getString("price3","");
tv6.setText(price31);
}
public void OnClick1(View view)
{
if(view.getID() == R.id.cb1)
{
if(cb1.isChecked())
editor.putBoolean("x",true);
else
editor.putBoolean("x",false);
}
}
In your second activity
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
boolean isChecked = sp1.getBoolean("x", false);
if(isChecked){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}

In android, How can i display selected data from databse in list view??? i am using sqlite database

I am developing one android application.i want to display a data which is selected from database and display it in listview.first of all i had used static data for display Trainee(user) data. which is static. then after For same functionality i have use sqlite Database and register the Trainee(user) and now i want to display registered trainne's name in listview. i have just done below code. can anyone help me how to display trainee names in listview.
AddTraineeActivity.java
This file works basic function of create trainee database and insert values of trainee:
package com.example.gymapp;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddTraineeActivity extends Activity implements OnClickListener
{
EditText fn;
EditText ln;
EditText un;
EditText pwd;
EditText pno;
EditText age;
Button btnAdd;
SQLiteDatabase db = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_managetrainee);
fn = (EditText) findViewById(R.id.etfirstname);
ln = (EditText) findViewById(R.id.etlastname);
age = (EditText) findViewById(R.id.edage);
pno = (EditText) findViewById(R.id.etphoneno);
un = (EditText) findViewById(R.id.ettraineeun);
pwd = (EditText) findViewById(R.id.etpwdtrainee);
btnAdd = (Button) findViewById(R.id.btnsavedata);
db=openOrCreateDatabase("mydb", MODE_PRIVATE, null);
db.execSQL("create table if not exists trainee(firstname text, lastname text,age varchar,phoneNumber varchar,userTrainee varchar,passwordTrainee varchar)");
btnAdd.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
public void show(String str)
{
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v== btnAdd)
{
String firstname = fn.getText().toString();
String lastname = ln.getText().toString();
String Age = age.getText().toString();
String phoneNumber = pno.getText().toString();
String usernameTrainee = un.getText().toString();
String passwordTrainee = pwd.getText().toString();
if(firstname==null||firstname==""||firstname.length()<3)
{
show("Please Enter Correct Name.");
}
else if(lastname==null||lastname==""||lastname.length()<2)
{
show("Please Enter Correct Name.");
}
else if(Age==null||Age==""||Age.length()>3)
{
show("Please Enter Correct Age.");
}
else if(phoneNumber==null||phoneNumber==""||phoneNumber.length()<10)
{
show("Please Enter Correct mobile number.");
}
else if(usernameTrainee==null||usernameTrainee==""||usernameTrainee.length()<4)
{
show("Please Enter valid User name.");
}
else if(passwordTrainee==null||passwordTrainee==""||passwordTrainee.length()<6)
{
show("Please Enter Strong Password.");
}
else
{
db.execSQL("insert into trainee values('"+firstname+"','"+lastname+"','"+Age+"','"+phoneNumber+"','"+usernameTrainee+"','"+passwordTrainee+"')");
//i=new Intent(this,Welcome.class);
//startActivityForResult(i, 500);
//overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
db.close();
finish();
}
}
}
}`
UserListActivity.java
This file contain the code which display the trainee names in listview. but this file display static users for example,trainee1,trainee2,trainee3....trainee13.
package com.example.gymapp;
import com.tss.constant.Constant;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.content.Context;
import android.database.sqlite.*;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import com.example.gymapp.AddTraineeActivity;
import com.example.gymapp.dao.DBfitguidehelper;
public class UserListActivity extends Activity {
private ListView listViewUser;
private String loggedInType ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
//SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
//queryBuilder.setTables(DBfitguidehelper.)
listViewUser = (ListView)findViewById(R.id.listViewUser);
String[] values = new String[]{"trainee", "trainee1", "trainee2", "trainee3", "trainee4", "trainee5", "trainee6", "trainee7", "trainee8", "trainee9", "trainee10", "trainee11", "trainee12", "trainee13"};
ArrayAdapter<String> userAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
listViewUser.setAdapter(userAdapter);
listViewUser.setOnItemClickListener(new ListViewListner());
if(savedInstanceState!=null){
Bundle extras = getIntent().getExtras();
loggedInType = extras.getString("loggedInType");
System.out.println("loggedInType - " + loggedInType);
}
}
private class ListViewListner implements OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "selected user is " + listViewUser.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
Constant.Selected_Trainee = ""+listViewUser.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(),TrainerActivity.class);
intent.putExtra("loggedInType", loggedInType);
Toast.makeText(getApplicationContext(), "loggedInType"+loggedInType, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_list, menu);
return true;
}
}
now i want to display name of trainees which is stored in database. can anyone help me??
If you want to see how a Cursor loader can work for you, you can review the following project that I have uploaded to github: GPS Distance Tracking

My Android application does not store the high score

I'm developing a simple game in Android and even i followed the steps found in the net, the highscore of my app is never saved. I'm using SharedPreferences to store, but I'm quietly sure the problem is in there, because I don't understand at all how to use it.Hope you guys can help me, thanks.
package com.example.memory;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Final extends Activity implements OnClickListener{
TextView levelReachedText;
TextView bestScoreText;
int levelReached, bestScore;
Intent intent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.finals);
levelReachedText = (TextView) this.findViewById(R.id.nivel);
bestScoreText = (TextView) this.findViewById(R.id.best);
Button menu = (Button) findViewById(R.id.inicio);
menu.setOnClickListener(this);
intent = getIntent();
levelReached = intent.getIntExtra("nivel", 1);
SharedPreferences preferences = this.getSharedPreferences("bestScore", MODE_PRIVATE);
int savedScore = preferences.getInt("selectedScore", 0);
levelReachedText.setText("You reached level "+levelReached );
if(savedScore>levelReached){
bestScore = savedScore;
}else{
bestScore = levelReached;
}
bestScoreText.setText("Maximum level reached "+levelReached);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.inicio:
SharedPreferences preferences = this.getSharedPreferences("mejorScore", MODE_PRIVATE);
preferences.edit().putInt("selectedScore", bestScore).commit();
this.finish();
break;
}
}
}
you are saving score value in mejorScore and trying to get it from bestScore.So either change
SharedPreferences preferences = this.getSharedPreferences("mejorScore", MODE_PRIVATE);
to
SharedPreferences preferences = this.getSharedPreferences("bestScore", MODE_PRIVATE);
or vice-versa.

Android code does not update user account

I am working on an android code and trying to update the user information. I am able to retrieve the information but have not been able to update. Not sure what I am doing wrong.
In the if-else statement, it does not hit the If statement, goes directly to the error(else statement.
here is the code
package com.example.autrui;
import com.parse.GetCallback;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.parse.SendCallback;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EditPP extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.editpp);
final Button confirmChangeEditPP = (Button) findViewById(R.id.bconfirmChangeEditPP);
final EditText fullName = (EditText) findViewById(R.id.etFullName);
final EditText email = (EditText) findViewById(R.id.etEmail);
//final ParseUser currentUser = new ParseUser();
final ParseUser currentUser = ParseUser.getCurrentUser();
System.out.println(currentUser);
String objectId = currentUser.getObjectId();
System.out.println(objectId);
String fName = currentUser.getString("fullName");
fullName.setText(fName);
email.setText(currentUser.getString("email"));
ParseQuery<ParseObject> userQuery = ParseQuery.getQuery("User");
userQuery.getInBackground((String)objectId, new GetCallback<ParseObject>(){
public void done(final ParseObject object, ParseException e) {
if (e == null) {
confirmChangeEditPP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ParseACL acl = new ParseACL();
acl.setPublicReadAccess(true);
acl.setPublicWriteAccess(true);
currentUser.setACL(acl);
object.put("fullName", fullName.getText().toString());
object.put("email", email.getText().toString());
object.saveInBackground();
}
});
} else {
Log.e("error","error");
}
}
});
}
#Override
public void onBackPressed() {
finish();
// Go to settings
/*
* if(MainActivity.s.isEmpty()) return; else { View v =
* MainActivity.s.pop(); Class c = MainActivity.s2.pop(); Intent intent
* = new Intent(v.getContext(), c); startActivityForResult(intent, 0); }
*/
}
private void showUserDetailsActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
I got the answer. the error was regarding the ACL and yes we did not need the query. I wrote the whole code again and made it simpler.

How do you save the data of an int, and then edit the number onclick of a button?

I am trying to have it so when you click one of the answeers (Q1A1 or Q1A2) it will add a number of points to the testScore int so I can then later call that in a later class so the score they got would be posted there. Thanks to anyone who helps in advance!
here's my code,
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Test extends Activity implements OnClickListener
{
TextView Q1A1;
TextView Q1A2;
TextView test;
public static final String PREFS_NAME = "MyPrefsFile";
public static final int testScore = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Q1A1 = (TextView) findViewById(R.id.Q1A1);
Q1A2 = (TextView) findViewById(R.id.Q1A2);
Q1A1.setOnClickListener(this);
Q1A2.setOnClickListener(this);
test = (TextView) findViewById(R.id.test);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
test.setText(settings.getString("YourScore", "No Score"));
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.Q1A1:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YourScore", (testScore + 10));
editor.commit();
//Intent FinalScore = new Intent(this, FinalScore.class);
//startActivity(FinalScore);
break;
case R.id.Q1A2:
break;
}
}
}
thanks for the help
You are are saving your score as an int but calling it as a string.
Change
test.setText(settings.getString("YourScore" , "No Score"));
To
test.setText(""+settings.getInt("YourScore" , 0));

Categories

Resources