gpt4 book ai didi

java - 如何在异步方法之外获取列表的值?

转载 作者:行者123 更新时间:2023-11-29 02:35:04 25 4
gpt4 key购买 nike

我已经在另一个stackoverflow帖子上搜索了2个小时,但仍然无法解决这个问题。我在 DetailMemilihIqro Activity 类中有一个名为 copyAudioListIqro 的变量,其数据类型为 List String。当 AsyncTask 类中名为 audioIqros 的变量(恰好在 onPostExecute 方法中)此列表具有来 self 的 json 的值 并且我想复制 audioIqros 变量到 copyAudioListIqro 通过 updateData 方法(在 asynctask 类之外)。当我在 updateData 方法上看到日志监视器时,我可以看到来自 copyAudioListIqro 的值,但问题是,当我通过 readDataAudioURL 方法(在 asynctask 之外)访问它时class) copyAudioListIqro 变量变为空。

这个问题的解决方案是什么?谢谢

这是整体的 DetailMemilihIqro 类

public class DetailMemilhIqro extends AppCompatActivity {

private ProgressDialog pDialog;
private List<ModelAudioIqro> audioIqros;
private List<String> copyAudioListIqro;
private AudioAdapter mAdapter;
private RecyclerView recyclerView;
private String TAG = DetailMemilihIqro.class.getSimpleName();
Context context;


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

recyclerView = (RecyclerView) findViewById(R.id.rvCVAudioIqro);
pDialog = new ProgressDialog(this);
audioIqros = new ArrayList<>();
mAdapter = new AudioAdapter(getApplicationContext(), audioIqros);
context = getApplicationContext();
copyAudioListIqro = new ArrayList<>();


recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);

Bundle getPosition = getIntent().getExtras();
int position = getPosition.getInt("positionUserClicked");
Log.d(TAG, "Position User clicked " + position);

if (position == 0) {
String endpoint = "http://latihcoding.com/jsonfile/audioiqro1.json";

new DownloadTask().execute(endpoint);


} else if (position == 1) {
String endpoint = "http://latihcoding.com/jsonfile/audioiqro2.json";
new DownloadTask().execute(endpoint);


} else if (position == 2) {
String endpoint = "http://latihcoding.com/jsonfile/audioiqro3.json";
new DownloadTask().execute(endpoint);

}

readDataAudioURL();

}

public void updateData(List<String> pathUrl) {

for (int i = 0; i < pathUrl.size(); i++) copyAudioListIqro.add(pathUrl.get(i));
Log.d(TAG, "updateData Method " + copyAudioListIqro.toString());

}

public void readDataAudioURL() {
Log.d(TAG, "readDataAudioURL Method " + copyAudioListIqro.toString());
}

public class DownloadTask extends AsyncTask<String, Void, List<String>> {

List<String> modelAudioIqroList;

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Downloading json...");
pDialog.show();
}

@Override
protected List<String> doInBackground(String... strings) {
modelAudioIqroList = new ArrayList<>();
int result;
HttpURLConnection urlConnection;
try {
URL url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();

// 200 represents HTTP OK
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
Log.d(TAG, "Result " + result);

} else {
//"Failed to fetch data!";
result = 0;
Log.d(TAG, "Result " + result);
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return modelAudioIqroList; //"Failed to fetch data!";

}

@Override
protected void onPostExecute(List<String> audioIqros) {
super.onPostExecute(audioIqros);
pDialog.hide();
if (!audioIqros.isEmpty()) {
updateData(modelAudioIqroList);
} else {
Toast.makeText(context, "Empty", Toast.LENGTH_SHORT).show();
}
}

private void parseResult(String result) {
try {
JSONArray response = new JSONArray(result);

for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
ModelAudioIqro modelAudioIqro = new ModelAudioIqro();
modelAudioIqro.setName(object.getString("name"));
modelAudioIqro.setUrl(object.getString("url"));
String path = modelAudioIqro.getUrl();
Log.d(TAG, "String path " + path);

modelAudioIqroList.add(path);
}
} catch (JSONException e) {
e.printStackTrace();
}

mAdapter.notifyDataSetChanged();
}

}

}

Log for the copyAudioListIqro in the updateDataMethod

Log for the copyAudioListIqro in the readDataAudioURL

最佳答案

readDataAudioURL() 调用,这是一个普通的 Log 调用,应该被移动。事实上,任务本质上是异步的,所以变量copyAudioListIqro不会在任务开始后立即初始化(.execute()方法)。

无论如何,您做对了,在 notyfiying 数据集更改为列表中...您也应该将其移动到 postExecute...

我建议将所有“after network”代码移动到 postExecute,这样 UI 就可以仅在数据可用时异步更新,而不会阻塞主线程。您可以在内部类中“读取”变量,因此只需将它们声明为 final:

@Override
protected void onPostExecute(List<String> audioIqros) {
super.onPostExecute(audioIqros);
pDialog.hide();
if (!audioIqros.isEmpty()) {
updateData(modelAudioIqroList);
//data is now updated, notify datasets and/or send broadcast
mAdapter.notifyDataSetChanged();
readDataAudioURL();
} else {
Toast.makeText(context, "Empty", Toast.LENGTH_SHORT).show();
}

}

更详细的模式将包括广播接收器和 Intent ,但我想这超出了这个问题的范围。

关于java - 如何在异步方法之外获取列表的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47537423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com