gpt4 book ai didi

android - 全局 ArrayList 和 AsyncTask 问题

转载 作者:太空狗 更新时间:2023-10-29 14:14:54 25 4
gpt4 key购买 nike

所以 AsyncTask 和我相处得不好。我正在尝试更好地了解它的使用方式。

所以我一直遇到这个问题,我通过 GSON AsyncTask 将 JSON API 加载到 ArrayList(称为 ratesList)中。调用成功。然后我尝试将 ratesList 内容复制到另一个名为 globalRates 的 ArrayList。这两个列表都是全局定义的。

为了确保两个列表都被填充,我从 onPostExecute 打印列表的大小并且都返回 158。

但是,一旦我尝试在 onCreate 方法上从 globalRates 列表中获取一个元素,我的程序就会崩溃。我尝试了一个 try/catch block 来查看我是否可以获得更多信息,并且错误以 NullPointerException 响应。我将在下面显示我的日志。

这是 MainActivity 类:

public class PostsActivity extends Activity {

// JSON info will be stored here through GSON
public static List<GlobalRates> ratesList = new ArrayList<GlobalRates>();

// Trying to copy contents of ratesList into this ArrayList
// Then trying to call an index from here on the onCreate method
public static List<GlobalRates> globalRates;

TextView view;

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

view = (TextView) findViewById(R.id.textView1);

BitRateFetcher br = new BitRateFetcher();
br.execute();

// Error comes here. Error keeps saying 'NullPointerException'
try {
String name = globalRates.get(0).getName();
} catch (NullPointerException ex) {
Log.e("BitRateFetcher", "Error: " + ex.fillInStackTrace());
Log.e("BitRateFetcher", "Error: " + ex.getLocalizedMessage());
}

// view.setText(name);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.posts, menu);
return true;
}

private void failedLoadingPosts() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(PostsActivity.this,
"Failed to load Posts. Have a look at LogCat.",
Toast.LENGTH_SHORT).show();
}
});
}

private class BitRateFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "BitRateFetcher";
public String BIT_PAY_SERVER = "https://bitpay.com/api/rates";

private ProgressDialog dialog;

@Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For
// example showing ProgessDialog
super.onPreExecute();
dialog = new ProgressDialog(PostsActivity.this);
dialog.setMessage("Please Wait... Downloading Information");
dialog.show();
}

@Override
protected String doInBackground(Void... params) {
try {
// Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpGet getBitRates = new HttpGet(BIT_PAY_SERVER);

// Perform the request and check the status code
HttpResponse bitRatesResponse = client.execute(getBitRates);

StatusLine bitRatesStatus = bitRatesResponse.getStatusLine();

if (bitRatesStatus.getStatusCode() == 200) {
HttpEntity entity = bitRatesResponse.getEntity();
InputStream content = entity.getContent();

try {
// Read the server response and attempt to parse it as
// JSON
Reader reader = new InputStreamReader(content);
Gson gson = new Gson();

ratesList = Arrays.asList(gson.fromJson(reader,
GlobalRates[].class));

content.close();
entity.consumeContent();
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: "
+ bitRatesStatus.getStatusCode());
failedLoadingPosts();
}
} catch (Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}

@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
globalRates = new ArrayList<GlobalRates>(ratesList);

// This shows both lists are populated.
Log.i(TAG, "Bit Rates Connected");
Log.i(TAG, "Rates List Size: " + ratesList.size());
Log.i(TAG, "Global Rates Size: " + globalRates.size());

if (dialog.isShowing()) {
dialog.dismiss();
}
}
}

这是“BitRateFetcher”日志:

04-20 22:13:55.626: E/BitRateFetcher(21097): Error: java.lang.NullPointerException
04-20 22:13:55.626: E/BitRateFetcher(21097): Error: null
04-20 22:13:56.206: I/BitRateFetcher(21097): Bit Rates Connected
04-20 22:13:56.206: I/BitRateFetcher(21097): Rates List Size: 158
04-20 22:13:56.206: I/BitRateFetcher(21097): Global Rates Size: 158

我最终要做的是从列表中抓取一个特定元素并通过 bundle 将其传递给 fragment (如果这是正确的方法)。

关于为什么会发生这种情况以及我该如何解决的任何想法?我什至尝试从 ratesList 调用一个元素,但它也崩溃了。

感谢您的帮助!

编辑:要查看它是否有更多帮助,这是关于我正在尝试做的事情的更多信息。当用户点击抽屉导航中的 ListView 时,将返回其位置编号。更多信息在代码中的注释中。这是代码:

private void displayView(int position) {
// update the main content by replacing fragments
Bundle bundle;
Fragment fragment = null;
String name;

switch (position) {
case 0:

// I want to get the name of a specific element depending on
// the position the user clicked. When i run the below line, it
// crashes and return the NullPointerException. globalRates is
// defined globally up top, similar to the code I pasted above.
name = globalRates.get( position).getName(); // <------ Crashes

// I will then pass the variable "name" into the bundle so
// that I can call it from the fragment.
bundle = new Bundle();
bundle.putString("message", "Test " + position);

fragment = new CoinFragment();
fragment.setArguments(bundle);
break;
case 1:
bundle = new Bundle();
bundle.putString("message", "Litecoin Info");

fragment = new CoinFragment();
fragment.setArguments(bundle);
break;
case 2:
bundle = new Bundle();
bundle.putString("message", "Peercoin Info");

fragment = new CoinFragment();
fragment.setArguments(bundle);
break;
case 3:
bundle = new Bundle();
bundle.putString("message", "Dogecoin Info");

fragment = new CoinFragment();
fragment.setArguments(bundle);
break;
case 4:
bundle = new Bundle();
bundle.putString("message", "Nxt Info");

fragment = new CoinFragment();
fragment.setArguments(bundle);
break;
case 5:
bundle = new Bundle();
bundle.putString("message", "Namecoin Info");

fragment = new CoinFragment();
fragment.setArguments(bundle);
break;

default:
break;
}

这可能不合适,但我真的需要通过 AsyncTask 调用 API 吗?我可以只实现一个新线程并做同样的事情吗?

最佳答案

您应该在 onPostExecute() 中移动以下内容;

// Error comes here. Error keeps saying 'NullPointerException'
try {
String name = globalRates.get(0).getName();
} catch (NullPointerException ex) {
Log.e("BitRateFetcher", "Error: " + ex.fillInStackTrace());
Log.e("BitRateFetcher", "Error: " + ex.getLocalizedMessage());
}

为什么?

因为 AsyncTask 在后台运行(换句话说在另一个线程中)。当您调用上面的代码时,它仍在处理中,因此 globalRates 列表仍然为空。
首先确保在使用 globalRates 之前调用 onPostExecute()。
当你打电话时

BitRateFetcher br = new BitRateFetcher();
br.execute();

程序不会等到 AsyncTask 完成后再跳转到下一行。
希望现在一切都清楚了。

关于android - 全局 ArrayList 和 AsyncTask 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23189879/

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