How to get TextView text widget from Activity?

I have a widget and activity, when I run an action, I need to read the text from the TextView widget and show it in the TextWidget activity.

My corresponding code is:

String frase=""; TextView text_frase = (TextView) findViewById(R.id.widget_textview_frase); if (text_frase != null){ frase = (String) text_frase.getText(); } Log.v(LOG_CLASS_NAME, "frase: "+frase); 

debugging it - I have text_frase as null (I think I can not refer to the view object from another view.) In any case, how could I do this?

+1
source share
2 answers

No, you can’t. I suggest one of the following ways:

  • Adding your text to the Bundle and selecting it in your activity.

in your widget:

 Intent intent = new Intent(context, YourActivity.class); Bundle b= new Bundle(); b.putString("Text", yourtext); intent.putExtras(b); PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT); 

in your activity:

 Intent intent=getIntent(); Bundle b= intent.getExtras(); String text= b.getString("Text", ""); 
  1. Using SharedPreferences to save text and load it into action.

In your situation, I recommend method 1.

+4
source

you might want to get the actual string using the .toString () method in a TextView.

 String frase; TextView text_frase = (TextView) findViewById(R.id.widget_textview_frase); if (text_frase.getText().toString() != null){ frase = (String) text_frase.getText().toString(); Log.v(LOG_CLASS_NAME, "frase: "+frase); } 
0
source

Source: https://habr.com/ru/post/1401962/


All Articles