需要帮助了解如何在类到类之间存储和访问变量

时间:2014-11-18 00:19:36

标签: java android class bundle

如果我在AsyncTask中的onPostExecute()内创建一个微调器,我可以将它的值存储在该类中,然后从另一个类中检索它。或者我如何将它存储在Bundle中?

 private class CallEventList extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {
        return readEventJSONFeed("service call", null);
    }

    protected void onPostExecute(String result){
        try {
        ...
        //....create the spinner....
                event_spinner.setAdapter(eAdapter);

                event_spinner.setOnItemSelectedListener(..... // create the listener
                //removed code for easy reading......

                    String selected_event = event_spinner.getSelectedItem().toString();
                    //Here I want to store the value for use in another class.


                    }
        }
}

1 个答案:

答案 0 :(得分:0)

您可以将字符串selected_event设为静态而不是方法变量,而是使用第一类。 但我不建议尽可能简单。

另一种方法是使用回调,为CallEventList创建类似于此

的构造函数
CallBackNamedHowYouLike mCallback;
public CallEventList(CallBackNamedHowYouLike callback){
    this.mCallback = callback;
}

然后在你的帖子中执行......

protected void onPostExecute(String result){
    try {
    ...
    //....create the spinner....
            event_spinner.setAdapter(eAdapter);

            event_spinner.setOnItemSelectedListener(..... // create the listener
            //removed code for easy reading......

                String selected_event = event_spinner.getSelectedItem().toString();
                //Here I want to store the value for use in another class.
                callback.aMethodWhereYouUseSelectedEvent(selected_event);

                }
    }

假设您从要使用该字符串的类中调用此asynctask,那么我将发明该类

public class TheClassFromWhereYouNeedTheString implements CallBackNamedHowYouLike {
...//a lot of your code is here

@Override
public void aMethodWhereYouUseSelectedEvent(String selected_event){
this.yourString = selected_event;
}

}

最后界面就是这个......

public interface CallBackNamedHowYouLike{
void aMethodWhereYouUseSelectedEvent(String selected_event);
}