Unable to get string from a Bundle - java

I created a new Activity once a Login is successful. But when I start the app, the app crash within 5 seconds with the message
Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
Error is coming from this
name.setText(" "+bundle.getString("name"));
public class LoginActivity extends Activity {
public ImageView bgLogo;
Button login_button;
EditText Username, Password;
String username, password;
String login_url = "http://192.168.0.19/login.php";
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Enlever la barre bleue
setContentView(R.layout.activity_login);
initExit ();
builder = new AlertDialog.Builder(LoginActivity.this);
login_button = (Button) findViewById(R.id.bLogin);
Username = (EditText) findViewById(R.id.etUsername);
Password = (EditText) findViewById(R.id.etPassword);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = Username.getText().toString();
password = Password.getText().toString();
if (username.equals("") || password.equals("")) {
builder.setTitle("Mince une erreur...");
displayAlert("Veuillez entrer un username et un mot de passe correct...");
}
else {
StringRequest stringRequest = new StringRequest(Request.Method.POST, login_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
if (code.equals("login_failed")) {
builder.setTitle("Erreur d'authentification");
displayAlert(jsonObject.getString("message"));
}
else {
Intent intent = new Intent (LoginActivity.this, UserAreaActivity.class);
Bundle bundle = new Bundle();
bundle.putString("name", jsonObject.getString("name"));
intent.putExtras(bundle);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Erreur", Toast.LENGTH_LONG).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map <String, String> params = new HashMap<String, String>();
params.put("user_name", username);
params.put("password", password);
return params;
}
};
MySingleton.getInstance(LoginActivity.this).addToRequestque(stringRequest);
}
}
});
}
private void initExit() {
bgLogo = (ImageView) findViewById(R.id.bgLogo1);
bgLogo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent (LoginActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
public void displayAlert (String message) {
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Username.setText("");
Password.setText("");
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
#Override
public void onBackPressed() {
// do nothing.
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
return;
}
}
public class UserAreaActivity extends Activity {
public ImageView bgNet;
public ImageView bgChat;
public ImageView bgStats;
public ImageView bgGo;
public Button bLogout;
TextView name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Enlever la barre bleue
setContentView(R.layout.activity_user_area);
name = (TextView) findViewById(R.id.name);
Bundle bundle = getIntent().getExtras();
name.setText(" "+bundle.getString("name"));
initGoHome ();
initPlay ();
initGoStats ();
initGoChat ();
buttonLogout ();
}
#Override
public void onBackPressed() {
return;
}
private void initGoHome () {
bgNet = (ImageView) findViewById(R.id.bgNet);
bgNet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent (UserAreaActivity.this, HomeActivity.class);
startActivity(intent);
}
});
}
private void initPlay () {
bgGo = (ImageView) findViewById(R.id.bgGo);
bgGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent (UserAreaActivity.this, PlayActivity.class);
startActivity(intent);
}
});
}
private void initGoStats () {
bgStats = (ImageView) findViewById(R.id.bgStats);
bgStats.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent (UserAreaActivity.this, StatsActivity.class);
startActivity(intent);
}
});
}
private void initGoChat () {
bgChat = (ImageView) findViewById(R.id.bgChat);
bgChat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent (UserAreaActivity.this, ChatActivity.class);
startActivity(intent);
}
});
}
private void buttonLogout () {
bLogout = (Button) findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent (UserAreaActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}

Replace this code snippet:
Bundle bundle = getIntent().getExtras();
name.setText(" "+bundle.getString("name"));
with
Bundle bundle = getIntent().getExtras();
if (bundle != null)
{
name.setText(" "+bundle.getString("name"));
}
Your problem will be solved.

Attempt to invoke virtual method 'java.lang.String
android.os.Bundle.getString(java.lang.String)' on a null object
reference
Well, you need to avoid calling a method on a null object. In your case:
name.setText(" "+bundle.getString("name"));
The bundle is a null object in this case. So it throws an error.
The solution to avoid this crash is to add a if/else statement
if (bundle != null)
// set text for name like what you have done
else
// set a default text for name
But, I suggest it's better to check your code and understand why your bundle is getting null.

The code is resolved for me by typing
in Activity where you get the value by bundle
Bundle bundle = getIntent().getExtras();
hName = bundle.getString("sharedName");
b1 =new Bundle(); //this b1 should be declared Globally where you are getting value
b1.putString("sharedName",hName);

Replace this code snippet:
"class".with(getActivity())
.using(Album.class)
.bucketId(Application.getBucketId())
.entityId(getArguments().getString(YourActivity.GALLERY_ID))
.retrieve(new XXXX()); Change code : Use Bundle method To replace code below type Bundle bundle = getArguments();
"example".with(getActivity())
.using(Album.class)
.bucketId(Application.getBucketId())
.entityId(bundle.getString(YourActivity.GALLERY_ID))
.retrieve(new XXXX());

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

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

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

Click countries name and save opened Activity, every time open app , show to last selected countries activity, i want to add change the countries

There is a lot of countries in this app including India, Pakistan, UAE, South Africa..etc. When clicking on name of a country, a new activity will be opened. It will be saved by share preference and when we open the app, the last activity will be opened. I created an app like this. I want to add one more thing to this app.
I want to go to countries list view by a button from the opened activity. The user can change the country here and when opening the app, the changed country's activity must be opened. If all countries are opened like this, there must be a option for choosing another country. I hope you will do this for me.
The project code which is done by me is given below.
The share preference will work on it. I want an option to change the country option.
** countries Listview (MainActivity)**
public class MainActivity extends AppCompatActivity {
CardView ind,pak,uae,south;
String clickedCard;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
ind = (CardView) findViewById(R.id.ind);
pak = (CardView) findViewById(R.id.pak);
ind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent CltButton = new Intent(MainActivity.this, India.class);
clickedCard = "Button 1";
CltButton.putExtra("fromMain", clickedCard);
startActivity(CltButton);
}
});
pak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton = new Intent(MainActivity.this,Pak .class);
clickedCard = "Button 2";
mgButton.putExtra("fromMain2", clickedCard);
startActivity(mgButton);
}
});
}
private void checkPreferences() {
////INDIA Preference
prefs = getSharedPreferences("pref", MODE_PRIVATE);
if (prefs.getString("txt", "").equals("") || prefs.getString("lastActivity", "").equals("")) {
} else {
String txt = prefs.getString("txt", "");
String activity = prefs.getString("lastActivity", "");
Intent CltButton = new Intent(MainActivity.this, India.class);
CltButton.putExtra("fromMain", txt);
startActivity(CltButton);
finish();
}
////PAKISTAN Preference
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
if (prefs.getString("txt2", "").equals("") || prefs.getString("lastActivity2", "").equals("")) {
} else {
String txt2 = prefs.getString("txt2", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton =MainActivity new Intent(MainActivity.this, Pak.class);
mgButton.putExtra("fromMain2", txt2);
startActivity(mgButton);
finish();
}
}
}
India Activity code
public class India extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonind;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_india);
buttonind = (Button) findViewById(R.id.buttonind);
buttonind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton = new Intent(India.this, Main2Activity.class);
startActivity(mgButton);
}
});
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain");
}
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt", s);
editor.putString("lastActivity", getClass().getName());
editor.apply();
}
}
Pak Activity Code
public class Pak extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonpak;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pak);
buttonpak = (Button) findViewById(R.id.buttonpak);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain2");
}
buttonpak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton1 = new Intent(Pak.this, Main2Activity.class);
startActivity(mgButton1);
}
});
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt2", s);
editor.putString("lastActivity2", getClass().getName());
editor.apply();
}
}
You are very welcome for this - It took me some time to do and it is working exactly like you want it to.
MainActivity:
public class MainActivity extends AppCompatActivity {
CardView ind,pak,uae,south;
String clickedCard;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
ind = (CardView) findViewById(R.id.ind);
pak = (CardView) findViewById(R.id.pak);
uae = (CardView) findViewById(R.id.uae);
south = (CardView) findViewById(R.id.south);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle!= null) {
SharedPreferences preferences,preferences1,preferences2,preferences3,preferences4;
SharedPreferences.Editor editor,editor1,editor2,editor3,editor4;
preferences = getSharedPreferences("pref", Context.MODE_PRIVATE);
editor = preferences.edit();
editor.clear();
editor.apply();
preferences1 = getSharedPreferences("pref1", Context.MODE_PRIVATE);
editor1 = preferences1.edit();
editor1.clear();
editor1.apply();
preferences2 = getSharedPreferences("pref2", Context.MODE_PRIVATE);
editor2 = preferences2.edit();
editor2.clear();
editor2.apply();
preferences3 = getSharedPreferences("pref3", Context.MODE_PRIVATE);
editor3 = preferences3.edit();
editor3.clear();
editor3.apply();
preferences4 = getSharedPreferences("pref4", Context.MODE_PRIVATE);
editor4 = preferences4.edit();
editor4.clear();
editor4.apply();
} else {
checkPreferences();
}
//checkPreferences();
ind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent CltButton = new Intent(MainActivity.this, India.class);
clickedCard = "Button 1";
CltButton.putExtra("fromMain", clickedCard);
startActivity(CltButton);
finish();
}
});
pak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton = new Intent(MainActivity.this,Pak.class);
clickedCard = "Button 2";
mgButton.putExtra("fromMain2", clickedCard);
startActivity(mgButton);
finish();
}
});
uae.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent keraButton = new Intent(MainActivity.this, Uae.class);
clickedCard = "Button 3";
keraButton.putExtra("fromMain3", clickedCard);
startActivity(keraButton);
finish();
}
});
south.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ButtonactivityIntent = new Intent(MainActivity.this, South.class);
clickedCard = "Button 4";
ButtonactivityIntent.putExtra("fromMain4", clickedCard);
startActivity(ButtonactivityIntent);
finish();
}
});
}
private void checkPreferences() {
////INDIA Preference
prefs = getSharedPreferences("pref", MODE_PRIVATE);
if (prefs.getString("txt", "").equals("") || prefs.getString("lastActivity", "").equals("")) {
} else {
String txt = prefs.getString("txt", "");
String activity = prefs.getString("lastActivity", "");
Intent CltButton = new Intent(MainActivity.this, India.class);
CltButton.putExtra("fromMain", txt);
startActivity(CltButton);
finish();
}
////PAKISTAN Preference
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
if (prefs.getString("txt2", "").equals("") || prefs.getString("lastActivity2", "").equals("")) {
} else {
String txt2 = prefs.getString("txt2", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton = new Intent(MainActivity.this, Pak.class);
mgButton.putExtra("fromMain2", txt2);
startActivity(mgButton);
finish();
}
////U A E Preference
prefs = getSharedPreferences("pref3", MODE_PRIVATE);
if (prefs.getString("txt3", "").equals("") || prefs.getString("lastActivity3", "").equals("")) {
} else {
String txt2 = prefs.getString("txt3", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton = new Intent(MainActivity.this, Uae.class);
mgButton.putExtra("fromMain3", txt2);
startActivity(mgButton);
finish();
}
//// SOUTH AFRICA Preference
prefs = getSharedPreferences("pref4", MODE_PRIVATE);
if (prefs.getString("txt4", "").equals("") || prefs.getString("lastActivity4", "").equals("")) {
} else {
String txt2 = prefs.getString("txt4", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton = new Intent(MainActivity.this, South.class);
mgButton.putExtra("fromMain4", txt2);
startActivity(mgButton);
finish();
}
}
}
India.java:
public class India extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonind;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_india);
buttonind = (Button) findViewById(R.id.buttonind);
buttonind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = "";
Intent mgButton2 = new Intent(India.this, MainActivity.class);
mgButton2.putExtra("test", test);
startActivity(mgButton2);
finish();
}
});
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain");
}
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt", s);
editor.putString("lastActivity", getClass().getName());
editor.apply();
}
}
Pakistan.java
public class Pak extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonpak;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pak);
buttonpak = (Button) findViewById(R.id.buttonpak);
buttonpak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = "";
Intent mgButton2 = new Intent(Pak.this, MainActivity.class);
mgButton2.putExtra("test", test);
startActivity(mgButton2);
finish();
}
});
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain2");
}
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt2", s);
editor.putString("lastActivity2", getClass().getName());
editor.apply();
}
}
You can repeat the process for all the other countries. In MainActivity where I check if (bundle!= null) can be simplified, but it is working.

How to pass data from activity to another activity on Android

I want to pass data from my Login Page to My Detail Page. However the Detail Page cannot accept the data because the String sent in Login Page has null value on Detail Page.
This is my Login Page Code:
public class MainActivity extends AppCompatActivity {
EditText editText, editText1;
Button button;
int success = 0;
ProgressDialog progressDialog;
JSONObject jsonObject;
HTTPURLConnection service;
String strname ="", strpass="";
String response;
String path = "http://sumbanggagasan.890m.com/select2.php";
Intent intent;
DetailGagasanku detailGagasanku;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.nik);
editText1 = (EditText) findViewById(R.id.pass);
button = (Button) findViewById(R.id.signin);
service = new HTTPURLConnection();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!editText.getText().toString().equals("") && !editText1.getText().toString().equals("")){
strname = editText.getText().toString();
strpass = editText1.getText().toString();
response = null;
new PostDataTOServer().execute();
} else{
Toast.makeText(getApplicationContext(), "Please Enter all fields", Toast.LENGTH_LONG).show();
}
}
});
}
private class PostDataTOServer extends AsyncTask<Void, Void, Void> {
//Create hashmap Object to send parameters to web service
HashMap<String, String> postDataParams;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postDataParams=new HashMap<String, String>();
postDataParams.put("NIK", strname);
postDataParams.put("pass", strpass);
//Call ServerData() method to call webservice and store result in response
response= service.ServerData(path,postDataParams);
try {
System.out.println(response + "menu");
jsonObject = new JSONObject(response);
//Get Values from JSONobject
System.out.println("success=" + jsonObject.get("successs"));
//success = jsonObject.getInt("success");
success = Integer.parseInt(jsonObject.getString("successs").trim());
System.out.println("Do in");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
System.out.println("Post 1");
System.out.println(strname);
if (progressDialog.isShowing()) {
System.out.println("Post 2");
System.out.println(strpass);
progressDialog.dismiss();
}
if(success==1) {
//Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
Intent intent;
Bundle b;
b = new Bundle();
b.putString("username", strname);
intent = new Intent(getApplicationContext(), LandingPage.class);
intent.putExtras(b);
startActivity(intent);
} else{
Toast.makeText(getApplicationContext(), "Login gagal", Toast.LENGTH_LONG).show();
}
}
}
And this is my Details code:
public class DetailGagasanku extends AppCompatActivity {
TextView judul, manfaat;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_gagasanku);
judul = (TextView)findViewById(R.id.textJudul);
manfaat = (TextView) findViewById(R.id.textManfaat);
bundle = getIntent().getExtras();
judul.setText(bundle.getString("judul_gagasan"));
if (bundle != null) {
if(bundle.containsKey("username"))
{
String s = bundle.getString("username");
manfaat.setText(s);
}
else
{
System.out.println("not send");
}
}
}
}
I want to ask why that username has null value. For your information, that "judul_gagasan" variable can receive value from another activity. I send it from My Adapter.
this is my Adapter code:
public class GagasanAdapter extends RecyclerView.Adapter<GagasanAdapter.GagasanHolder> {
List<String> gagasanList = new ArrayList<>();
public GagasanAdapter(List<String> gagasanList) {
this.gagasanList = gagasanList;
Log.v("gagasanSize", "" + gagasanList.size());
}
#Override
public GagasanHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_gagasan, parent, false);
return new GagasanHolder(v);
}
#Override
public void onBindViewHolder(final GagasanHolder holder, final int position) {
Log.v("Gagasan[" + position + "]", gagasanList.get(position));
String item = gagasanList.get(position);
holder.judulGagasan.setText(item);
holder.judulGagasan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DetailGagasanku.class);
intent.putExtra("judul_gagasan", holder.judulGagasan.getText().toString());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return gagasanList.size();
}
public class GagasanHolder extends RecyclerView.ViewHolder{
TextView judulGagasan;
public GagasanHolder(View itemView) {
super(itemView);
judulGagasan = (TextView) itemView.findViewById(R.id.tvListGagasan);
}
}
}
You pass "username" in Bundle to LandingPage Activity, so you can't access in DetailGagasanku Activity.
So to access "username" in DetailGagasanku Activity, pass username from adapter.

Using Conditions to Pass Data between Activities

Successfully I tried to pass data between three Activities.
That is :
(Data3)Activity1(Data1)-->(Data1)Activity2(Data2)-->(Data2)Activity3)
Now the Problem is:
I want pass to data between these activities using conditions. That
is in Activity2, before sending data to Activity3 I want to check
WORD = "word building"
DROP = "word built"
if WORD FROM EDITTEXT == WORD
pass data to Activity1 AND
goto Activity1
else
if WORD FROM EDITTEXT == DROP
pass data to Activity3 AND
goto Activity3
Here is the code for Activity1 named PickCard.java
public class PickCard extends Activity {
String card = "Card Picked";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayIntentData();
findViewById(R.id.sendButton).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(PickCard.this, BuildWord.class);
intent.putExtra("key", card);
startActivity(intent);
}
});
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);//must store the new intent unless getIntent() will return the old one
displayIntentData();
}
private void displayIntentData() {
Intent intent = getIntent();
TextView tv = (TextView) findViewById(R.id.intentData);
Bundle extras = intent.getExtras();
if (extras != null) {
tv.setText("Data received: " + extras.getString("key"));
} else {
tv.setText("No extradata received");
}
}
}
Here is the code for Activity2 BuildWord.java
public class BuildWord extends Activity {
String word = "Word Building";
String finished = "Word Built";
EditText simulate = (EditText) findViewById(R.id.dataToSend);
String getdata = simulate.getText().toString();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buildword);
displayIntentData();
if (getdata == word) {
findViewById(R.id.sendButton1).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(BuildWord.this, MainActivity.class);
intent.putExtra("key", getdata);
startActivity(intent);
}
});
} else {
findViewById(R.id.sendButton1).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(BuildWord.this, DropCard.class);
intent.putExtra("key", finished);
startActivity(intent);
}
});
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
displayIntentData();
}
private void displayIntentData() {
Intent intent = getIntent();
TextView tv = (TextView) findViewById(R.id.intentData1);
Bundle extras = intent.getExtras();
if (extras != null) {
tv.setText("Data received: " + extras.getString("key"));
} else {
tv.setText("No extradata received");
}
}
}
Here is the code for Activity3 named DropCard.java
public class DropCard extends Activity {
String drop = "Card Dropped";
String declared = "User Declared";
boolean won = false;
/*Intent intent = getIntent();
TextView tv = (TextView)findViewById(R.id.intentData2);
Bundle extras=intent.getExtras();*/
String get = "word building";//extras.getString("key");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dropcard);
displayIntentData();
if (get == "word built") {
findViewById(R.id.sendButton2).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(DropCard.this, Declare.class);
intent.putExtra("key", declared);
startActivity(intent);
}
});
} else {
findViewById(R.id.sendButton2).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(DropCard.this, MainActivity.class);
intent.putExtra("key", drop);
startActivity(intent);
//notice we dont call finish() here
}
});
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);//must store the new intent unless getIntent() will return the old one
displayIntentData();
}
private void displayIntentData() {
Intent intent = getIntent();
TextView tv = (TextView) findViewById(R.id.intentData2);
Bundle extras = intent.getExtras();
if (extras != null) {
tv.setText("Data received: " + extras.getString("key"));
} else {
tv.setText("No extradata received");
}
}
}
use
if (getdata.equals(word)){
}
instead of
if (getdata == word){
}
for comparing Strings.as in your current code replace all == with equals
if (getData.getText().toString().equalsIgnoreCase("String name"))//change this line in your code for checking
{
findViewById(R.id.sendButton1).setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(BuildWord.this,MainActivity.class);
intent.putExtra("key", getdata);
startActivity(intent);
}
});
}
else
{
findViewById(R.id.sendButton1).setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(BuildWord.this,DropCard.class);
intent.putExtra("key", finished);
startActivity(intent);
}
});
}
Its a simple you have to compare in that default method equalsIgnoreCase().
String name = edit_text.getText().toString();
if(name.equalsIgnoreCase("WellCome"))
{
//CALL YOUR ACTIVITY ONE
}
else
{
//CALL YOUR ACTIVITY THREE
}

Categories