How to insert TextView in Activity from other non activity class Android? - java

I need to set TextView object of Main3Activity (Activity class) from IncomingSms (Non activity class).
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
#Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String senderNum = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
if (message.equalsIgnoreCase("FIRE DETECTED")) {
//Problem start here: I cant able to set TextView object of Main3Activity
Main3Activity main3Activity = new Main3Activity();
TextView tv = (TextView) main3Activity.findViewById(R.id.firealert);
tv.setText(message);
//Problem end here
Log.i("SmsReceived", "senderNum: " + senderNum + "; message: " + message);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, message, duration);
toast.show();
}
}
}
} catch(Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
}

create an interface class save it as java class then
public interface SmsListener {
public void messageReceived(String messageText);
}
and
final SmsManager sms = SmsManager.getDefault();
private static SmsListener mListener;
#Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String senderNum = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
if (message.equalsIgnoreCase("FIRE DETECTED") ){
mListener.messageReceived(message); //add this
Log.i("SmsReceived", "senderNum: "+ senderNum + "; message: " + message);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, message, duration);
toast.show();
}
}
}
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
public static void bindListener(SmsListener listener) {
mListener = listener;
}
And in your Main3Activity onCreate method
TextView tv=(TextView) main3Activity.findViewById(R.id.firealert);
SmsReceiver.bindListener(new SmsListener() {
#Override
public void messageReceived(String messageText) {
Log.d("Text",messageText);
tv.setText(messageText);
}
});

You can't create the activity instance like that.
Solution:
1. Create a broadcast receiver in your activity and register for a custom intent.
2. Send a custom broadcast intent from your sms receiver. So basically that will reach activity receiver and then you can simply update the text there.
In case your activity is not started, simply create a activity intent and pass the sms text as part of the intent extras.

Related

If message contains a text then use the answer (Android Studio)

If the message received have text "1" then show in-app message "Da" (already done part with show app)
If the message received doesn't have text "1" then don't show the app.
MainActivity:
public class MainActivity extends AppCompatActivity {
/* Button msg; */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* In beta mode
PreferenceManager.setDefaultValues(this, R.xml.preferences, true); */
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String address = extras.getString("MessageNumber");
String message = extras.getString("Message");
TextView addressField = (TextView) findViewById(R.id.address);
TextView messageField = (TextView) findViewById(R.id.message);
addressField.setText("ALERT From : " + address);
messageField.setText("ALERT Type : " + message);
}
/* msg = (Button)findViewById(R.id.btn_msg);
msg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});*/
SimpleSMSReciver class
public class SimpleSmsReciever extends BroadcastReceiver {
private static final String TAG = "Message recieved";
#Override
public void onReceive(Context context, Intent intent) {
Bundle pudsBundle = intent.getExtras();
Object[] pdus = (Object[]) pudsBundle.get("pdus");
SmsMessage messages =SmsMessage.createFromPdu((byte[]) pdus[0]);
// Start Application's MainActivty activity
Intent smsIntent=new Intent(context,MainActivity.class);
smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsIntent.putExtra("MessageNumber", messages.getOriginatingAddress());
smsIntent.putExtra("Message", messages.getMessageBody());
context.startActivity(smsIntent);
// Get the Sender Message : messages.getMessageBody()
// Get the SenderNumber : messages.getOriginatingAddress()
Toast.makeText(context, "Message Received From :"+messages.getOriginatingAddress()+"\n"+ messages.getMessageBody(), Toast.LENGTH_LONG).show();
}
If the message received doesn't have text "1" then don't show the app.
if(!extras.getString("Message").equals("1"))finish();

how to show received sms in textview instead of toast

I am currently working on a simple android application to read an SMS and print it in TexView instead of Toast. but in receiver activity, we do not initialise "findbyid" so we can't print the SMS in textView. now I am showing SMS in Toast to test but I do not want it in a toast. I am also read questions/answer and also other articles but can't find what I want.
receiver activity,
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class read_sms extends BroadcastReceiver {
// Get the object of SmsManager
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReciver", "senderNum: " + senderNum + ", message: " + message);
//ourSMS.getSmsDetails(senderNum, message);
// Show SMS notification
//Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, Toast.LENGTH_LONG).show();
if(message.equals("Milind")){
Toast.makeText(context, "sms matched", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(context, "not matched", Toast.LENGTH_LONG).show();
}
} // end of for loop
} // bundle
} catch (Exception e) {
// TODO: handle exception
Log.e("SmsReciver", "Exception smsReciver" + e);
}
}
}
my home activity is empty because I can't find which code placed here.
public class home extends AppCompatActivity {
TextView SMS_textview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
SMS_textview = (TextView) findViewById(R.id.sms_text);
}
}
change that TextView to
public static TextView SMS_textview;
add method
public void recivedSms(String message)
{
try
{
SMS_textview.setText(message);
}
catch (Exception e)
{
}
}
in read_sms class add the following code when you recieve sms
home Sms = new home();
Sms.recivedSms(message );
Register your Receiver in your activity whenever you Receive a text in receiver
use this code in your Receiver class
Intent broadcastIntent = new Intent();
broadcastIntent.putExtra("your key", your Value);
broadcastIntent.setAction("link from you have recieve a text");
context.sendBroadcast(broadcastIntent);
after this register a broadcast Receiver in your activity like this
private void registerSmsReciever() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("link from you have recieve a text");
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("onReceive", "Sms recieved in progress");
String message= intent.getStringExtra("key");
textView.setText(intent.getStringExtra("key"));
}
};
registerReceiver(broadcastReceiver, intentFilter);
}

How to pass data from Receiver to Activity using interface?

I'm trying to pass the data from the brodcast receiver to the activity to display it on the view using an interface, but, it's not working.Here are my files,MainActivity.java
public class MainActivity extends AppCompatActivity implements OtpPassing {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onReceive(String msg) {
Toast.makeText(this, "o" + msg, Toast.LENGTH_SHORT).show();
textView = (TextView) findViewById(R.id.textView);
textView.setText("OTP: " + msg);
}
}
OtpPassing.java
public interface OtpPassing {
public void onReceive(String msg);
}
Receiver.java
public class Receiver extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);
String otp = getOtp(message);
Toast.makeText(context, otp, Toast.LENGTH_LONG).show(); //This is working fine
OtpPassing otpPassing = new MainActivity();
otpPassing.onReceive(otp); //This is not working
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
private String getOtp(String message) {
String otp = null;
int index = message.indexOf("otp:");
if(index != -1){
int start = index + 5;
otp = message.substring(start, start+4);
}
return otp;
}
}
The receiver is woking(it's displaying the message on a Toast) but why is displaying the message on the screen via MainActivity not working?
You can create a broadcast receiver as a data member of your activity. You register for it in onCreate and unregister in onDestroy (or onStart and onStop).
That way the receiver has a reference to the parent activity and you can do whatever.
public class MainActivity extends AppCompatActivity implements OtpPassing {
private TextView textView;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//Access the parent activity as follows
MainActivity.this.textView.setText("...");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//instantiate and register the receiver
setContentView(R.layout.activity_main);
}
#Override
protected void onDestroy() {
// Unregister the receiver here
super.onDestroy();
}
Here better way (I suppose) would be to use Android Intents
in your receiver, something like this
Intent intent = new Intent(context,MainActivity.class);
intent.putExtra(.....);
startactivity(intent);
now in your MainActivity, override onNewIntent(). Here check for the 'extras' you had passed from the receiver.
Please note, this might result in having multiple MainActivities running in your phone if your "older" MainActivity was not killed by the time this intent was passed via receiver. To overcome this, use 'singleTop' or similar flags in your Manifest file

Notification will not open Activity

I have an application where the user may send recipes to others with the application.
Right now, the app is able to send the notification, however, when the notification is clicked, it does not open the intended activity (SmsViewActivity) it simply closes the drawer.
Here is the code for the SmsViewActivity:
public class SmsViewActivity extends Activity {
private static final String TAG = "SmsViewActivity";
private static final String SMS_FOOD = "food_recieved";
private FoodJSONSerializer mSerializer;
public Button mSaveButton, mDismissButton;
public int mNotificationId;
public String message;
private EditText mTitleField;
private CheckBox mImperialCheckBox;
private CheckBox mMetricCheckBox;
private EditText mServingsField;
private EditText mDirectionsField;
private Spinner mMetricSpinner;
private Spinner mImperialSpinner;
Food mFood;
private String msg;
private Activity mActivity;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mActivity = this;
setContentView(R.layout.sms_view);
mSaveButton = (Button) findViewById(R.id.save_button_sms);
mDismissButton = (Button) findViewById(R.id.dismiss_button_sms);
this.msg = getIntent().getStringExtra("message");
try {
JSONObject jsonRecipe = new JSONObject(this.msg);
this.mFood = new Food(jsonRecipe);
Log.i(TAG, "Food = " + mFood);
} catch (JSONException e) {
e.printStackTrace();
}
mNotificationId = getIntent().getIntExtra("notificationid", 0);
if (mNotificationId == 0) {
Log.e(TAG, "Could not retrieve notification ID.");
Toast.makeText(this, "A fatal error has occurred in SMS viewer.",
Toast.LENGTH_LONG).show();
finish();
}
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationMgr = (NotificationManager) getSystemService(ns);
notificationMgr.cancel(mNotificationId);
this.mTitleField = (EditText) findViewById(R.id.food_title_sms);
this.mTitleField.setText(mFood.getTitle());
this.mServingsField = (EditText) findViewById(R.id.food_servings_sms);
this.mServingsField.setText(Integer.toString(mFood.getServings()));
this.mDirectionsField = (EditText) findViewById(R.id.directions_text_sms);
this.mDirectionsField.setText(mFood.getDirections());
this.mSaveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FoodStorage.get(mActivity).addFood(mFood);
finish();
}
});
this.mDismissButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
backToList();
finish();
}
});
}
public void backToList() {
Intent i = new Intent(this, FoodListFragment.class);
startActivity(i);
}
}
Also here is the receiver Activity:
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
Bundle bundle = intent.getExtras();
Map<String, String> msgTexts = new LinkedHashMap<String, String>();
if (bundle != null){
Object[] pdus = (Object[]) bundle.get("pdus");
for (Object pdu : pdus) {
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
String incomingMsg = message.getMessageBody();
String originatingNumber = message.getOriginatingAddress();
Log.i(TAG, "Rcvd: from " + originatingNumber + " Msg: " + incomingMsg);
msgTexts.put(originatingNumber, incomingMsg);
smsMessage = incomingMsg;
}
}
processMessages(msgTexts, mNextNotificationId);
}
public void processMessages( Map<String, String> msgTexts, int notificationId ){
for (Entry<String, String> entry : msgTexts.entrySet()) {
Log.i(TAG, "Processing message: " + entry.getValue());
Intent notificationIntent = new Intent(mContext, SmsViewActivity.class);
notificationIntent.putExtra("message", entry.getValue());
notificationIntent.putExtra("sender", entry.getKey());
notificationIntent.putExtra("notificationid", notificationId);
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Recipe Received")
.setContentTitle("Recipe Received")
.setContentIntent(resultPendingIntent)
.setContentText("from " + entry.getKey())
.setWhen(System.currentTimeMillis());
NotificationManager notificationMgr = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationMgr.notify(notificationId++, mBuilder.build());
}
}
Try changing the intent flag to:
PendingIntent.FLAG_CANCEL_CURRENT
Otherwise it just updates the existing intent. It should be possible to have an onNewIntent handler in your activity, but I found this works more reliably.

Java Android : Subclass, Call method from main activity class caused NullPointerException

i want to call function from subclass to main activity class.
here is my source code :
SMS.java
public class SMS extends ListActivity {
public void testerr(String kata) {
Toast.makeText(getBaseContext(), "test coyyyy="+kata, Toast.LENGTH_LONG).show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
SMSReceiver.java
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
try {
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
SMS sss = new SMS(); ---> call the main class
sss.testerr("try the words"); ---> call method from main class
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
}
}
catch(NullPointerException ex){
Toast.makeText(context, "penyakite neng kene:"+ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
my program run after it receive new text message, and i always get NullPointerException when call that sss.testerr("my example words");
any clue guys?
thankyou so much for your help
You should not instantiate the Activity with it's constructor, either start it with an intent, or, if the Activity is already up, make it implement the broadcast receiver.
If you only want to show toast from your receiver, you can use the answer for this question

Categories