【问题标题】:Set a variable in a class method to be accessed in a background (async) task class (Java/Android)在要在后台(异步)任务类(Java/Android)中访问的类方法中设置变量
【发布时间】:2017-04-16 13:57:53
【问题描述】:

我正在尝试设置一个变量 'election_id' 从上一课获得额外的意图。我需要使用 id 将其解析为 PHP URL 以检索一些 JSON。我想要做的是将一个变量设置为与前一个类中分配的选举 ID 相同,以便在后台任务中使用:

public class AdminFinishCandidateActivity extends AppCompatActivity {

String json_string;
String json_string_result;

String election_id;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_admin_finish_candidate);

    System.out.println("creating");

    Bundle electionData = getIntent().getExtras();
    if (electionData==null) {
        return;
    }

    election_id = electionData.getString("electionId");

}



public void getJson(View view){

    new BackgroundTask().execute();

}


class BackgroundTask extends AsyncTask<Void,Void,String> {



    String json_url="http://192.168.56.1/dan/db/getjson.php?election_id=" + election_id;


// code to retrieve JSON
    }
}
}

目前,在我的 onCreate 方法中分配了election_id,但是我知道我无法从我定义 String json_url 的 BackgroundTask 类中的此方法访问它。我该如何做才能在这个类中调用election_id 变量?检索意图附加内容的方法在此类中不起作用。当我使用 JSON 代码运行代码时,没有检索到任何内容。谢谢。

【问题讨论】:

    标签: java android android-asynctask background-task


    【解决方案1】:

    您可以将字符串传递给 AsyncTask,如下所示:

    public class BackgroundTask extends AsyncTask<String,Void,String>{
    
        @Override
        protected String doInBackground(String... params) {
        String json_url="http://192.168.56.1/dan/db/getjson.php?election_id=" + params[0];
    
          //perform network operation and return response
          return response;
        }
    
        @Override
        protected void onPostExecute(String res){
          //Batman Rocks
        }
    }
    

    现在执行如下任务:

    new BackgroundTask().execute(election_id);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多