【问题标题】:Can't set activity's variable from class method无法从类方法中设置活动的变量
【发布时间】:2017-12-04 16:20:06
【问题描述】:

注意:我在术语方面做得不是很好,因为这是我第一次接触面向对象的编程和 android studio。

在 android studio 中,我为 JSON 获取任务创建了一个类。 (我不包括后台覆盖中的 do)。

public class jsonTasks extends AsyncTask<String, String, String> {


public interface AsyncResponse {
    void processFinish(String output);
}

private AsyncResponse delegate = null;

jsonTasks(AsyncResponse delegate){
    this.delegate = delegate;
}

@Override
protected void onPostExecute(String result) {
    delegate.processFinish(result);
}

现在在我的活动中:

public class activity extends Activity {
    // in here I've declared the string variable
    String valuableInfo;

    // FIRST TASK
    jsonTasks asyncTask = new jsonTasks(new jsonTasks.AsyncResponse() {

        @Override
        public void processFinish(String output) {
            String TAG = activity.class.getSimpleName();
            JSONObject info;

            //i do stuff with the json here
            //i set the textboxes normally
            txtSumName.setText(sumInfo.getString("name"));

            //but setting the string valuableInfo is not working
            valuableInfo = "info I took from json operation"

        });
    // and here I execute
    asyncTask.execute("url");

    // SECOND TASK
    jsonTasks asyncTask2 = new .... {
    .................
    }
    asyncTask2.execute("https://example.com/" + valuableInfo);
}

我想使用该变量的地方是另一个“asyncTask2”,它使用 URL 上的有价值信息继续获取。

当我运行第二个“asyncTask2”时,该变量始终为空。

【问题讨论】:

    标签: java android json variables android-asynctask


    【解决方案1】:

    AsyncTask 异步执行操作。这意味着您不会立即得到结果,您必须等到它完成才能使用valueableInfo。有一个方法可以覆盖,它叫做onPostExecute。这将在您的任务完成并且信息可用时触发。在此处执行您的第二个任务,此时它不会为空。

    也许您也可以合并这两个任务?

    【讨论】:

    • 对不起,我在代码上添加了 onPostExecute 方法覆盖。这一切都在 onPostExecute 上执行。 (编辑了主帖)我认为这与变量声明有关。我不太确定。
    • 第二个 AsyncTask 还没有等待 processFinishe 回调。将 asyncTask2.execute() 放在 processFinish() 的最后一行
    • 从上面的代码中,您创建了两个 jsonTask。试试 new jsonTask(JsonTask.Response { }) 之类的东西,不要两次使用 'new' 关键字。
    猜你喜欢
    • 2019-08-14
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    相关资源
    最近更新 更多