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.

protectedvoidonCreate(...) {
...
//I suppose you get your textView like this wayTextViewtextView= ((TextView) findViewById(...));
//I suppose your MainActivity extends from ListActivity
getListView().setAdapter(newYourAdapter(textView));
}

privatestaticclassYourAdapterextendsBaseAdapter {
private TextView textView;
privateYourAdapter(TextView textView) {
    this.textView = textView;
}
...
//somewherethis.textView.setText(".....");
}

or

// Inner non-static classprivateclassYourAdapterextendsBaseAdapter {
...
//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((newmyCurrentclass_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:

publicclassAdapterClass extend BaseAdater..(blah blah)
{
    TextView textView;
    publicAdapterClass(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:

AdapterClassadapter=newAdapterClass(this, textView);

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