I'm trying to send data on SharedPreferenceson from MainActivity to a BroadcastReceiver.
but that always return null .
I tried very code but all of them returned null.
this is my code on MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences shpMobile = getSharedPreferences("text", MODE_PRIVATE);
final String MobileNumber = (shpMobile.getString("MobileDevice", "0"));
Intent inte = new Intent();
inte.setAction("MyBroadcast");
inte.putExtra("Phone", MobileNumber);
sendBroadcast(inte);
and this is my BroadcastReceiver class
String phoo1;
#Override
public void onReceive(Context context, Intent intent) {
//updateWidget();
Bundle extras = intent.getExtras();
if (extras != null) {
String phoo1 = (String) extras.get("Phone");//getting null value
Toast.makeText(context, phoo1 +"این شماره انتقال دهنده است", 5000).show();
}
But phoo is null.
Whats wrong?
Had a similar problem some time ago. Try it using getStringExtra() from the intent instead of extras.get() from bundle:
String phoo1 = intent.getStringExtra("Phone");
that solved my problem.
Try to replace this code:
Bundle extras = intent.getExtras();
if (extras != null) {
String phoo1 = (String) extras.get("Phone");//getting null value
Toast.makeText(context, phoo1 +"این شماره انتقال دهنده است", 5000).show();
}
With this:
String phoo1 = intent.getStringExtra("Phone") !=null? intent.getStringExtra("Phone"):"";
Toast.makeText(context, phoo1 +"این شماره انتقال دهنده است", 5000).show();
thanks all.
but i cant get value with this solution. and i was searched on net to find another way to get the values.
finally ,i find a new sulotion . code is in below: ( i used to Shareperferenced to get values in BroadcastReceiver)
SharedPreferences prefs = context.getSharedPreferences("text",
Context.MODE_PRIVATE);
final String MobileNumber = (prefs.getString("MobileDevice", null));
this code work for me and reply the our Qustion for #Opiatefuchs request
Related
how can I check if Activity is started by default or a method of the Activity is called from an intent in an other activity?
I think at the moment my Code is very bad, because i handle it over a Try/Catch
It works fine, but i want better code
public class MyScan extends Activity {
public final static String EXTRA_MESSAGE = ".MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkIntent();
}
public void checkIntent() {
try {
Intent i = getIntent();
String method_name = i.getStringExtra("method_name");// is firing an error if there is no intent call
if (method_name.equals("scanBarcode")) {
scanBarcode2();// That starts my method
}
} catch (Exception e) {
setContentView(R.layout.activity_my_scan); // that shows just my Content
}
}
....
Thanky you for your hint Alex Terreaux
i changed the code this way
public void checkIntent() {
Intent i = getIntent();
if (i != null) {
String method_name = i.getStringExtra("method_name");
if (method_name != null && method_name.equals("scanBarcode")) {
scanBarcode2();
} else {
setContentView(R.layout.activity_my_scan);
}
}
}
and that works.
Try checking if the result of getIntent() is null.
You could use extras. In strings.xml add a new string:
<string name="starting_from_intent">STARTING_FROM_INTENT</string>
In the file where you are starting the activity by intent you can use:
intent.putExtra(getString(R.string.starting_from_intent), 1);
Then, in the checkIntent(), do:
boolean startedFromIntent;
Intent i = getIntent();
if (i.getIntExtra(getString(R.string.starting_from_intent), 0) == null
|| i.getIntExtra(getString(R.string.starting_from_intent), 0) == 0)
startedFromIntent = false;
else
startedFromIntent = true;
Hope this wasn't too hard to understand and hope this helps.
When your activity was started just by startActivity() a getCallingActivity() method in target activity will return null.
When it was called by startActivityForResult() it will return name of calling activity.
MainActivity.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.anaekran);
Thread t = new Thread(new Runnable() {
public void run() {
String smsMsj = getIntent().getStringExtra("sms");
if(smsMsj != null){
Toast.makeText(getApplication(), smsMsj, 2).show();
}
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle mesaj = intent.getExtras();
SmsMessage[] smsMessage = null;
String msj = "";
if(mesaj!= null){
Object[] pdus = (Object[])mesaj.get("pdus");
smsMessage = new SmsMessage[pdus.length];
for(int i = 0; i < pdus.length; i++){
smsMessage[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msj = smsMessage[i].getMessageBody();
}
Intent mIntent = new Intent(context, SmsReceiver.class);
mIntent.putExtra("sms", msj);
}
}
}
My receiver working correctly but i have one problem when message coming i want to show on my MainAcitivty toast, so i create mIntent in receiver class, and then im use putExtra method.
But not working, sory for my bad english and thank you :)
Perhaps using explicit Intent and starting it could help you, hm? :)
Intent mIntent = new Intent(context, MainActivity.class);
mIntent.putExtra("sms", msj);
context.startActivity(mIntent);
Your mistake is that you construct your new Intent with SmsReceiver.class (but you need to launch MainActivity) and that you do not start any activity with such an intent.
Edit 1: Also, pay attention - you are trying to run a toast inside your worker thread. This is not possible. Remove your anonymous Thread and move your toast code to your onCreate(Bundle):
protected void onCreate(Bundle saveState){
....
String smsMsj = getIntent().getStringExtra("sms");
if(smsMsj != null){
Toast.makeText(getApplication(), smsMsj, 2).show();
}
....
}
Edit 2: Moreover, your duration parameter in Toast.makeText(..) is set to 2. This does not correspond to any magic constant in Toast class. You have to use one of the constants: Toast.LENGTH_LONG or Toast.LENGTH_SHORT. So, rewrite your code to:
Toast.makeText(getApplication(), smsMsj, Toast.LENGTH_SHORT);
I have some problem with passing throught my variable from Activity to the BroadcastReceiver...
Here is my code:
here is my Broadcast receiver code... I try to catch SMS from one phone number which I have got from my Activity...
public class SMSMonitor extends BroadcastReceiver
{
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
public static String phone_number = "";
public static String msg_body = "";
public static final String SMS_EXTRA_NAME = "pdus";
#Override
public void onReceive(Context context, Intent intent)
{
String phone = intent.getExtras().getString("trusted_num");
if (intent != null && intent.getAction() != null && ACTION.compareToIgnoreCase(intent.getAction()) == 0)
{
Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] messages = new SmsMessage[pduArray.length];
for (int i = 0; i < pduArray.length; i++)
{
messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]);
}
phone_number = messages[0].getDisplayOriginatingAddress();
msg_body = messages[0].getMessageBody();
System.out.println("Phone number: "+phone_number);
System.out.println("Phone entered: "+phone);
}
}
}
Here is my Activity code:
public class Settings extends Activity implements OnClickListener{
private Button btn_save;
private EditText txt_phone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
//set Save button
btn_save = (Button)findViewById(R.id.btn_save);
txt_phone = (EditText)findViewById(R.id.et_phone);
btn_save.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_settings, menu);
return true;
}
#Override
public void onClick(View v)
{
if (v == btn_save)
{
try
{
String phone_num = txt_phone.getText().toString();
Intent i = new Intent(Settings.this, SMSMonitor.class);
i.putExtra("trusted_num", phone_num);
sendBroadcast(i);
}
catch(Exception e)
{
System.out.println("Error: "+e.getLocalizedMessage());
}
}
}
}
In this code I have text field for entering the phone number, which I need to pass to the BroadcastReceiver with intent.putExtra() method, but in LogCat I see, that variable didnot pass:
07-25 18:43:57.382: I/System.out(14245): Phone number: +37129690449
07-25 18:43:57.382: I/System.out(14245): Phone entered: null
So what I am doing wrong here?
UPD
Maybe code is not correct, but it works for me...
public void onReceive(Context context, Intent intent)
{
phone = intent.getExtras().getString("trusted_num");//get trusted phone number from Settings screen
//receive SMS
if (intent != null && intent.getAction() != null && ACTION.compareToIgnoreCase(intent.getAction()) == 0)
{
Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] messages = new SmsMessage[pduArray.length];
for (int i = 0; i < pduArray.length; i++)
{
messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]);
}
phone_number = messages[0].getDisplayOriginatingAddress();
msg_body = messages[0].getMessageBody();
System.out.println("Phone number: "+phone_number);
}
//check if number is not null
if (phone != null && phone != "")
{
System.out.println("Phone entered: "+phone);
}
}
}
You can't pass an intent to a broadcast receiver. "There is no way for a BroadcastReceiver to see or capture Intents used with startActivity()"
https://developer.android.com/reference/android/content/BroadcastReceiver.html
I had a similar issue a while back and solved it by using a combination of IntentServices and Activities. You have to restructure your program to fit these guidlines
Well, there are some things not that don't match:
You're sending an intent with no action in the first place, but you're specifying Broadcastreceiver's class; don't do like that:
Intent i = new Intent(Settings.this, SMSMonitor.class);
i.putExtra("trusted_num", phone_num);
sendBroadcast(i);
But try instead:
Intent i = new Intent("my_package_name.Some_general_constant");
i.putExtra("trusted_num", phone_num);
sendBroadcast(i);
Then, your BroadcastReceiver is supposed to know that it can also handle "Some_general_constant" action. For this reason, register an extra action in your Manifest file for your SMSMonitor:
<receiver android:name=".package_to_bla_bla.SMSMonitor">
<intent-filter>
<action android:name="my_package_name.Some_general_constant"/>
</intent-filter>
</receiver>
Then in your SMSMonitor you need to add an else if statement to handle this broadcast:
else if("my_package_name.Some_general_constant".equals(intent.getAction())
{
// get the data from intent and use it
}
I am trying to create an application that reads an NFC tag and checks the tag against strings in a string array and then sets the text on another activity. I have got it working so that it checks if the string exists and sets the text in the new activity, but I want to be able to specify which string I want it to check against within the array, because there will be multiple strings in the NFC tag that I want to then display in the new activity. I have tried this for it:
result == getResources().getString(R.string.test_dd)
Here is the relevant code:
String[] dd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dd = getResources().getStringArray(R.array.device_description);
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
if(doesArrayContain(dd, result)) {
Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(800);
Intent newIntent = new Intent(getApplicationContext(), TabsTest.class);
Bundle bundle1 = new Bundle();
bundle1.putString("key", result);
newIntent.putExtras(bundle1);
startActivity(newIntent);
Toast.makeText(getApplicationContext(), "NFC tag written successfully!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), result + " is not in the device description!", Toast.LENGTH_SHORT).show();
}
}
}
EDIT:
Here is the method used and please can anyone help me with this problem:
public static boolean doesArrayContain(String[] array, String text) {
for (String element : array) {
if(element != null && element.equalsIgnoreCase(text)) {
return true;
}
}
return false;
}
For comparing equality of strings (and other objects) use the equals() method. == compares identity of objects (same string object).
Here is the solution that I found:
Create a new method:
public static boolean stringCaseInsensitive(String string, String result) {
if(string != null && string.equalsIgnoreCase(result)) {
return true;
}
return false;
}
And call it in like this:
if(stringCaseInsensitive(getResources().getString(R.string.test_dd), result))
{
Intent newIntent = new Intent(getApplicationContext(), TabsTest.class);
Bundle bundle1 = new Bundle();
bundle1.putString("key", result);
newIntent.putExtras(bundle1);
startActivity(newIntent);
Toast.makeText(getApplicationContext(), "NFC tag written successfully!", Toast.LENGTH_SHORT).show();
}
else{
}
I'm new to Android and I'm just trying to pass two doubles from one activity to another. This question has been asked several different times on this site in several different ways, but something about my implementation is causing my app to force close. I think my problem may be with my "savedInstanceState" Bundle in the activity I'm trying to pass the variables to. I left out a lot of code obviously, but I included all the places where Bundles are used.
[EDIT] - I found a bad programming solution for what I need to do. I put public static variables in the receiving class and access them from the sending class. I realize this is bad programming, but it does what I want. Thanks to all who tried to help. I'm going to continue to try to do this the proper way.
Without the i.putExtra lines and any lines involving the Bundle extra, it works fine. Here's the code:
int lat = 0;
int lon = 0;
private void createNote() {
Intent i = new Intent(this, NoteEdit.class);
i.putExtra("lat", lat);
i.putExtra("lon", lon);
startActivityForResult(i, ACTIVITY_CREATE);
}
This is the activity I sent them to:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extra = getIntent().getExtras();
int lat = extra.getInt("lat");
int lon = extra.getInt("lon");
mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID) : null;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
String lattitude = mLatText.getText().toString();
String longitude = mLonText.getText().toString();
String date = mDateText.getText().toString();
String time = mTimeText.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createNote(title, body, lattitude, longitude, date, time);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body, lattitude, longitude, date, time);
}
}
This is how you should pass values.
Bundle bundle = new Bundle();
bundle.putString("str1", str1);
bundle.putInt("int1", int1);
bundle.putDouble("double1", double1);
Intent i = new Intent(this, Activity2.class);
i.putExtras(bundle);
startActivityForResult(i);
And this is how you get them in next activity
int int1 = getIntent().getExtras().getInt("int1")
String str1 = getIntent().getExtras().getString("str1")
double double1 = getIntent().getExtras().getDouble("double1")
does this clear your doubts?
The looks fine, you problem is someplace else.
Try adding prints before setting the intent to make sure your key and value are what you really think they are
int name = getIntent().getExtras().getInt(key);
You are calling startActivityforresult.so try getting the bundle in onActivityResult not in oncreate.you can override this onActivityResult
I think this is the problem try getting the bundle using this.you will get the value to this new variable.