My app requires a username to be added to function properly.
The mainActivity displays the username on the top which it retrieves form the database.
The mainActivity also has a button which leads to 'addusername' activity through startActivityForResult() method; when the user actually enters a username then only username on the main activity gets refreshed and displayed.
There is a submit button on the 'addusername' activity which adds the username and does setResult(RESULT_OK);
Everything works fine if the username is entered by clicking the 'addusername' button.
Now, I have added a dialogue in mainActivity which gets displayed when the app starts only if no username exists on the database. The dialogue gives an option to add username, which if clicked, leads to the 'addusername' activity. But upon pressing the 'submit' button the mainActivity does get called but the username is not refreshed (though, the database does get updated)
Here is the code for 'addusername' activity:
public void submitusername(View view) {
userdatabase name = new userdatabase(this);
name.open();
String user = name.getusername();
name.close();
EditText cinone = (EditText) findViewById(R.id.username);
username = cinone.getText().toString();
if(user.equals("")) {
userdatabase entry = new userdatabase(Editprofile.this);
entry.open();
entry.createEntry(username, null, null, null);
entry.close();
Context context = getApplicationContext();
CharSequence text = "Added new user!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else {
userdatabase update = new userdatabase(Editprofile.this);
update.open();
update.updateUsername(username);
update.close();
Context context = getApplicationContext();
CharSequence text = "Username updated!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
setResult(RESULT_OK);
finish();
}
Here is the code for Dialog:
public class NouserFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.nouseralert)
.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getActivity().getBaseContext(), Editprofile.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.ignore, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
I understand this is happening because the Dialog does not call startActivityForResult() method. But even if I change my code, like this:
Intent intent = new Intent(getActivity().getBaseContext(), Editprofile.class);
startActivityForResult(intent, 0);
It still does not help. Probably because, onActivityResult() method does not lie in the same class from which startActivityForResult() has been called, but I don't know how to get after that.
EDIT 1: Tried using
Intent intent = new Intent(getActivity(), Editprofile.class);
startActivityForResult(intent, 0);
No use.
Have you tried this way:
Intent intent = new Intent(getActivity(), Editprofile.class);
startActivityForResult(intent, 0);
When you create your the Intent object you use the BaseContext, instead of using the reference to the activity itself.
Using
Intent intent = new Intent(getActivity(), Editprofile.class);
getActivity().startActivityForResult(intent, 0);
worked!
Related
I have a LoginActivity that is not tied to any online database, I only validate the username via edit text component to login and move to the MainActivity. LoginActivity appears when the value of text in MainActivity is null, therefore I created a validation method when the username is null, then the layout will move to LoginActivity, I made it like this with the aim that LoginActivity does not become the main layout of the app.
Validation users in MainActivity.java:
private void checkUsername() {
Intent intent = getIntent();
if(intent.getExtras() != null){
String users = intent.getStringExtra(LoginActivity.EXTRA_USER);
txuser.setText(users);
//NullPointerException: Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert(java.lang.String)
ContentValues cv = new ContentValues();
cv.put(Contract.UserEntry.NAME_COLUMN,users);
database.insert(Contract.UserEntry.TABLE_NAME,null,cv);
} else {
startActivity(new Intent(this, LoginActivity.class));
}
}
LoginActivity.java
private void loginUser() {
final String username;
username = user.getText().toString();
if (TextUtils.isEmpty(username)) {
Toast.makeText(this, "Name cannot be blank!", Toast.LENGTH_SHORT).show();
}
if (!cbAgree.isChecked()) {
Toast.makeText(this, "Login fails!", Toast.LENGTH_SHORT).show();
}
fabLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, UtamaActivity.class);
intent.putExtra(EXTRA_USER, username);
startActivity(intent);
}
});
}
How do I fix this?, because when I open the app for the first time, the LoginActivity is successfully displayed, but when I enter to MainActivity it immediately forces close. I have included the logcat comment in the checkUsername() method
Change Intent intent = new Intent(LoginActivity.this, UtamaActivity.class);
to Intent intent = new Intent(LoginActivity.this, MainActivity.class);
I have Activity1, Activity1 Adapter and Activity2
I'm not able to pass value between an Adapter and Activity. When back button is pressed, I'm expecting a value to be coming from the Second Activity (Activity 2) to Activity1 Currently, it gives me null
Here are my code snippets.
Activity1 Adapter
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Activity origin = (Activity) context;
Intent intent = new Intent(context, PostActivity.class);
intent.putExtra("searchText", staggeredCustomCard.getSearchText());
origin.startActivityForResult(intent, 1);
}
});
Activity2
#Override
public void onBackPressed() {
super.onBackPressed();
Intent mIntent = new Intent();
mIntent.getStringExtra("searchText");
setResult(1, mIntent);
}
I'm expecting this searchText to be going to Activity1. Could anyone please guide me how to achieve this?
You are getting getStringExtra("searchText"); from a completely new intent, that's why it's returning null. You need to get search text from getIntent() like this:
#Override
public void onBackPressed() {
super.onBackPressed();
Intent mIntent = new Intent();
String search = getIntent().getStringExtra("searchText");
mIntent.putExtra("searchText", search);
setResult(1, mIntent);
}
I have 2 EditTexts. EditText1 is in MainActivity, EditText2 is in SecondActivity.
EditText1 is to login (password), EditText2 is to change password.
My code looks like this:
EditText editText1 = findViewById(R.id.login);
editText2 = findViewById(R.id.changePassword); // declared in SecondActivity
if (editText1.getText().toString().equals(editText2.getText().toString())
{
Intent intent = new Intent (MainActivity.this, SecondActivity.class);
startActivity(intent);
}
else
{
Toast.makeText(MainActivity.this, "Password incorrect", Toast.Length_Long).show;
}
When I press Button to login, it shows me an error. I know it has to be initialized in a different way but how?
I tried another code with a Dialog and everything worked perfectly:
changePasswordDialog = new Dialog(MainActivity.this);
changePasswordDialog.setContentView(R.layout.activity_second_activity);
editText2 = changePasswordDialog.findViewById(R.id.changePassword);
So it works perfectly with Dialog, but how does it work without Dialog?
Try Like this
Store edit text 2 pass
String pass = editText2.getText().toString().trim();
SharedPreferences.Editor editor = getSharedPreferences(My_Prefs,Context.MODE_PRIVATE).edit();
editor.putString("pass", pass);
editor.apply();
Now Retrive the stored passwod in MainActivity
SharedPrefrences prefrences = getSharedPrefrences(My_Prefs,Context.MODE_PRIVATE);
String pass = prefrences.getString("pass","");
if (editText1.getText().toString().equals(pass)
{
Intent intent = new Intent (MainActivity.this, SecondActivity.class);
startActivity(intent);
}
You can use intent put extra and intent get extra for this
/// you can use this as per your requirement or you can use sharedprefrence///
// In main activity ///
Intent intent = new Intent (MainActivity.this, SecondActivity.class);
intent.putExtra("editText1",editText1.getText().toString());
startActivity(intent);
/// In second activity//
String passWord = getIntent().getExtras().getString("editText1");
Log.d("password : ",passWord);
I want to transfer my "result" data from my first (Main) acitivity to
my Custaddress activity, which has edit texts for customer details, and then this is sent to an email. The email/edit texts work perfectly - but I want to
add in "result.toString" into email body string. How do I transfer "result" to the second activity? I believe its something to do with arg?
Here's my code from first activity..
DecimalFormat decimalFormat = new DecimalFormat(COMMA_SEPERATED);
result.append("\nTotal: £"+decimalFormat.format(totalamount));
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setMessage(result.toString());
alertDialogBuilder.setTitle("YOUR ORDER");
alertDialogBuilder.setPositiveButton("Accept",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
//do what you want to do if user clicks ok
//Intent intent = new Intent(context, Custaddress.class);
// startActivity(intent);
Intent custaddress = new Intent(getApplicationContext(),com.example.frytest.Custaddress.class);
startActivity(custaddress);
}
});
alertDialogBuilder.setNegativeButton("Decline",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do what you want to do if user clicks cancel.
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
Write it in activity that passing data
Intent custaddress = new Intent(getApplicationContext(),com.example.frytest.Custaddress.class);
custaddress.putExtra("key",value);
startActivity(custaddress);
Write below code in activity that catching data
Intent intent=getIntent();
String mString=intent.getStringExtra("key");
hope this will help you
You should use intent (click here) :
Intent intent = new Intent(getBaseContext(), CustAdrresActivity.class);
intent.putExtra("text", mytext);
startActivity(intent);
You just need to replace your lines:
Intent custaddress = new Intent(getApplicationContext(),com.example.frytest.Custaddress.class);
startActivity(custaddress);
with these three lines:
Intent custaddress = new Intent(getApplicationContext(),com.example.frytest.Custaddress.class);
custaddress.putExtra("result", result.toString());
startActivity(custaddress);
and then, when you open the new activity (in your case the Custaddress Activity), you should do the following to get your result
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("result");
}
You should add Extra in the Intent object which you are passing in the startActivity(intent) method.
Example
String value = "String i want to send to next activity"
Intent intent = new Intent(getApplicationContext(),com.example.frytest.Custaddress.class);
intent.putExtra("KEY", value);
startActivity(intent);
In the Custaddress.java Activity class you need to get the data from the Bundle object that you get as a parameter in the onCreate(Bundle bundle) method
Bundle extras = getIntent().getExtras();
if (extras != null) {
// get data via the key
String valueFromPreviousActivity = extras.getString("KEY");
if(valueFromPreviousActivity != null){
// do something with the data
}
}
Check out this official doc Starting Another Activity.
Through the below code we can send the values between activities
use the below code in parent activity
Intent myintent=new Intent(Info.this, GraphDiag.class).putExtra("<StringName>", value);
startActivity(myintent);
use the below code in child activity
String s= getIntent().getStringExtra(<StringName>);
I'm have one activity with 10 buttons, and transfer info about button clicked to next activity.
View.OnLongClickListener olongBtn = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (v == btn1) {
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", "slot1");
startActivity(intent);
} else if (v == btn2) {
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", "slot2");
startActivity(intent);
} else if (v == btn3) {
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", "slot3");
startActivity(intent);
}
return false;
}
};
btn1.setOnLongClickListener(olongBtn);
btn2.setOnLongClickListener(olongBtn);
btn3.setOnLongClickListener(olongBtn);
}
I want to change it like this
String slot = toString(v);
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", slot);
startActivity(intent);
But when I do it, I get in next activity something like this:
android.widget.Button{6548fcd}VFED..CL...P....17.0-147.130 #7f08004f app:id/btnPayman}
But i'm expectation name of button object.
To get name of clicked button use ((Button)v).getText() method instead of v.toString() which return String representation of calling Object:
String slot = (Button)v).getText().toString();
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", slot);
startActivity(intent);
You can simply send button id.
View.OnLongClickListener olongBtn = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", v.getId());
startActivity(intent);
return false;
}
};
On next Activity, you can use a switch in order to know what Button has been pressed:
int buttonId = getIntent().getIntExtra("slot", 0);
switch() {
case R.id.firstbutton:
//Do what you want
break;
case R.id.secondbutton:
//Do What you whant
}
Sending int is better than sending a String because you can use a switch on the receiver activity which is faster than anidated if/else
-----------------------EDIT----------------------
While you are using include tag in order to compose your layout, you should set a different id to every button (at the same time your are setting Button text). You can also use an Integer as a tag for every button, and send that tag to the next activity (instead of id).
Look about view tags here: View setTag() method
If you want to send the name of the button, try this:
String slot = ((Button) v).getText().toString();
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", slot);
startActivity(intent);
Thanks user pozuelog for solution.
I'm use separate xml files for layout and attach it by include to main_activity.
Result of it, that getId method don't work for me.
solution is set Tag for my buttons.
btn1.setTag(1);
btn2.setTag(2);
btn3.setTag(3);
View.OnLongClickListener olongBtn = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent intent = new Intent(MainActivity.this, AddContact.class);
intent.putExtra("slot", String.valueOf(v.getTag()));
startActivity(intent);
return false;
}
};
btn1.setOnLongClickListener(olongBtn);
btn2.setOnLongClickListener(olongBtn);
btn3.setOnLongClickListener(olongBtn);
I think that solution may be optimize, but I'm googlecoder and leave it as is for this time.