2

How can I add view bye function, outside of onCreate() in Android ?

My MainActivity.java

public class Main extends Activity {

    static RelativeLayout mainRel;
    static LinearLayout ll;
    static TextView title;
    static Context context;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
        RelativeLayout mainRel=(RelativeLayout) findViewById(R.id.mainRel);
    }

    public static void refresh(){
            LinearLayout ll = new LinearLayout(this); // actually "this" just works in onCreate;
            TextView title = new TextView(this);// actually "this" just works in onCreate;
            ll.setOrientation(LinearLayout.HORIZONTAL);
            ll.addView(title);
            title.setText("TV");
            mainRel.addView(ll);
        }
    }
}

Thanks in advance

Drew McGowen
  • 11,471
  • 1
  • 31
  • 57
FaridFaa
  • 88
  • 10

2 Answers2

3

Usually, UI-related operations are not done in static methods. If you remove the static keyword, the this pointer will work even outside onCreate().

If you insist on keeping the static keyword (because you need the method to be static) then, you should pass a Context parameter to the method, by changing it to refresh(Context context)

Edit: if you need to call this method from another class, you might want to create a reference to your Main Activity and pass it to this other class, then call myMainActivity.refresh()

Karim
  • 5,298
  • 3
  • 29
  • 35
1

Calling static method is really bad idea.

Instead you can provide reference of the Activity to your AsyncTask in constructor. Then call non-static refresh() method from AsyncTask#onPostExecute().

When you store reference to Activity in AsyncTask use WeakReference. In case your activity is destroyed while background task is working, it won't be held in memory till background ends.

public class YourAsyncTask extends AsyncTask<Void, Void, Void> {

    private WeakRefrence<Main> mainRef;
    public YourAsyncTask(Main activity) {
        mainRef = new WeakReference<Main>(activity);
    }

    protected void onPostExecute(Void result) {
        Main main = mainRef.get();
        if (main != null) {
            main.refresh();
        }
    }
}
Damian Petla
  • 8,963
  • 5
  • 44
  • 47