Why is the bundle always null in spite of key being present? - java

The code below is intended to pass the data, using bundle, collected on signing up in Signup.java to ViewProfile.java which displays the data. On checking for a key in the bundle, it returns true, however, the bundle is null when checked in ViewProfile.java. Help will b appreciated.
Signup.java
public class Signup extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
final EditText n=(EditText)findViewById(R.id.editText3);
final EditText u=(EditText)findViewById(R.id.editText4);
final EditText p=(EditText)findViewById(R.id.editText5);
final EditText c=(EditText)findViewById(R.id.editText6);
Button s=(Button)findViewById(R.id.button4);
final Userdatabase udb=new Userdatabase(this);
s.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String name=n.getText().toString();
String email=u.getText().toString();
String password=p.getText().toString();
String phone=c.getText().toString();
boolean b=udb.insertuser(name,email,password);
if(b==true) {
Intent i = new Intent(Signup.this, MainActivity.class);
Bundle bundle=new Bundle();
bundle.putString("NAME",name);
bundle.putString("ID",email);
bundle.putString("PHONE",phone);
i.putExtras(bundle);
startActivity(i);
}
else
Toast.makeText(getApplicationContext(),"Please try again",Toast.LENGTH_SHORT).show();
}
});
}
}
ViewProfile.java
public class ViewProfile extends AppCompatActivity {
String name,username,contact,profession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_profile);
Intent intent=getIntent();
Bundle b=intent.getExtras();
if(b!=null) {
name = b.getString("NAME");
username = b.getString("ID");
contact = b.getString("PHONE");
TextView tv1=(TextView)findViewById(R.id.textView17);
TextView tv2=(TextView)findViewById(R.id.textView18);
TextView tv3=(TextView)findViewById(R.id.textView19);
tv1.setText(name);
tv2.setText(username);
tv3.setText(contact);
}
ImageView img=(ImageView)findViewById(R.id.imageView4);
img.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(ViewProfile.this,Profile.class);
startActivity(i);
}
});
}
}

You are calling the wrong activity in the SignUp activity:
if(b==true) {
Intent i = new Intent(Signup.this, MainActivity.class);//problem here
You have set the intent as MainActivity.class and sending data to MainActivity and not to ViewProfile activity.
Change to this in SignUp activity:
if(b==true) {
Intent i = new Intent(Signup.this, ViewProfile.class);

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

Transferring data from the third activity to the first

From the first activity I would like to go to the second, then from the second to the third. In the third activity I would like to enter the name in EditText, then after pressing the button, go to the first activity and at the same time send the information entered in the third activity.
Unfortunately, after pressing the button in the third activity, instead of returning to the first activity, I return to the second activity. Was the first activity killed? What could I do to ensure that the information is correct for the first activity? This is my code:
First:
public class MainActivity extends AppCompatActivity {
TextView textViewInformation;
Button button_GoToSecond;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewInformation = findViewById(R.id.textView);
button_GoToSecond = findViewById(R.id.button);
button_GoToSecond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Second.class);
startActivity(i);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent i) {
if((requestCode == 1) &&(resultCode == RESULT_OK)) {
String name = i.getStringExtra("name");
textViewInformation.setText(name);
}
}
}
Second:
public class Second extends AppCompatActivity {
Button button_GoToThird;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
button_GoToThird = findViewById(R.id.button2);
button_GoToThird.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Second.this, Third.class);
startActivity(i);
}
});
}
}
Third:
public class Third extends AppCompatActivity {
EditText editText_Data;
Button button_SendData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
editText_Data = findViewById(R.id.editText);
button_SendData = findViewById(R.id.button3);
button_SendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
public void finish() {
String name;
name = editText_Data.getText().toString();
Intent i = new Intent(Third.this, MainActivity.class);
i.putExtra("name", name);
setResult(RESULT_OK, i);
super.finish();
}
}
just remove finish(); thats it
The reason that it goes to the second activity is because of this:
button_SendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
public void finish() {
String name;
name = editText_Data.getText().toString();
Intent i = new Intent(Third.this, MainActivity.class);
i.putExtra("name", name);
setResult(RESULT_OK, i);
super.finish(); //This kills the current activity.
}
You should do:
public void finish() {
String name;
name = editText_Data.getText().toString();
Intent i = new Intent(Third.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("name", name);
startActivityForResult(i, RESULT_OK, bundle);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent i) {
if((requestCode == 1) &&(resultCode == RESULT_OK)) {
Bundle bundle = i.getExtras();
String name = bundle.getString("name");
textViewInformation.setText(name);
}
}
When you call finish, it just kills the current activity. If you want to go back to the first activity, just start a new activity for the first activity and pass the data in a Bundle.
If you want to have more of a stack concept, you can use Fragments.

int/string value becomes "0"/null when passed from one activity to another

I have two activities, MainActivity and SecondActivity. While passing int value from MainActivity to SecondActivity it becomes "0". I have tried with and without bundle, tried various solution already present on StackOverFlow, but no go.
Here is my code:
MainActivity
final Intent intent = new Intent(MainActivity.this, SecondActivity.class);
final TextView textView = findViewById(R.id.textView);
textView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Bundle bundle = new Bundle();
bundle.putInt("category",9);
intent.putExtras(bundle);
startActivity(intent);
}
});
SecondActivity:
package com.example.app;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class SecondActivity extends AppCompatActivity {
ViewPager viewPager;
TabsPagerAdapter pagerAdapter;
private int mMedCategory = 6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// String stringCategory = getIntent().getStringExtra("category_string");
int medCategory = getIntent().getIntExtra("category_int", -1);
setMedCategory(medCategory);
viewPager = findViewById(R.id.viewpager);
pagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
public int getMedCategory(){
return mMedCategory; //This value goes to TabsPagerAdapter
}
public void setMedCategory(int i){
mMedCategory = i;
}
}
You can try this:
MainActivity
TextView textView = findViewById(R.id.textView);
textView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("category_int", 9);
intent.putExtra("category_string", "9");
startActivity(intent);
}
});
SecondActivity
private int medCategoryInt;
private String medCategoryString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
medCategoryInt = getIntent().getIntExtra("category_int", 0);
medCategoryString = getIntent().getStringExtra("category_string");
}
You can have a look at How do I pass data between Activities in Android application?
Use Intent#getIntExtra() to retrieve an integer value from the intent:
From MainActivity:
Intent myIntent = new Intent(MainActivity.this, SecondActivity.class);
myIntent.putExtra("category", 9);
MainActivity.this.startActivity(myIntent);
From SecondActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
medCategory = intent.getIntExtra("category", -1);
}
Note that this would assign a default value of -1 to medCategory in the event that the key cannot be found.
I'm not sure but You may use this for second activity:
SecondActivity secondActivity = new SecondActivity();
if (secondActivity.getIntent.getExtras() != null)
{
int medCat = secondActivity.getIntent.getExtras().getInt("category");
}
Use this code. Remove final and try to initialize intent in onclick method not outside of it.
In your OnClick
Intent intent=new Intent(this,Main2Activity.class);
Bundle bundle = new Bundle();
bundle.putInt("category",9);
intent.putExtras(bundle);
startActivity(intent);
In your second activity
public class Main2Activity extends AppCompatActivity {
private int mMedCategory =0;
public int getmMedCategory() {
return mMedCategory;
}
public void setmMedCategory(int mMedCategory) {
this.mMedCategory = mMedCategory;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Bundle bundle=getIntent().getExtras();
if(bundle!=null){
int demoCategory =bundle.getInt("category");
setmMedCategory(demoCategory);
}else {
Toast.makeText(this, "null", Toast.LENGTH_SHORT).show();
}
}
public void Show(View view) {
Toast.makeText(this, String.valueOf(getmMedCategory()), Toast.LENGTH_SHORT).show();
}
}
EDIT
Created a demo project for you it is working. Show method is onclick method of a button.

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.

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();
}
}

Categories