Intent passing variable malfunction - java

In my app I am trying to provide two functions to the users. One is uploading a post with an image and the other is to upload post without an image. To do so I created Strings nonselected_image and selected_image (or selected_bitmap). In case of pressing one of the TextViews by user one of the strings will be passed within the intent consequently. It works great when user wishes to create non photo post but when he wants to create one with a photo there are two posts emerging, one with photo and the other without. What did I wrong? Here is my code.
Sending an intent and strings to the next activity
TextView nextScreen = (TextView) view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
if (isRootTask()) {
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
startActivity(intent);
} else {
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}
}
});
noPhoto.setOnClickListener(new View.OnClickListener(){
public void onClick (View v) {
mSelectedImage = null;
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.nonselected_image), nonSelectedImage);
startActivity(intent);
}
});
receiving an intent and taking actions accordingly to passed variable
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
//upload the image to firebase
// Toast.makeText(NextActivity.this, "Attempting to upload new photo", Toast.LENGTH_SHORT).show();
String caption = mCaption.getText().toString();
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
Toast.makeText(NextActivity.this, "Attempting to upload a normal photo", Toast.LENGTH_SHORT).show();
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl,null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = (Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap));
Toast.makeText(NextActivity.this, "Attempting to upload a new bitmap", Toast.LENGTH_SHORT).show();
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, null,bitmap);
}
else if(intent.hasExtra(getString(R.string.nonselected_image)));{
Toast.makeText(NextActivity.this, "Attempting to upload new photo", Toast.LENGTH_SHORT).show();
imgUrl = intent.getStringExtra(getString(R.string.nonselected_image));
mFirebaseMethods.uploadNoPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl, null); // HERE IS THE ERROR
}

Related

Check validation and pass value from edit text to move activity

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

startActivityForResult() button crashes

I am trying to link 2 activities (MainActivity and Taskcreation) with a button. I'm expecting a result from the second activity, so I'm using startActivityForResult(), but it keeps on crashing when I'm starting the main activity.
Main activity works properly without the button and the link. Every forum I visit about startActivityForResult state that the problem is about putting MainActivity.this (the context) instead of just this but that's what I have been doing since the beginning. It also obviously doesn't work with this alone.
MainActivity.java button creation/link:
private static final int REQUEST_ADD = 1;
Button AjoutTache = (Button) findViewById(R.id.AjoutTache);
AjoutTache.setOnClickListener( new OnClickListener(){
#Override
public void onClick(View v){
Intent intent = new Intent(MainActivity.this, Taskcreation.class);
startActivityForResult(intent, REQUEST_ADD);
//startActivityForResult(intent, 1);
}
});
Taskcreation.java results:
buttonOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent result = new Intent();
setResult(RESULT_OK, result);
result.putExtra("nom", nomTache.getText().toString());
result.putExtra("statut", statut.isChecked());
result.putExtra("priorite", ((RadioButton) findViewById(priorite.getCheckedRadioButtonId())).getText());
result.putExtra("deadline", deadline.getText().toString());
finish();
}
});
MainActivity.java onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_ADD) {
if (resultCode == RESULT_OK) {
// Create Task
Tache tache = new Tache();
tache.setNom(data.getStringExtra("nom"));
tache.setStatut(data.getBooleanExtra("statut", false));
tache.setPriorite(data.getStringExtra("priorite"));
tache.setDeadline(data.getStringExtra("deadline"));
//mesTaches.add(tache);
// Toast
Toast.makeText(this, "Task added:\n" + tache.toString(), Toast.LENGTH_LONG).show();
// Update listview
}
else if (resultCode == RESULT_CANCELED) {
Log.d("Main", "canceled");
}
}
}
It just crashes when I start the application in the virtual device.
Here is the lastest stack trace:
2019-04-14 17:44:13.694 6009-12813/? E/ctxmgr:
[SyncServerInterestRecordsOperation]Failed WriteInterestRecord: network status=-1 [CONTEXT service_id=47 ]
com.android.volley.VolleyError: Unable to obtain auth token - is the device online?
at eme.a(:com.google.android.gms#16089040#16.0.89 (100700-239467275):31)
at eha.run(:com.google.android.gms#16089040#16.0.89 (100700-239467275):2)
at egy.handleMessage(:com.google.android.gms#16089040#16.0.89 (100700-239467275):3)
at rlu.run(:com.google.android.gms#16089040#16.0.89 (100700-239467275):8)
at rmf.b(:com.google.android.gms#16089040#16.0.89 (100700-239467275):32)
at rmf.run(:com.google.android.gms#16089040#16.0.89 (100700-239467275):21)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at rsc.run(Unknown Source:7)
at java.lang.Thread.run(Thread.java:764)
########## intent.settype("");
use this
public void onClick(View v){
Intent intent = new Intent(MainActivity.this, Taskcreation.class);
intent.settype("");
startActivityForResult(intent, REQUEST_ADD);
//startActivityForResult(intent, 1);
}
});

Android Studio: Activity only finishes when you call the finish() for second time

So, we're working with intents at school and I'm having trouble with the intents when I try to pass data from the "Activity2" to the "Activity1", when I do the setResult() and stuff. The problem is it won't go back to the first activity when I trigger the event the first time, but it will the second.
I've been working with Android studio only for about 12h so I really lack a lot of understanding.
Here is what I'm doing:
First I call this form the main activity.
public void CheckPassword(View view) {
password = PasswordManagement.getPassword(this);
TextView txtPassword = findViewById(R.id.txtPassword);
if (txtPassword.getText().toString().equals(password)) {
Intent intent;
intent = new Intent(this, WelcomeActivity.class);
intent.putExtra("password", password);
startActivityForResult(intent, 1);
startActivity(intent);
} else {
Intent intent;
intent = new Intent(this, RestrictedActivity.class);
startActivityForResult(intent, 1);
startActivity(intent);
}
}
Then, when I'm done from the second activity I run this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restricted);
lblRestrictedArea = findViewById(R.id.lblRestrictedArea);
lblRestrictedArea.setOnLongClickListener(
new OnLongClickListener() {
public boolean onLongClick(View view) {
intent = new Intent();
intent.putExtra(EXTRA_RESPONSE, true);
setResult(RESULT_OK, intent);
finish();
return false;
}
});
}
And back to the main activity I overwrote this to act according to the response:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
if (data.getBooleanExtra(RestrictedActivity.EXTRA_RESPONSE,false)){
LinearLayoutPasswordActivity.setBackgroundColor(getResources().getColor(R.color.red));
}else{
LinearLayoutPasswordActivity.setBackgroundColor(getResources().getColor(R.color.white));
}
}
}
}
If anyone can help I would be very glad, meanwhile I'll try to solve it my own.
Thanks!
Your are calling startActivity twice. So there are two instance of the same Activity and then you have to finish twice.
Keep your startActivityForResult(...) and delete startActivity in CheckPassword(View view)
->
public void CheckPassword(View view) {
password = PasswordManagement.getPassword(this);
TextView txtPassword = findViewById(R.id.txtPassword);
if (txtPassword.getText().toString().equals(password)) {
Intent intent;
intent = new Intent(this, WelcomeActivity.class);
intent.putExtra("password", password);
startActivityForResult(intent, 1);
// startActivity(intent);
} else {
Intent intent;
intent = new Intent(this, RestrictedActivity.class);
startActivityForResult(intent, 1);
//startActivity(intent);
}
}
Plus, note that you are using the same requestCode (1) for two different activities. The requestCode is very important for onActivityResult method.

How to send clicked button to another Activity optimally?

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.

Intent putExtra persists

i'm having an issue with Intents and putExtra.
What i want to do is this :
In Activity A(it's not my MainActivity),when i click a button,it will close all my activities, send a string and launch my main activity.For testing purposes it will show a test dialog with my string.All good till now,works as i need it to.
The problem is that if i restart my MainActivity(and i need to do that,it's something like a shopping list,i need to start a new shopping list) the dialog with the putExtra string shows again.
Here are my code snippets :
In Activity A :
#Override
public void onClick(View v) {
Intent intent = new Intent(Gestionarez.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra( "paramName", str );
startActivity( intent );
// TODO Auto-generated method stub
dialog.dismiss();
dialog.cancel();
}
In my MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadPref();
Bundle extras = getIntent().getExtras();
if (extras != null) {
String myParam = extras.getString("paramName");
ShowAlertMessage(this, "TEST", myParam + "");
} else {
}
}
And this is how i restart my MainActivity when i need to start a new shopping list :
Intent intent = getIntent();
finish();
startActivity(intent);
replace
Intent intent = getIntent();
finish();
startActivity(intent);
with
Intent intent = new Intent(this, ActivityB.class);
finish();
startActivity(intent);

Categories