Skip to content Skip to sidebar Skip to footer

How To Update TextView From A Class That Doesn't Extend Activity Class

I am New to Android. I am having a tough time with my code. Here is my problem. I have a TextView in my MainActivity which extends activity. And this textview has top be updated

Solution 1:

Create a field in your Adapter class and assign the instance of your text view, or using MainActivity.this.findViewById(...) or just findViewById(...) if your Adapter class is an inner non-static class of your MainActivity.

protected void onCreate(...) {
...
//I suppose you get your textView like this way
TextView textView = ((TextView) findViewById(...));
//I suppose your MainActivity extends from ListActivity
getListView().setAdapter(new YourAdapter(textView));
}

private static class YourAdapter extends BaseAdapter {
private TextView textView;
private YourAdapter(TextView textView) {
    this.textView = textView;
}
...
//somewhere
    this.textView.setText(".....");
}

or

// Inner non-static class
private class YourAdapter extends BaseAdapter {
...
//somewhere
    ((TextView) findViewById(...)).setText("...");
}

Solution 2:

I have solved my problem atlast. I added the below line in the method present in my other class. So now when the method is called, my textView changes its text automatically.

mymainActivity.textView_name.setText((new myCurrentclass_Name(this.context_name)).some_array[value]);

This is how I was allowed to change the text of my TextView which I had in my MainActivity.


Solution 3:

You can make your TextView static or you can take a field in your AdapterClass and pass that TextView to the Constructor of AdapterClass while you have finished all in AdapterClass your can update the TextView from AdapterClass

Edit:

say it is your AdapterClass:

public class AdapterClass extend BaseAdater..(blah blah)
{
    TextView textView;
    public AdapterClass(Context context, TextView view)
    {
                this.context = context;
                this.textView = view;
    }
     public View getView(int position, View convertView, ViewGroup viewGroup)
    {
        //do your task


        textView.setText("123 Results found");
    }
}

and in your Activity while declaring AdapterClass pass your textView to the constructor like:

AdapterClass adapter = new AdapterClass(this, textView);

Post a Comment for "How To Update TextView From A Class That Doesn't Extend Activity Class"