java - 将数组 [] 从 AsyncTask 返回到 Main Activity

标签 java android arrays android-listview android-asynctask

我正在尝试从我的 AsyncTask 返回一个数组到我的 Activity,因为我正在尝试从该数组创建一个 ListView。 不幸的是,程序出现了错误,因为它不允许我返回一个数组。我的代码如下:

主菜单类:

public class MainMenu extends Activity {
String username;
public String[] returnValue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);
    username ="user1";  

if (checkInternetConnection()) {

    try {
        MainAsyncTask mat = new MainAsyncTask(MainMenu.this);
        mat.execute(username);
    } catch (Exception e) {
        e.printStackTrace();
    }
} else {
    Toast.makeText(getApplicationContext(),"No internet connection. Please try again later",Toast.LENGTH_SHORT).show();
    }
}

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

private boolean checkInternetConnection() {
    ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    if (conMgr.getActiveNetworkInfo() != null
            && conMgr.getActiveNetworkInfo().isAvailable()
            && conMgr.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        return false;
    }
}}

主异步任务:

public class MainAsyncTask extends AsyncTask<String, Void, Integer> {
    private MainMenu main;
    private String responseText, http;
    private Ipaddress ipaddr = new Ipaddress(http);
    private Context context;

    public MainAsyncTask(MainMenu main) {
        this.main = main;
    }

    protected Integer doInBackground(String... arg0) {
        int responseCode = 0;
        try {
            HttpClient client = new HttpClient(main.getApplicationContext());
            Log.e("SE3", ipaddr.getIpAddress());
            HttpPost httpPost = new HttpPost(ipaddr.getIpAddress()
                    + "/MainServlet");

            List<NameValuePair> nvp = new ArrayList<NameValuePair>();

            JSONObject json = new JSONObject();
            json.put("username", arg0[0]);

            Log.e("SE3", arg0[0]);

            nvp.add(new BasicNameValuePair("data", json.toString()));
            httpPost.setEntity(new UrlEncodedFormEntity(nvp));

            HttpResponse response = client.execute(httpPost);

            if (response != null) {
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    try {
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(response.getEntity()
                                        .getContent()));
                        StringBuilder sb = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line);
                        }
                        responseText = sb.toString();
                    } catch (IOException e) {
                        Log.e("SE3", "IO Exception in reading from stream.");
                        responseText = "Error";
                    }
                } else {
                    responseText = "Error";
                }
            } else {
                responseText = "Response is null";
            }
        } catch (Exception e) {
            responseCode = 408;
            responseText = "Response is null";
            e.printStackTrace();
        }
        return responseCode;
    }

    protected void onPostExecute(Integer result) {
        if (result == 408 || responseText.equals("Error")
                || responseText.equals("Response is null")) {
            Toast.makeText(main.getApplicationContext(),
                    "An error has occured, please try again later.",
                    Toast.LENGTH_SHORT).show();
        } else {
            JSONObject jObj;
            try {
                jObj = new JSONObject(responseText);
                String folderString = jObj.getString("folder");

                String [] folders = folderString.split(";");    
                //I need to return folders back to MainMenu Activity
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

我的问题是我应该如何修改,以便我能够在我的连接保持不变的情况下读取我的数组。

最佳答案

我建议您像这样声明您的 MainAsyncTask:

public class MainAsyncTask extends AsyncTask<String, Void, String[]> {

然后修改 doInBackground 以执行您现在在 onPostExecute 中执行的所有处理(Toast 部分除外)并让它返回String[](如果有错误则为 null)。您可以将结果代码存储在 MainAsyncTask 的实例变量中,并在出错时返回 null。然后 onPostExecute 可以访问与当前代码相同的信息。最后,如果没有错误,只需在主 Activity 中从 onPostExecute 调用一个方法来执行 UI 更新,并将 String[] 结果传递给它。

关于java - 将数组 [] 从 AsyncTask 返回到 Main Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14670753/

相关文章:

javascript - 合并不同 id 的对象数组

java - 使用单个低位数字时,最小值和最大值不能正常工作

java - 是否可以在 java 中创建我自己的原始数据类型。像 int、float、double

java - servlet如何工作?实例化, session ,共享变量和多线程

java - 如果将多个 Intent 传递给服务,如何从 Intent 获取 bundle

android - 在地球上找到 2 个向量的交点

java - 如何分割字符串并保留特定的分隔符?

java - && 在 if() 中的重要性

android - 从 Apple Store 安装的应用程序会自动创建主屏幕快捷方式图标吗?

arrays - fatal error : Index out of range (Arrays)