How to receive multiple values using an intent - java

I have my main activity using the startActivityForResult method which calls an activity that i need to return two string values from. I have it working to return one, but even with all the tutorials and other questions on here i have read i cant seem to get it to return the two values. Below is my code.
here is where i start the second activity:
Button button = (Button) findViewById(R.id.add);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(addM, 1);
}
});
Here is the activity it starts, i need to return the text that is in the titleField(which works now) and the yearField
public class AddMovie extends Activity {
String movieTitle, movieYear;
EditText titleField, yearField;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
titleField = (EditText) findViewById(R.id.titleField);
yearField = (EditText) findViewById(R.id.yearField);
save = (Button) findViewById(R.id.saveMovie);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.setData(Uri.parse(titleField.getText().toString()));
setResult(RESULT_OK, data);
//data.setData(Uri.parse(yearField.getText().toString()));
//setResult(RESULT_OK, data);
finish();
}
});
}
}
Here is the method in my main class that receives results
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == request_Code)
{
if(resultCode == RESULT_OK)
{
tempTitle = data.getData().toString();
//tempYear = data.getStringExtra("movieYear");
Toast.makeText(this, tempTitle, Toast.LENGTH_SHORT).show();
dbAddMovie(tempTitle, tempYear);
}
}
}
The code that is commented out was one attempt at making it receive multiple values, although they failed. Any help with this situation would be great. Thanks!

You should use something like:
Intent returnIntent = new Intent();
returnIntent.putExtra("title",titleField.getText().toString());
returnIntent.putExtra("year",yearField.getText().toString());
setResult(RESULT_OK,returnIntent);
finish();
And on your main activity, onActivityResult:
tempTitle = data.getStringExtra("title");
tempYear = data.getStringExtra("year");

use data.putExtra("keys", data); instead of data.setData(.....)
and get data like;
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
String value = extras.getString("keyName");
}

You should be able be put extras on your intent and get that data through an associated tag. This is how I'm doing it from an Activity's onCreate.
Intent mIntent = new Intent(this, MainActivity.class);
mIntent.putExtra("your_tag", "the string you want to get");
startActivity(mIntent);
finish();
Then in the activity you want that data (the MainActivity or whatever you're calling it)....
Intent intent = getIntent();
String value = intent.getExtras().getString("your_tag");
It may also be worth noting that you can Override the onNewIntent in your MainActivity to handle new Intents coming in, mine currently looks like...
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}

Try this
public class AddMovie extends Activity {
String movieTitle, movieYear;
EditText titleField, yearField;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
titleField = (EditText) findViewById(R.id.titleField);
yearField = (EditText) findViewById(R.id.yearField);
save = (Button) findViewById(R.id.saveMovie);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra("title_field", titleField.getText().toString);
data.putExtra("year_field", yearField.getText().toString);
setResult(RESULT_OK, data);
finish();
}
});
}
And this
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == request_Code)
{
if(resultCode == RESULT_OK)
{
tempTitle = data.getStringExtra("title_field");
tempYear = data.getStringExtra("year_field");
Toast.makeText(this, tempTitle, Toast.LENGTH_SHORT).show();
dbAddMovie(tempTitle, tempYear);
}
}
}

You can use a putExtra method on your Intent:
data.putExtra("title", movieTitle);
data.putExtra("year", movieYear);
Then in the Activity that opens, you can get this data as follows:
String title, year;
Intent data = getIntent();
if (data != null) {
title = data.getExtras().getString("title");
year = data.getExtras().getString("year");
}

You can create a new intent and then add your two variables
Intent i = new Intent(getApplicationContext(), asd8.as.hwapp.timemonday.class);
i.putExtra("username",username);
i.putExtra("password", password);
startActivity(i);
And then retrieving the information in your new activity as so;
public void getInformation(){
Bundle extras = getIntent().getExtras();
if (extras != null) {
username = extras.getString("username");
password = extras.getString("password");
}
}

Related

How to store button information from previous activity, Android Studio Edition

So, I have an activity with 2 buttons marsPhoto and viewByDate. After the buttons are clicked they go to a new activity page where I want to take the name from the putExtra (Daily or Date) and printout Daily or Date in the TextView. I only want to set the text to match the string for the button (which is Daily for intent2 clicked and Date for intent3 clicked).
Activity 1
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.marsPhoto:
Intent intent2 = new Intent(this, MARS.class);
intent2.putExtra("Daily",1);
startActivity(intent2);
break;
case R.id.viewByDate:
Intent intent3 = new Intent(this, MARS.class);
intent3.putExtra("Date",2);
startActivity(intent3);
break;
}
}
Activity 2
TextView type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mars);
type = (TextView)findViewById(R.id.type);
Intent i = getIntent();
String s1 = i.getStringExtra("Daily");
String s2 = i.getStringExtra("Date");
type.setText(s1);
}
Change the key for the passed StringExtra to something like "button_text" and set the value to the text you want to display, i.e. "Date" or "Daily". There doesn't seem to be any meaning to the integer you are transferring.
modify the first code to this
Activity 1
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.marsPhoto:
Intent intent2 = new Intent(this, MARS.class);
intent2.putExtra("dataSent","Daily");
startActivity(intent2);
break;
case R.id.viewByDate:
Intent intent3 = new Intent(this, MARS.class);
intent3.putExtra("dataSent","Date");
startActivity(intent3);
break;
}
}
Activity 2
TextView type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mars);
type = (TextView)findViewById(R.id.type);
String s1="";
Bundle extras = getIntent().getExtras();
if(extras == null) {
s1 = "";
} else {
s1 = extras.getString("dataSent","");
}
type.setText(s1);
}

How to check from which onResume the user is coming

I have a problem. The following Picture visualises my issue. We start in App 1 and press the button. Now we either get to see the screen of app2 or the setting screen. Now when i press the back button (marked as the red circle in app2 and settings) and we get back to the app1 screen. But what i wanna know is from what screen we get back to the app1 screen.
#Override
protected void onResume() {
super.onResume();
// if(from setting) {
// do this
}
NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
NfcAdapter adapter = manager.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) {
Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
startActivity(userHomeScreen);
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nfc_setting);
NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
NfcAdapter adapter = manager.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
if (currentUser != null){
Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
startActivity(userHomeScreen);
}else{
Intent loginScreen = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(loginScreen);
}
}
else {
btn_nfc_navigate_setting = findViewById(R.id.btn_nfc_navigate_setting);
btn_nfc_navigate_setting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
}
});
}
Look now that I understand whats going on, you have to startActivityForResult() not startActivity():
Now in the activity that you use to open other activities:
When you open Log in screen:
Intent loginScreen = new Intent(getApplicationContext(), LoginActivity.class);
int requestCode = 10;
startActivityForResult(loginScreen , requestCode);
When you open settings
btn_nfc_navigate_setting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int requestCode = 11;
startActivityForResult(new Intent(Settings.ACTION_NFC_SETTINGS) , requestCode);
}
});
Override this method to listen to from where you came instead of onResume()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//this is triggered when you come back to this activity
if(requestCode == 10){
//we came from login
}else if(requestCode == 11){
//we came from settings
}
}
Use startActivityForResult()
From App1 to App2 or Setting:
int FLAG_APP2 = 1
Intent i = new Intent(this, App2.class);
startActivityForResult(i, FLAG_APP2);
Then in App2 button back tapped:
finish();
Then in App1 override onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FLAG_APP2) {
//here you know this is from App2 Screen
}
}
If you want to know the result of an Intent (in this case settings or app2), you can use
startActivityForResult(intent, requestCode)
instead of
startActivity(intent).
Where request code should be unique for different intents (in this case settings and app2).
To handle the result you have to override the onActivityResult() in the actvity.
So your required code will be
#Override
protected void onResume() {
super.onResume();
// if(from setting) {
// do this
// }
NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
NfcAdapter adapter = manager.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) {
Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
startActivityForResult(userHomeScreen,1);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
// Activity returned from userHomeScreen
}
else if (requestCode ==2) {
// Activity returned from Settings
}
}
UPDATE:
To add to that above if you want to access any Settings FEATURE you can use SETTINGS Constants as intent parameters.
Settings Documentation
For example, if you want to access NFC settings:
// Look into the constants in the documentation to know which constants to use in intent
Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
startActivityForResult(intent, 2);

Integrate git project on an existing project startActivityForResult and onActivityResult android

I implemented this git on my current project without cloning
implementation 'com.github.adityaarora1:LiveEdgeDetection:master-SNAPSHOT'
But I'm unable to call it on my method. The document says
Start startActivityForResult from your activity
startActivityForResult(new Intent(this, ScanActivity.class), REQUEST_CODE);
Get a file path for cropped image on onActivityResult
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
So I tried calling like this onClick button from a new Class
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this,
ScanActivity.class);
startActivity(myIntent);
}
and put the rest inside my onActivityResult
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
}
Edit: here is the MainActivity the author used on git I tried using it I get this error:
scannedImageView = findViewById(com.adityaarora.liveedgedetection.R.id.scanned_image);
MainActivity (imported)
private static final int REQUEST_CODE = 101;
private ImageView scannedImageView;
Button scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
scannedImageView = findViewById(com.adityaarora.liveedgedetection.R.id.scanned_image);
startScan();
scan = findViewById(R.id.open_scan);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(ScanActivity2.this,
ScanActivity.class);
startActivityForResult(myIntent ,111);
}
});
}
private void startScan() {
Intent intent = new Intent(this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
if(null != data && null != data.getExtras()) {
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
scannedImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
scannedImageView.setImageBitmap(baseBitmap);
}
} else if(resultCode == Activity.RESULT_CANCELED) {
finish();
}
}
}
Update :
After some research I found that the imported project was on read file only and cannot be changed (ScanActivity.java) and my current project was updated sdk 28 which is different from the one Imported so there is some errors in ScanActivity which Is why the button (technically) wasn't working
You should use startActivityForResult instead of startActivity like below.
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this,
ScanActivity.class);
startActivityForResult(myIntent ,111);
}
});
and modify your onActivityResult like
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK && requestCode == 111){
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
Log.d("YourTAG","File Path "+filePath);
// here you can set bitmap to your image view
yourImageView.setImageBitmap(baseBitmap);
}
}
UPDATE
You Main Activity should be like
private static final int REQUEST_CODE = 111;
private ImageView scannedImageView;
Button scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
scannedImageView = findViewById(R.id.scanned_image); // this ImageView should be in your activity_scan.xml file with same id(scanned_image)
startScan();
scan = findViewById(R.id.open_scan);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startScan();
}
});
}
private void startScan() {
Intent intent = new Intent(ScanActivity2.this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
if(null != data && null != data.getExtras()) {
String filePath = data.getExtras().getString(ScanConstants.SCANNED_RESULT);
Bitmap baseBitmap = ScanUtils.decodeBitmapFromFile(filePath, ScanConstants.IMAGE_NAME);
scannedImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
scannedImageView.setImageBitmap(baseBitmap);
}
} else if(resultCode == Activity.RESULT_CANCELED) {
finish();
}
}
}
Demo project
I have uploaded a demo project on Github which is integrated LiveEdgeDetection library and working as expected.
To check it go here

Alertdialog doesn't show when within if statement

I'm building a small app that scans barcodes and put them in a database (using ZXing library). After the scan is taken, and the barcode doesn't exist in the database I want to show a popup dialog that allows an user to enter the name manually.
The dialog works perfectly if it's invoked in an onClickListener, however when I try to put it in an 'if' statement within another method (which checks if the scan result is in the database) the dialog doesn't show.
What's strange, I put tags in the beginning of the method and at the end, both of them are shown in the log, but the alertdialog doesn't appear and it gets me back to the main activity without any error...
public void popUP (String barcode) {
Log.d(TAG, "method started");
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_input, null);
TextView tv = (TextView) mView.findViewById(R.id.textView2);
final EditText et = (EditText) mView.findViewById(R.id.item1);
Button bt1 = (Button) mView.findViewById(R.id.button2);
Button bt2 = (Button) mView.findViewById(R.id.button3);
final String code = barcode1;
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mydb.addNewItem(et.getText().toString(), code);
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
Log.d(TAG,"dialog shown");
}
And here is the method from which I try to inflate the popUP
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
final String barcode = scanResult.getContents();
if (scanResult != null) {
if(scanResult.getContents() == null) {
Log.d(TAG, "Cancelled Scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d(TAG, "SCANNED");
int rows = mydb.checkRows(barcode);
if (rows == -1){
Log.d(TAG, "popUP should appear");
popUP(barcode); //INVOKING THE ALERT DIALOG
} else {
Log.d(TAG, "found and attempting adding");
mydb.addItem(barcode, rows);
}
}
} else {
Toast.makeText(this, "oddal zero", Toast.LENGTH_LONG);
}
Intent intynt = new Intent(this, MainActivity.class);
startActivity(intynt);
}

Why is onActivityResult is called before a contact is chosen?

I'm following the answer https://stackoverflow.com/a/867828/129805 to add a contact picker to my app.
The problem is that onActivityResult is immediately invoked with the correct reqCode (PICK_CONTACT), but with aresultCode of 0 and a null for data.
It is not invoked again, when the user actually picks a contact.
The AndroidManifest gives this activity android:launchMode="singleInstance"> as I only ever want there to be one instance.
What have I done wrong?
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
addContactButton = (Button) findViewById(R.id.addContactButton);
addContactButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult");
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// TODO Whatever you want to do with the selected contact name.
Log.d(TAG, "you chose " + name + ".");
}
}
break;
}
}
The singleInstance fires the callback immediately. You have more info in this link

Categories