【问题标题】:Android inner class AsyncTask return null ArrayListAndroid内部类AsyncTask返回null ArrayList
【发布时间】:2015-04-29 18:48:35
【问题描述】:

我试图返回通过从 AsyncTask 派生的内部类解析 XML 获得的 ArrayList,但是即使我在上层类中声明 ArrayList 变量提要,系统也会给我一个 null ArrayList。

public class ListFeed extends ListActivity {
public static final String WIFI = "Wi-Fi";
public static final String ANY = "Any";
private static final String URL = "http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest";

// Whether there is a Wi-Fi connection.
private static boolean wifiConnected = false;
// Whether there is a mobile connection.
private static boolean mobileConnected = false;
// Whether the display should be refreshed.
public static boolean refreshDisplay = true;
public static String sPref = null;

private ArrayList feed = new ArrayList();


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

    new DownloadXmlTask().execute(URL);
    Log.d("feed size", Integer.toString(feed.size()));


    ListView listView = getListView();

    setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_list_feed,feed));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}


// Given a string representation of a URL, sets up a connection and gets
// an input stream.
private InputStream downloadUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    return conn.getInputStream();
}

// Uploads XML from stackoverflow.com, parses it, and combines it with
// HTML markup. Returns HTML string.
private ArrayList loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
    InputStream stream = null;
    // Instantiate the parser
    StackOverFlowXmlParser stackOverflowXmlParser = new StackOverFlowXmlParser();
    List<StackOverFlowXmlParser.Entry> entries = null;
    String title = null;
    String url = null;
    String summary = null;
    Calendar rightNow = Calendar.getInstance();
    // Checks whether the user set the preference to include summary text
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean pref = sharedPrefs.getBoolean("summaryPref", false);

    // List to store the items
    //ArrayList<String> feed = new ArrayList<String>();

    try {
        stream = downloadUrl(urlString);
        entries = stackOverflowXmlParser.parse(stream);
        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
    for (StackOverFlowXmlParser.Entry entry : entries) {
        feed.add(entry.title);
    }


    //return arraylist of string
    return feed;
}

// Implementation of AsyncTask used to download XML feed from stackoverflow.com.
private class DownloadXmlTask extends AsyncTask<String, Void, ArrayList> {
    @Override
    protected ArrayList doInBackground(String... urls) {
        try {
            return loadXmlFromNetwork(urls[0]);
        } catch (IOException e) {
            //return getResources().getString(R.string.connection_error);
            return null;
        } catch (XmlPullParserException e) {
            //return getResources().getString(R.string.xml_error);
            return null;
        }
    }

    @Override
    protected void onPostExecute(ArrayList result) {
        //setContentView(R.layout.activity_list_feed);
        Log.d("feed size 2", Integer.toString(feed.size()));

    }
}

}

【问题讨论】:

  • 日志异常 - Log.e(TAG, "", e);在doInBackground
  • 您在异常时返回 null,您是否遇到任何异常?
  • 你必须在返回数组之前查看它是否为空。另外,看看是否有异常和你的一个 catch 语句返回 null。
  • 添加登录doInBackGroound avec 编译错误信息:java.lang.IllegalStateException:适配器的内容已更改但ListView 没有收到通知。确保适配器的内容不是从后台线程修改的,而只是从 UI 线程修改的。 [在 ListView(16908298, class android.widget.ListView) with Adapter(class android.widget.ArrayAdapter)]
  • 根据日志,"feed size" 打印 0,而 "feed size 2" 打印 31,所以 feed 变量在 DoanloadXmlTask​​ 之外为 null

标签: android arraylist android-asynctask


【解决方案1】:

通过放置

解决了这个问题
ListView listView = getListView();
setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_list_feed,feed));

onPostExecute() 方法中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    相关资源
    最近更新 更多