Rohit Singh
Rohit Singh

Reputation: 18202

How to update UI from BroadcastReceiver

I know how to update UI from BroadcastReceiver(When BroadcaseReceiver is an inner class).
So here is what i am trying to achieve.
(FOR Test Purpose) I have an activity, which has a LinearLayout(R.id.parent) which has a child TextView(R.id.text). I want to update this TextView from Broadcast Receiver.
For that I am passing Parent view in BroadcastReceiver constructor.And inside onReceive(Context context,Intent i) i am setting value (textView,setText("something")). But i am getting NullPointerException. I debugged it and found that View received in constructor is null . What i am missing here ?

Here is the code snippet

public class CustomReceiver extends BroadcastReceiver {

View view;

public CustomReceiver (View v)    // <-- This v is null in Logs but it is not null in activity
{
    this.view = view;
}

@Override
public void onReceive(Context context, Intent intent) {


    if (intent.getAction().equalsIgnoreCase("Some String")) {

        TextView text= (TextView)view.findViewById(R.id.text);
         text.setText("WINTER IS COMING BRUH");
    }
}
}

This it the activity

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.seach_page_layout);

    text = (TextView)findViewById(R.id.text);
    IntentFilter filter = new IntentFilter();
    filter.addAction("Some String");
    View parent = (View)findViewById(R.id.parent);
    BroadcastReceiver receiver = new CustomReceiver (parent);    
    registerReceiver(receiver ,filter);
}

Here is the layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
 >

<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
   </LinearLayout>

Upvotes: 0

Views: 1716

Answers (2)

ColinK
ColinK

Reputation: 11

Variable 'view' is assigned to itself

public CustomReceiver (View v)   
{
    this.view = view; //  view -->v
}

Upvotes: 1

Meikiem
Meikiem

Reputation: 1936

You can not get view like this, you should inflate your root layout that your TextView is in it:

View view = View.inflate(context, R.layout.YOUR_ROOT_LAYOUT, null);

and then find your TextView from the view result :

TextView text = (TextView)view.findViewById(R.id.text);
text.setText("WINTER IS COMING BRUH");

Upvotes: 1

Related Questions