I am trying to send an Intent value between two activities, though it appears, having read this, that in my second activity, the received intent is null; having encoutnered an NPE at runtime.
The intended functionality behind this is: 'the user scans a code in Activity A' -> 'a true value received and packed into an intent' -> 'Activity B opens, unpacks the intent and checks that the intent value is true' -> 'if true, the height of an ImageView in the activity is reduced by a set amount'.
I am therefore, not sure why my Intent is received as null in Activity B, as I would like this check to happen so that the height is updated when the activity opens?
Activity A:
//do the handling of the scanned code being true and display
//a dialog message on screen to confirm this
#Override
public void handleResult(Result result) {
final String myResult = result.getText();
Log.d("QRCodeScanner", result.getText());
Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Activity Complete!");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
//the user has pressed the OK button
#Override
public void onClick(DialogInterface dialog, int which) {
scannerView.resumeCameraPreview(QRActivity.this);
//pack the intent and open our Activity B
Intent intent = new Intent(QRActivity.this, ActivityTank.class);
intent.putExtra("QRMethod", "readComplete");
startActivity(intent);
}
});
builder.setMessage(result.getText());
AlertDialog alert1 = builder.create();
alert1.show();
}
Activity B:
// in onCreate, I check that the bundled intent is true
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tank);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
//then the extras bundle is null, and nothing needs to be called here
}
else {
String method = extras.getString("QRmethod");
if (method.equals("readComplete")) {
updateTank();
}
}
}
}
//this is the method that is called when the intent check is true
public int tHeight = 350;
public void updateTank() {
ImageView tankH = (ImageView)findViewById(R.id.tankHeight);
ViewGroup.LayoutParams params = tankH.getLayoutParams();
params.height = tHeight - 35;
tankH.setLayoutParams(params);
}
In Activity B you have a typo while pulling QRMethod from the Intent extras. You are using QRmethod while you have set extras with 'QRMethod'.
You can use :
In first activity ( MainActivity page )
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("QRmethod","readComplete" );
then you can get it from your second activity by :
In second activity ( SecondActivity page )
Intent intent = getIntent();
String YourtransferredData = intent.getExtras().getString("QRmethod");
You can get string value by using intent.getStringExtra() method like this in your second activity.
if (getIntent() != null){
getIntent().getStringExtra("QRmethod") //this s your "readComplete" value
}
Related
I am writing a code which should return NFC tag value on the next activity ( page ) when NFC get detected during scan. What happens here is that when I launch the app for the first time it the first page shows for a fraction of a second and moves to second page directly ( activity ).
Here is the piece of code for the first activity ( which is just for asking user to tap to scan )
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
askPermissions();
mtxtViewNfcContent = (TextView) findViewById(R.id.text);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "No NFC", Toast.LENGTH_SHORT).show();
finish();
return;
}
else {
Intent in = new Intent(Main2Activity.this, MainActivity.class);
startActivity(in);
}
What I want is the the to show the first page at launch and when user tap to nfc scan, show the output on the next page ( MainActivity).
PS : I am new to android, please excuse with my codes.
what are you doing until now is to exit the app when the device doesnot support nfc or to start another activity when the device supports nfc.
you are actually not listening at all to any tag.
here you have two possibilities:
first : read an nfc tag in the first activity and then creat a new intent with and put the result of tag reading as extra bundel.
two : listen to tag existance in the first activity and then send the tag to second one and read it in the second activity.
I would prefer the first secinario.
on firstActivity:
public class MainActivity extends AppCompatActivity {
private PendingIntent pendingIntent;
private IntentFilter[] writeTagFilters;
private NfcAdapter nfcAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.AppTheme);
setContentView(R.layout.activity_main);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "No NFC", Toast.LENGTH_SHORT).show();
finish();
return;
}
setForeground();
}
private void setForeground() {
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
writeTagFilters = new IntentFilter[]{tagDetected};
}
#Override
protected void onResume() {
super.onResume();
if (nfcAdapter != null) {
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
processNfcTag(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
#Override
protected void onPause() {
super.onPause();
if (nfcAdapter != null) {
nfcAdapter.disableForegroundDispatch(this);
}
}
private void processNfcTag(Intent intent) {
//TODO: here you should to check if this intent is an NFC Intent, in case it is an nfc intent you could read it according of tag tech you have
// for example MifareUltralight.
MifareUltralight mfu = MifareUltralight.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));
try {
mfu.connect();
byte [] bytes = mfu.readPages(pageNumber);
mfu.close();
} catch (IOException e) {
e.printStackTrace();
}
// then you could get this bytes and send it to the other activity
}
please check this link to know how to send data between activities.
p.s: you should to check the code I have wrote it quickly.
You can use intent.putExtra (key,value) while calling the intent and use bundle on the result activity to fetch the variable data
use this while calling the intent
`Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("some_key", value);
intent.putExtra("some_other_key", "a value");
startActivity(intent);`
use this on result activity
`Bundle bundle = getIntent().getExtras();
int valueText = bundle.getInt("some_key");
String valueString = bundle.getString("some_other_key");
TextView textone =(TextView)findVeiwById(R.id.textone);
textone.setText(valueText);
TextView stringTextView = (TextView)FindViewById(R.id.stringTextView)
stringTextView.setText(valueString)`
This is my MainActivity.java and I want the results in a text view of another activity? How can I achieve it? Can you Show me with an example please.
public class MainActivity extends AppCompatActivity {
private Button scan_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scan_btn=(Button)findViewById(R.id.btnQr);
final Activity activity =this;
scan_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator intentIntegrator = new IntentIntegrator(activity);
intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
intentIntegrator.setPrompt("Scan");
intentIntegrator.setCameraId(0);
intentIntegrator.setBeepEnabled(false);
intentIntegrator.setBarcodeImageEnabled(false);
intentIntegrator.initiateScan();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null){
if (result.getContents()==null){
Toast.makeText(this,"You cancelled scanning",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this,result.getContents(),Toast.LENGTH_LONG).show();
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
This is my Second Activity. Where I want to show the result.
public class DetailActivity extends AppCompatActivity {
private TextView qrResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
qrResult= findViewById(R.id.qrResult);
}
}
If you want I can post my Layout file as well. Thankyou.
You need to create a new Intent object, and add it extra data with intent.putextra(). This method can take a String object as an argument. You need to specify a unique key for that string.Then start the new activity. For example
Intent i = new Intent(context, nextactivity.class)
i.putextra(“stringKey”,yourSstring)
startActivity(i)
Then, in the second activity, you need to get the intent that started that activity (with getIntent), you can use it as early as onCreate.
The getIntent function returns the intent object that started the new activity.
When you have the new intent, you can get the extra string you passed from the old activity, with intent.getStringExtra(“stringKey”)
This allows you to pass simple data between activities. Make sure to use the same key.
You can put data into the intent from your main acivity and the get the intend from the second activity for the data.
For example:
In your MainActivity.class
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("result", "Your result text here");
startActivity(intent);
In Your DetailsActivity.class:
Intent intent = getIntent();
String result = intent.getStringExtra("result");
qrResult.setText(result);
You can even send any type of object through intent. Please google it for further information.
I've 2 activities, and need the main Activity to send some data to the second Activity then the second activity analyze this data and send response back, so I've the below 2 codes:
Main Activity:
import static tk.zillion.mobile.SecondActivity.EXTRA_STUFF;
public class MainActivity extends Activity {
private static int PICK_CONTACT_REQUEST = 0;
private static final int SECOND_ACTIVITY_RESULT_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Start the SecondActivity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, "my text");
startActivityForResult(intent, SECOND_ACTIVITY_RESULT_CODE);
finish();
}
// This method is called when the second activity finishes
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(this, "I'm the Main activity", Toast.LENGTH_SHORT).show();
// check that it is the SecondActivity with an OK result
if (requestCode == SECOND_ACTIVITY_RESULT_CODE) {
if (resultCode == RESULT_OK) {
// get String data from Intent
String returnString = data.getStringExtra(EXTRA_STUFF);
// set text view with string
Toast.makeText(this, "I'm the Main activity", Toast.LENGTH_SHORT).show();
}
}
}
and the Second Activity is as below:
public class SecondActivity extends Activity {
static final String EXTRA_STUFF = "tk.zillion.mobile.EXTRA_STUFF";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent();
String s = getIntent().getStringExtra(Intent.EXTRA_TEXT);
Toast.makeText(this, "I'm the second activity " + s , Toast.LENGTH_SHORT).show();
Bundle basket =new Bundle();
basket.putString(EXTRA_STUFF, s);
intent.putExtras(basket);
setResult(RESULT_OK, intent);
finish();
}
}
The second activity is fired correctly, and receive the data from the main one, but once the data is sent back the onActivityResult is not fired!!
How can I solve it? thanks
Remove the finish() call that comes after startActivityForResult(). You prevent the oncoming activity to give a result back, because you remove your MainActivity with finish() from the back task.
Dont call finish() after startActivityForResult otherwise that instance of MainActivity that started the second one will be destroyed
I have an activity which transfer a string datatype to another activity which then uses that string and calls a method from another class which returns a string. I want to use that method to display the string in the current activity.
So visually it goes (activity 1) -- string--> (activity 2). Activity 2 uses that string to call a method in a different java class which returns a type string which i want to display on the screen along with a few buttons.
So some pseudo code:
say The method in a different java class is:
public static String getStringexample(String n) {
return "hello" + " " + n;
}
and my activity class is:
public class manage extends Activity {
protected void onCreate(bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContainerView(R.layout.activity_manage);
Intent intent = getIntent();
String example = intent.getExtras().getString("intentid");
i'm lost after this..not sure how to use what i got from the intent to display it on the screen in java code.
Information between activities is passed in 'extras'. That is just a collection of string keys and values.
Both sides need to use the same keys, so define static final strings with they keys that your destination activity expects.
Then read the values from the extras using the key and go from there:
public class DestinationActivity extends Activity {
// let your callers know how to pass you the information you need
public static final String EXTRA_N = "n";
private TextView resultText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_destination);
resultText = (TextView) findViewById(R.id.resultText);
// get the information you was passed
Intent intent = getIntent();
String n = intent.getStringExtra(EXTRA_N);
// do your transformation using the other class
String example = DifferentClass.getStringexample(n);
// display the transformed string
resultText.setText(example);
}
// ...
}
The calling activity sends the information like this:
Intent intent = new Intent(this, DestinationActivity.class);
intent.putExtra(DestinationActivity.EXTRA_N, "foo");
startActivity(intent);
Good luck
You can start activity as
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
Then return to first activity from second activity
Intent returnIntent = new Intent();
returnIntent.putExtra("result",yourdata);
setResult(RESULT_OK,returnIntent);
finish();
In your first activity you will get result by using below code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
I'm writing an app that has multiple activities. Activity A calls Activity B, not expecting a result. Then if a button is pressed B startsActivityForResult with Activity C. When Activity C is done, it makes an intent with all of the extras it needs and finishes. The problem is that when it calls this.finish() or just finish(), it brings me all the way back out to Activity A. onActivityResult in Activity B is not called. What is wrong?
Activity A: Starts Activity B
Intent in = new Intent(ccstart.this,mainmenu.class);
in.putExtra("uid",loginresponse);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("usr",text_user.getText().toString());
// Commit the edits!
editor.commit();
startActivity(in);
Activity B: Starts Activity C for result
Intent intent = new Intent(mainmenu.this,filebrowser.class);
startActivityForResult(intent,0);
Activity C: Return statement
Intent result = new Intent();
result.putExtra("fname", file.getAbsolutePath());
this.setResult(Activity.RESULT_OK, result);
finish();
Activity B: Upon the result of activity c...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// If the request went well (OK) and the request was PICK_CONTACT_REQUEST
if (resultCode == Activity.RESULT_OK && requestCode==0) { //upload a file
final String fname = data.getExtras().getString("fname");
final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); //Load settings
final String uid = settings.getString("uid", "");
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
doFileUpload(fname, uid);
}
}).start();
}
}
What is the issue with that? It happens with an activity that doesn't return a result as well, so its not just this one.
Thanks!
You need to explicit close your activity when you start the next one, if not, it stays in the "stack of activities" that you can access with the back button or when the next activity closes.
You need to call finish on activity A after you started activity B