SharedPreferences doesn't save my username - java

The SharedPreferences doesn't save my username while I don't get any error. I have checked my method with some tutorials and I can't find what's wrong. I have tried both commit() and 'apply()' despite that can't make here a difference.
Someone who finds the error?
my code:
public class MainActivity extends AppCompatActivity implements AsyncResponse, View.OnClickListener {
EditText etUsername, etPassword;
ImageButton btnLogin;
String username;
CheckBox ckbx_login;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (ImageButton) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(this);
username = etUsername.getText().toString();
}
#Override
public void processFinish(String result) {
if(result.equals("success")) {
SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences(PREFS_NAME,0).edit();
editor.putString("loginname",username);
editor.commit();
Intent in = new Intent(this, SubActivity.class);
String naam2= etUsername.getText().toString();
in.putExtra("naam2",naam2);
startActivity(in);
}
else{
Toast.makeText(this,"Inloggen mislukt", Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View view) {
HashMap postData = new HashMap();
postData.put("mobile", "android");
postData.put("txtUsername", etUsername.getText().toString());
postData.put("txtPassword", etPassword.getText().toString());
PostResponseAsyncTask task = new PostResponseAsyncTask(this, postData);
task.execute("http://exemple.com");
}
And the second class:
public static final String PREFS_NAME = "MyPrefsFile";
String name;
TextView msg_welcome;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_sub);
msg_welcome = (TextView) findViewById(R.id.txtVwelcome);
SharedPreferences prefs = this.getSharedPreferences(PREFS_NAME,0);
String restored_loginname = prefs.getString("loginname",null);
if(restored_loginname != null) {
name = prefs.getString("name", "No name defined");
}
Toast.makeText(getApplicationContext(),name,Toast.LENGTH_LONG).show();
}
public void scan(View View){
zXingScannerView = new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
#Override
protected void onPause() {
super.onPause();
zXingScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
// Toast.makeText(getApplicationContext(),result.getText(),Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Avt_form2.class);
String qrcode = result.getText();
i.putExtra("qrcode",qrcode);
startActivity(i);
}
Btw I know that Postdata is outdated. I am looking to replace it.

Issue : currently your taking the value of username in onCreate when you don't have the user input so
username = etUsername.getText().toString();
should be executed after user input is available like in onclick
or
#Override
public void processFinish(String result) {
if(result.equals("success")) {
SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences(PREFS_NAME,0).edit();
username = etUsername.getText().toString();
//^^^^^^^^^
editor.putString("loginname",username);
editor.commit();
Note : name was not previously used to store any value , i guess wanted to use name2

Related

How to store the login state in sharedpreferences

I'm making an Android app and in my app, I add the feature of storing the login state.
My Splash screen:
public class Splash extends AppCompatActivity {
private SharedPreferences preferences;
public int a = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
new CountDownTimer(5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
a = a + 1;
progressBar.setProgress(a);
}
#Override
public void onFinish() {
SharedPreferences preferences = getSharedPreferences("login", MODE_PRIVATE);
String check = preferences.getString("login", "off");
if (check.equals("on")) {
startActivity(new Intent(Splash.this, Menu.class));
} else {
startActivity(new Intent(Splash.this, LoginPage.class));
}
}
}.start();
} }
My Login screen:
public class LoginPage extends AppCompatActivity {
private SharedPreferences preferences;
Context context;
Button login, register, database;
EditText username;
EditText password;
TextView msg;
MyDBManager db;
static final int REGISTRATION_REQUEST = 1; // The request code
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginpage);
db = new MyDBManager(this);
msg = (TextView) findViewById(R.id.msg);
login = (Button) findViewById(R.id.button);
register = (Button) findViewById(R.id.button2);
database = (Button) findViewById(R.id.button3);
username = (EditText) findViewById(R.id.user);
password = (EditText) findViewById(R.id.pass);
// Click and move to the next activity
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.open();
Cursor c = db.getUser(username.getText().toString(), password.getText().toString());
if (c.moveToFirst()) {
db.close();
context.startActivity(new Intent(context,Menu.class));
// Intent i=new Intent(getApplicationContext(),Menu.class); //
i.putExtra("Username", username.getText().toString()); //
startActivity(i); // call Login Activity
Store();
}
else
{
db.close();
// set error message when the username and/or password is not valid
msg.setText("Unable to login: wrong username or password!");
// Stay at the current activity.
}
}
private void Store() {
SharedPreferences preferences=context.getSharedPreferences("login",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
editor.putString("login_status","on");
editor.commit();
}
});
// Click and move to the next activity
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginPage.this, Registration.class);
startActivityForResult(intent, REGISTRATION_REQUEST);
}
});
// Click and move to the next activity
database.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginPage.this, Database.class);
startActivity(intent);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REGISTRATION_REQUEST) {
//if(resultCode == Registration.RESULT_OK){
Log.d("Pikatchu", "User successfully registered!");
Bundle res = data.getExtras();
String result = res.getString("result");
System.out.println(result);
msg.setText(result);
}
}
}
My Menu screen:
public class Menu extends AppCompatActivity {
private SharedPreferences preferences;
Button startJourney, displayJourneys;
TextView msg; // where to display the name of the user
Button buttonLogout ;
/* the string is where to store data when we select something */
String db_username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
buttonLogout = (Button) findViewById(R.id.btn_logout);
msg = (TextView) findViewById(R.id.msg);
startJourney = (Button) findViewById(R.id.recordingmode);
// Bundle bundle = getIntent().getExtras(); //
db_username = (bundle.getString("Username")); //// //// // Set
Welcome message to the user who logged in //
msg.setText("Welcome "+db_username);
// Click and move to the next activity // startJourney.setOnClickListener(new View.OnClickListener() { //
#Override // public void onClick(View v) { //
Intent intent = new Intent(Menu.this, Recordingmode.class); //
intent.putExtra("Username", db_username); //
startActivity(intent); // } // });
// Click and move to the next activity buttonLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences=getSharedPreferences("login", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
editor.putString("login_status","off");
editor.commit();
finish();
moveTaskToBack(true);
} });
}
}
But if I login in the app, the error is thrown:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null
object reference

Issues in SharedPreference

I have one button in mainactivity when i click on button formactivty opened then after saved the data and i killed the app it display from main activity, it doesn't show welcome activity by using shared preference. any one can solve this one
Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void open(View v) {
Intent i = new Intent(MainActivity.this,Form.class);
startActivity(i);
}
}
FormActivty
public class Form extends Activity {
SharedPreferences sp;
public static String Filename= "LoginFile";
public static String key = "status";
EditText namee,emaill;
String Name,Email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = getSharedPreferences(Filename,MODE_PRIVATE);
boolean res = sp.getBoolean(key,false);
if (res) {
setContentView(R.layout.welcom);
} else {
setContentView(R.layout.form);
}
}
public void save(View v) {
namee = (EditText)findViewById(R.id.name);
emaill = (EditText)findViewById(R.id.email);
Name = namee.getText().toString();
Email = emaill.getText().toString();
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean(key,true);
ed.putString("k1",Name);
ed.putString("k2",Email);
ed.commit();
Intent i = new Intent(this,Welcome.class);
startActivity(i);
}
}
Welcome Activity
public class Welcome extends Activity {
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcom);
sp = getSharedPreferences(Form.Filename,MODE_PRIVATE);
TextView tv= (TextView)findViewById(R.id.text);
TextView tv1= (TextView)findViewById(R.id.text1);
String username,email;
Intent i = getIntent();
Bundle b = new Bundle();
b= i.getExtras();
username = sp.getString("k1","");
email = sp.getString("k2","");
tv.setText(username);
tv1.setText(email);
}
public void logout(View v) {
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean(Form.key,false);
ed.commit();
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}
}
On your MainActivity, under onCreate(), there should be a code that checks if your SharedPreference is empty. If it's empty, it should go to Form.class or it should not do anything since you have a button there in MainActivity. If not, then go to Welcome.class. You're almost there, just do some minor tweaks on your code and you'll get it.
public class MainActivity extends AppCompatActivity {
SharedPreferences sp;
public static String Filename= "LoginFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = getSharedPreferences(Filename,MODE_PRIVATE);
String name = sp.getString("k1", "");
if(!name.isEmpty()){
Intent intent = new Intent(MainActivity.this, Welcome.class);
startActivity(intent);
}
}
public void open(View v) {
Intent i = new Intent(MainActivity.this,Form.class);
startActivity(i);
}
}
If you'll notice on this code, every time the app is killed and you start it again, it'll check if sharedpreference is empty. If not, it will go directly to Welcome.class.

Problems setting TextView value to a String got from Intent

So... My problem is that when I try to send Intent putExtra , get it in the new class and then put it into a TextView it returns null...
Here is my code:
final String phonenum = text.getText().toString();
Intent i = new Intent(sms_verification.this, sms_verification_two.class);
i.putExtra("num", num);
i.putExtra("phonenum" , phonenum);
startActivity(i);
And then the "sms_verification_two"
Button next;
EditText code;
TextView phone;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sms_verification2);
next = (Button)findViewById(R.id.button);
code = (EditText)findViewById(R.id.editText2);
phone = (TextView)findViewById(R.id.textView);
String phonenum = getIntent().getStringExtra("phonenum");
String num = getIntent().getStringExtra("num");
phone.setText(phonenum);
Try using this approach on your sms_verification_two activity
String phonenum = "";
String num = "";
Bundle extras = getIntent().getExtras();
if (extras != null) {
phonenum = extras.getString("phonenum");
num = extras.getString("num");
}
phone.setText(phonenum + num);
Make sure the data you put in the intent isn't null. The code itself looks fine to me.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button goToNextActivity=(Button) findViewById(R.id.bSendID);
final EditText etNum=(EditText) findViewById(R.id.etNumID);
final EditText etPhoneum=(EditText) findViewById(R.id.etPhoneumID);
goToNextActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textFromEtNum=etNum.getText().toString();
String textFromEtPhoneum=etPhoneum.getText().toString();
Intent i = new Intent(getApplicationContext(), secondActivity.class);
i.putExtra("num", textFromEtNum);
i.putExtra("phonenum" , textFromEtPhoneum);
startActivity(i);
}
});
}
}
second activity:
public class secondActivity extends AppCompatActivity {
Button next;
EditText code;
TextView phone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
next = (Button)findViewById(R.id.button);
code = (EditText)findViewById(R.id.editText2);
phone = (TextView)findViewById(R.id.textView);
String phonenum = getIntent().getStringExtra("phonenum");
String num = getIntent().getStringExtra("num");
phone.setText(phonenum + " " + num);
}
}
First Activity
**if your text variable TextView or EditText then write**
String phonenum = text.getText().toString();
Intent i = new Intent(sms_verification.this, sms_verification_two.class);
i.putExtra("nums", num);
i.putExtra("phonenums" , phonenum);
startActivity(i);
Second Activity
public class sms_verification_two extends AppCompatActivity {
Button next;
EditText code;
TextView phone;
String phonenumss = "",numss = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
next = (Button)findViewById(R.id.button);
code = (EditText)findViewById(R.id.editText2);
phone = (TextView)findViewById(R.id.textView);
if(getIntent().getStringExtra("phonenums") != null){
phonenumss = getIntent().getStringExtra("phonenums");
}
if(getIntent().getStringExtra("nums") != null){
numss = getIntent().getStringExtra("nums");
}
phone.setText(" " +phonenumss + " " + numss);
}
}

Passing value from one activity to another doesn't work

I tried looking on other questions but nothing seems to work. Trying to pass the value stored in sUsername from activity Username.java to MainActivity.java (username).
This is Username.java:
public class Username extends ActionBarActivity implements View.OnClickListener {
EditText eUsername;
Button login;
String sUsername;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_username);
eUsername = (EditText) findViewById (R.id.username);
sUsername = eUsername.getText().toString();
login = (Button)findViewById(R.id.login);
login.setOnClickListener(this);
}
private void loginClick() {
Intent intent = new Intent(this, MainActivity.class );
intent.putExtra("containsUsername", sUsername); //first argument is the name of the string being passed
startActivity(intent);
}
public void onClick (View v) {
switch (v.getId()) {
case R.id.login:
loginClick();
break;
}
}
and this is MainActivity.java
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String username = bundle.getString("containsUsername");
WebView listOfSongs = (WebView) findViewById (R.id.webview);
String url = "http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user="+username+"&api_key=68f82cd7b37e7b23800c2025066531c9&format=json";
listOfSongs.loadUrl(url);
}
your loginCheck Method should be like this:
private void loginClick() {
sUsername = eUsername.getText().toString();
Intent intent = new Intent(this, MainActivity.class );
intent.putExtra("containsUsername", sUsername); //first argument is the name of the string being
startActivity(intent);
}
As in on create your edittext might be empty.
Please check your edittext is empty or not. Chnage your method longClick.
private void loginClick(){
if(!sUsername.isEmpty()) {
Intent intent = new Intent(this, MainActivity.class );
intent.putExtra("containsUsername", sUsername);
startActivity(intent);
} else {
Toast.makeText(Username.this, "Please enter username.", Toast.LENGTH_LONG).show();
}
}

sharedpreferences not storing data in android

sharedpreferences does not store data. Error shows in getSharedPreferences this method. Error is in DetailPref key. And catlog error is : Unable to start activity ComponentInf com.example.add_fetch_data.MainActivity java.lang.NullPointerException. please any one help me what to do to store data Because I am new in Android.
public class MainActivity extends Activity {
Button addData, viewData, saveData, fetchData;
EditText editName, editAdd;
TextView textName, textAdd;
Dialog AddDialog, ViewDialog;
SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("DetailPref", MODE_PRIVATE);
addData = (Button) findViewById(R.id.btn_add_data);
addData.setOnClickListener(new View.OnClickListener() {
String name, address;
#Override
public void onClick(View arg0) {
AddDialog = new Dialog(MainActivity.this);
AddDialog.setContentView(R.layout.add_fragment);
AddDialog.setTitle("Enter Details");
editName = (EditText) findViewById(R.id.ed_ad_name);
editAdd = (EditText) findViewById(R.id.ed_ad_add);
saveData = (Button) findViewById(R.id.save_data);
saveData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
name = editName.getText().toString();
address = editAdd.getText().toString();
SharedPreferences.Editor edit = pref.edit();
// Storing data using SharedPreferences
edit.putString("Name", name);
edit.putString("Address", address);
edit.commit();
AddDialog.dismiss();
}
});
AddDialog.show();
}
});
}
}
Try edit.apply() instead of commit().
Please clear your sharedPreferences first to test. You can do this with code or in application settings
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
editor.commit();
And, you are using 3 different tags. "Name", "Address" and "DetailPref":
FIRST OPTION
You need to save all in DetailPref.
Maybe you need a structure for this. Something like this
{"Name": "xxxxx" , address: "home"}
So you can do this:
#Override
public void onClick(View arg0) {
name = editName.getText().toString();
address = editAdd.getText().toString();
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPref.edit();
JSONObject jsonToSave = new JSONObject();
jsonToSave.put("Name", name);
jsonToSave.put("Address", address);
// Storing data using SharedPreferences
edit.putString("DetailPref", jsonToSave.toString());
edit.commit();
AddDialog.dismiss();
}
SECOND OPTION
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefName = getSharedPreferences("Name", MODE_PRIVATE);
prefAddress = getSharedPreferences("Address", MODE_PRIVATE);
addData = (Button) findViewById(R.id.btn_add_data);
addData.setOnClickListener(new View.OnClickListener() {
String name, address;
#Override
public void onClick(View arg0) {
AddDialog = new Dialog(MainActivity.this);
AddDialog.setContentView(R.layout.add_fragment);
AddDialog.setTitle("Enter Details");
editName = (EditText) findViewById(R.id.ed_ad_name);
editAdd = (EditText) findViewById(R.id.ed_ad_add);
saveData = (Button) findViewById(R.id.save_data);
saveData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
name = editName.getText().toString();
address = editAdd.getText().toString();
SharedPrefearences.Editor editName = prefName.edit();
SharedPreferences.Editor editAddress = prefAddress.edit();
// Storing data using SharedPreferences
editName.putString("Name", name);
editAddress.putString("Address", address);
editName.commit();
editAddress.commit();
AddDialog.dismiss();
}
});
AddDialog.show();
}
});

Categories