data is not received from intent - java

I am working with BLE. I am trying to use intend to send rssi value from one activity to another.
Activity 1, when ever there is a change in the rssi signal, I send the values over, shown below:
#Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
//first logcat
Log.d("BLE_Strength_connected", String.format("BluetoothGatt ReadRssi[%d]", rssi));
Intent i = new Intent(Activity1.this, Activity2.class);
i.putExtra("key",rssi);
startActivity(i);
}
}
};
Activity 2:
In the oncreate() method, I started a handler, and it reads the data every second, I have the following:
mIntent = getIntent();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
try {
mHandler.postDelayed(this, 1000);
// if (mIntent != null) {
int value = mIntent.getIntExtra("key", 0);
Log.d("retrieve_RSSI", "value:" + value);
//The key argument here must match that used in the other activity
// }
}catch (Exception e) {
}
}
}, 1000);
My logcat on Activity 1 is constantly prints the rssi signal, but the logcat on activity 2 only prints zero. I am wondering why I can't receive any values in activity 2?

Your mIntent variable will always refer to the same Intent object, so when you extract the "key" extra from it, you will of course always get the same value.
You must make sure you handle new incoming intents. See for example http://m.helloandroid.com/tutorials/communicating-between-running-activities how to do that.

Related

Disappearing string in intent

I have something strange going on with my application.
I am trying to send a string via Broadcast by doing the following:
1st step (Sending):
Intent intent = new Intent("INFO");
intent.putExtra("INFO_VALUE", "hello_world_2019");
2nd step (Receiving):
if ("INFO".equals(intent.getAction())) {
String abc = intent.getStringExtra("INFO_VALUE");
Log.i(TAG, "" + abc);
}
Doing the previous steps, I get a null into my abc field. Also, if I use the debugger and check my intent related to the second step, I get:
intent -> mExtras -> mMap -> value[0] -> name: "hello_world_2019"
I am confused to what is going on. The abc field is not supposed to be null, but it is in this case.
How can I populate the aforementioned field so it is not null ?
Please explain what exactly you are trying to do, if you want to send data from one activity to other than my friend this is not the correct way to do that.
If you want to send a broadcast and receive that somewhere inside your code than you need to follow the below steps:
ReceiverActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
...
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("INFO"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
SenderActivity.java
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("INFO");
// You can also include some extra data.
intent.putExtra("message", "Message goes here!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

Android - StartActivityForResult on finish() method freezes UI

I have the following situation:
Activity A starts Activity B, by using startActivityForResult
Activity B then returns an ArrayList of Strings to Activity A by using on finish().
Here is a code example of what exactly Activity B does:
ArrayList<String> urls = new ArrayList<>();
urls.add("Some string");
Intent intent = new Intent();
intent.putStringArrayListExtra(KEY, urls);
setResult(Activity.RESULT_OK, intent);
finish();
Then Activity A receive the data in onActivityResult(...)
The issue I have is that when the user taps the done button and Activity B's code example executes, Activity B freezes for about 3 seconds (when I have about 2 strings in the ArrayList). The more strings I have in the ArrayList the longer it freezes. I have more or less determined that it is finish() that causes the UI thread to freeze.
Is there a way to call finish() without freezing Activity B? If not, why is this happening?
EDIT:
Here is the full example:
/**
* Background task
*/
private class gatherUrlsTask extends AsyncTask<ArrayList<PictureEntry>, Integer, Intent> {
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
bt_done.setVisibility(View.GONE);
fab_add_picture.setVisibility(View.GONE);
}
#SafeVarargs
#Override
protected final Intent doInBackground(ArrayList<PictureEntry>... params) {
ArrayList<String> imagePaths = new ArrayList<>();
for (PictureEntry pictureEntry : params[0]) {
if (pictureEntry.isSelected()) {
imagePaths.add(pictureEntry.getPath());
}
}
if (imagePaths.size() == 0) {
Toast.makeText(getApplicationContext(), R.string.please_select_atleast_one_image, Toast.LENGTH_LONG).show();
return null;
} else {
Intent intent = new Intent();
intent.putStringArrayListExtra(SELECTED_IMAGES_KEY, imagePaths);
return intent;
}
}
#Override
protected void onPostExecute(Intent intent) {
setResult(Activity.RESULT_OK, intent);
finish();
}
}
However I can remove everything from the AsyncTask since it did not have any effect on performance.
i don't know what is cause of that, but for prevent ui getting freezed, use asyncTask and then in the onPostExcecute call finish()

setActivityForResult from Fragment returns null data

I have a Fragment MainFragment and I do:
Intent i = new Intent(getActivity(), PersonActivity.class);
startActivityForResult(i, 0);
The activity starts ok and it starts its own PersonFragment and inside the PersonFragment I do:
#Override
public void onDestroy() {
super.onDestroy();
Intent i = new Intent();
i.putExtra(PERSON_ID_EXTRA, getPersonId());
i.putParcelableArrayListExtra(PERSON_CONTACT_LIST, (ArrayList<? extends Parcelable>) contactFriends);
getActivity().setResult(Activity.RESULT_OK, i);
}
Back in my MainFragment I do:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if ( requestCode != 0) {
return;
}
int personId = data.getIntExtra(PERSON_ID_EXTRA, -1);
List<Person> contacts = data.getParcelableArrayListExtra(PERSON_CONTACT_LIST);
for(Person p:contacts) {
Log.d("APP", p.getFullName());
}
}
I see that the code goes to onActivityResult but the data is null. What am I messing up here?
Update:
I see that pressing back button does not call onDestroy().
But where am all examples I saw used getActivity.finish() and I don't want to finish the activity. Only when the user presses e.g. back send the data
Update2:
I added the following and I go through that code but the Intent data in the result onActivityResult is still null
#Override
public void onPause() {
super.onPause();
Intent i = new Intent();
i.putExtra(PERSON_ID_EXTRA, getPersonId());
i.putParcelableArrayListExtra(PERSON_CONTACT_LIST, (ArrayList<? extends Parcelable>) contactFriends);
getActivity().setResult(Activity.RESULT_OK, i);
}
From the Activity documentation about finish:
Call this when your activity is done and should be closed. The
ActivityResult is propagated back to whoever launched you via
onActivityResult().
From the documentation about onActivityResult:
Called when an activity you launched exits, giving you the requestCode
you started it with, the resultCode it returned, and any additional
data from it.
So, onActivityResult will only be called when the second activity finishes.
If you don't want to finish your PersonActivity to send the result to your main activity, then you may want to start another intent to send the data or pass the data using static fields (not a best practice at all).
In your case, to set your result when you press the back button, you can write a code like this:
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Intent i = new Intent();
i.putExtra(PERSON_ID_EXTRA, getPersonId());
i.putParcelableArrayListExtra(PERSON_CONTACT_LIST, (ArrayList<? extends Parcelable>) contactFriends);
getActivity().setResult(Activity.RESULT_OK, i);
finish();
return true;
}
return false;
}
Follow up based on the comments:
The code for the finish() on the Activity class looks as follows:
// Call this when your activity is done
// and should be closed. The ActivityResult
// is propagated back to whoever launched
// you via onActivityResult().
public void finish() {
if (mParent == null) {
int resultCode;
Intent resultData;
synchronized (this) {
resultCode = mResultCode;
resultData = mResultData;
}
if (false) Log.v(TAG, "Finishing self: token=" + mToken);
try {
if (resultData != null) {
resultData.prepareToLeaveProcess();
}
if (ActivityManagerNative.getDefault()
.finishActivity(mToken, resultCode, resultData)) {
mFinished = true;
}
} catch (RemoteException e) {
// Empty
}
} else {
mParent.finishFromChild(this);
}
}
Here you can see that is the responsibility for setting the result values lays on the finish() method.
Then, before the Activity is destroyed, the onDestroy() method is called. That is the reason why setting the result of the Activity on the onDestroy() method won't work.

EditText value in a Service

I'm building an application in which I use a service to create a background process. but I have a problem.
I use an EditText where the user enters a URL, then I will use that url in the service for check the connection to a website every X minutes. But if the user closes the application, the background process crash because the value of the EditText became Null, and logcat give me null pointer exceptions. I pass the value from the activity to the service with an intent, MainActivity code below:
public void onClickReadWebPage(View v)
{
if(address.getText().toString().trim().length() == 0)
{
Toast.makeText(getApplicationContext(), "URL String empty.", Toast.LENGTH_LONG).show();
}
else
{
time = String.valueOf(address.getText());
i=new Intent(MainActivity.this,MyService.class);
p=PendingIntent.getService(MainActivity.this, 0, i, 0);
i.putExtra("Address", time);
//start the service from here //MyService is your service class name
startService(i);
}
and this is the service code:
#Override
public void onStart(Intent intent, int startId)
{
Address = intent.getStringExtra("Address");
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(Address);
if(report == "false")
{
//do my stuff
}
else
{
//do my stuff
}
}
Any suggestion?
Just save the value of ediText in SharedPreferences and then retrieve them in your service
.See
How to use SharedPreferences in Android to store, fetch and edit values
Also Problems using SharedPreferences on a Service (getPreferences doesn't exist on a service)

passing more data from android view

private Button.OnClickListener goFirstPage = new Button.OnClickListener() {
public void onClick(View v)
{
try
{
Intent i = new Intent(v.getContext(), quizMath.class);
startActivityForResult(i, 0);
} catch (Exception e)
{
e.printStackTrace();
// TODO: handle exception
}
}
};
hi, this is my code, but the problem is that i want to call a function from class quizmath.So is it possible or not?. can we pass integer or string from startActivityForResult?
Yes it's possible. You'll find documentation for Intent here http://developer.android.com/reference/android/content/Intent.html
Before you start the activity you can use the putExtra function on your intent.
i.putExtra( "yourapp.function_to_call", "subtract" );
This is going to be passed to your activity and you can get out the information with the Intent.getStringExtra function. In your activity you can then do something like this.
Intent i = this.getIntent();
String fname = i.getStringExtra( "yourapp.function_to_call" );
if( fname.equals("add") )
// ...

Categories

Resources