-1

I'm writing a GCM application. I'm unable to set a received message to a text view.

Check the below code:

public class GcmMessageHandler extends IntentService {

    String mes;
    private Handler handler;

    public GcmMessageHandler() {
        super("GcmMessageHandler");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        handler = new Handler();
    }

    @Override
    public void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();

        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        String messageType = gcm.getMessageType(intent);
        mes = extras.getString("title");
        showMsg();
        Log.i("GCM", "Received : (" +messageType+") "+extras.getString("title"));
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    public void showMsg(){
        handler.post(new Runnable() {
            public void run() {

                TextView textview = (TextView)findViewById(R.id.getMsg);
                textview.setText(mes );
            }
         });
    }
}

(Error msg : The method findViewById(int) is undefined for the type new Runnable(){})

Robin Vinzenz
  • 1,247
  • 15
  • 19
  • I don't think adding text to a textview needs to be in a runnable at all. It's not the error but thought I'd comment on that. – Onimusha Feb 04 '16 at 22:36

2 Answers2

1

What you're trying to do is to get the reference of your TextView R.id.getMsg in the layout. You're using the findViewByIdmethod in an IntentService Class which does not provide this method. See Android Documentation

Normally you do that in an Activity or Fragment in lifecycle methods like onCreate or onCreateView etc. where the View is given as parameter value. That looks similar to the following line of code:

TextView textview = (TextView)view.findViewById(R.id.getMsg);

After you've retrieved your TextView reference, you're able to use it in implemented methods.

You need a way to handle data from your Intent Service back to your Application/Activity etc. A possible solution could be to pass your retrieved message data from the IntentService back to the Activity you could use a BroadcastReceiver (as shown here)

Community
  • 1
  • 1
Robin Vinzenz
  • 1,247
  • 15
  • 19
  • Thank you so much for your reply. I tried the below code, now I'm getting error at "view": [view cannot be resolved] public void showMsg(){ handler.post(new Runnable() { public void run() { TextView textview = (TextView)view.findViewById(R.id.getMsg); textview.setText(mes ); } – bharath bugs Feb 04 '16 at 23:33
0

Your textview is in service class and textview must be at activity class . If you want to set data in activity than create an interface or make textview public static.

Gevaria Purva
  • 552
  • 5
  • 15