在继续mainActivity之前,如何设置doInbackground完成其任务?

时间:2015-08-03 07:00:22

标签: java android html mysql android-studio

这些是MainActivity

    database_connector wp_terms = new database_connector("SELECT * FROM  `dse120071750`.`wp_terms` ",progressDialog,this);
    wp_terms.execute();
    wp_terms.onPreExecute();
    try {

        for (int i=0; i<wp_terms.getJsonArray().length(); i++){
            JSONObject obj = wp_terms.getJsonArray().getJSONObject(i);
            this.wp_terms.put(obj.getString("term_id"), obj.getString("name"));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

DatabaseConnector:

package hk.hoome.www.mobilehoome;

public class database_connector extends AsyncTask<Void,Void, Void> {

//String mode;
HttpResponse response;
String sql;
JSONArray jsonArray;
searchPage searchPage;

public database_connector(String sql, searchPage searchPage){
    //this.mode = mode;
    this.sql = sql;
    this.searchPage = searchPage;
    jsonArray = new JSONArray();
}

@Override
protected Void doInBackground(Void... params) {
    connect();
    publishProgress();
    return null;
}



@Override
protected void onProgressUpdate(Void... values) {

}

public void connect() {
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
    nameValuePair.add(new BasicNameValuePair("sql", sql));
    //nameValuePair.add(new BasicNameValuePair("mode", mode));
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://www.hoome.hk/hoomeMobileApps/connectDB.php");
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
        response = httpClient.execute(httpPost);
        HttpEntity httpEntity  = response.getEntity();
        String entityResponse  = EntityUtils.toString(httpEntity);
        Log.e("Entity Response ", entityResponse.substring(2));
        jsonArray = new JSONArray(entityResponse.substring(2));

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}



public JSONArray getJsonArray(){
    return jsonArray;
}

}

当我运行此代码时,for (int i=0; i<wp_terms.getJsonArray().length(); i++){会产生nullPointerException

我认为这是因为doInbackground尚未完成其流程,但mainActivity仍在继续运行。如何在继续运行mainActivity之前设置doInbackground必须完成?

解吗

   try {
        while (wp_posts.getJsonArray().equals(null))
            Thread.sleep(1000);                 
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

这是一个很好的解决方案吗?

2 个答案:

答案 0 :(得分:1)

在数据库连接器类中使用回调并传递完成回调。为了简单起见,我使用的是Runnable接口。通常,尝试拥有自己的界面,并通过自定义界面在后台线程和主线程之间传递参数。

package hk.hoome.www.mobilehoome;

public class database_connector extends AsyncTask<Void,Void, Void> {

//String mode;
HttpResponse response;
String sql;
JSONArray jsonArray;
searchPage searchPage;
private Runnable activityCallback;

public void setCallback(Runnable callback) {
    this.activityCallback = callback;
}

public database_connector(String sql, searchPage searchPage){
    //this.mode = mode;
    this.sql = sql;
    this.searchPage = searchPage;
    jsonArray = new JSONArray();
}

@Override
protected Void doInBackground(Void... params) {
    connect();
    publishProgress();
    return null;
}

protected void onPostExecute(Void result) {

    if(activityCallback != null) {
        activityCallback.run();
    }
}


@Override
protected void onProgressUpdate(Void... values) {

}

public void connect() {
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
    nameValuePair.add(new BasicNameValuePair("sql", sql));
    //nameValuePair.add(new BasicNameValuePair("mode", mode));
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://www.hoome.hk/hoomeMobileApps/connectDB.php");
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
        response = httpClient.execute(httpPost);
        HttpEntity httpEntity  = response.getEntity();
        String entityResponse  = EntityUtils.toString(httpEntity);
        Log.e("Entity Response ", entityResponse.substring(2));
        jsonArray = new JSONArray(entityResponse.substring(2));

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}



public JSONArray getJsonArray(){
    return jsonArray;
}
}

在您的MainActivity中

database_connector wp_terms = new database_connector("SELECT * FROM  `dse120071750`.`wp_terms` ",progressDialog,this);
wp_terms.setCallback(new Runnable() {

        public void run() {

        try {

                for (int i=0; i<wp_terms.getJsonArray().length(); i++){
                    JSONObject obj = wp_terms.getJsonArray().getJSONObject(i);
                    this.wp_terms.put(obj.getString("term_id"),      obj.getString("name"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
    wp_terms.execute();

答案 1 :(得分:0)

我的一个项目也遇到了同样的问题,这可能会对你有所帮助

public class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(String...params) {
     String result;
     //background tasks here.
     return result;
 }

 protected void onPostExecute(String result) {
       //task after doInBackground here.

 }
 }

doInBackground(): 重写此方法以在后台线程上执行计算。

onPostExecute():

Runs on the UI thread after doInBackground(Params...). The specified result is the value returned by doInBackground(Params...).

This method won't be invoked if the task was cancelled.

Parameters
result  The result of the operation computed by doInBackground(Params...)

在onPostExecute(String result)方法中执行doInBackground方法中的后台任务和后台任务(显示toast或dialog)后的任务。 从doInBackground(String ... params)方法返回的结果将作为参数在result参数的onPostExecute(String result)方法中接收。

要使用此代码段,请从主活动中调用new DownloadFilesTask()。excute(param1,param2,...,paramn)。 这些参数将在参数中的doInBackground(String ... params)中接收。

Write in comment if you face any problem.

快乐的编码!!!