我怎样才能在onPostExecute()中调用方法?

时间:2016-07-04 09:13:23

标签: android

我想将值传递给HTTP POST并获得一些结果,但是我从服务器获取结果时遇到小问题。所有内容都在同一个文件中

我的Asycn任务

 private class GetCustomerDataTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {
            // params comes from the execute() call: params[0] is the url.
            try {
                return downloadUrl(urls[0]);
            } catch (IOException e) {
                return "Unable to retrieve web page. URL may be invalid.";
            }
        }

        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            parseData(result);// i am going to call method here
        }
    }

private String downloadUrl(String myurl) throws IOException {
        InputStream is = null;
        // Only display the first 500 characters of the retrieved
        // web page content.
        int len = 500;

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("cus_name", cus_names));
        params.add(new BasicNameValuePair("created_date1", createddate));
        params.add(new BasicNameValuePair("created_date2", created_date));

        //String urlParameters ="cus_name=" + URLEncoder.encode(cus_names, "UTF-8") + "&created_date1=" + URLEncoder.encode(createddate, "UTF-8") + "&created_date2=" + URLEncoder.encode(created_date, "UTF-8");

        String urlParameters = URLEncoder.encode("cus_name", "UTF-8")+ "=" + URLEncoder.encode(cus_names, "UTF-8");
        urlParameters += "&" + URLEncoder.encode("created_date1", "UTF-8") + "=" + URLEncoder.encode(createddate, "UTF-8");
        urlParameters += "&" + URLEncoder.encode("created_date2", "UTF-8") + "=" + URLEncoder.encode(created_date, "UTF-8");

        URL url;
        HttpURLConnection connection = null;
        try {
            //Create connection
            url = new URL(myurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //Send request
            DataOutputStream wr = new DataOutputStream(
                    connection.getOutputStream());
            wr.writeBytes(getQuery(params));
            wr.flush();
            wr.close();
            //Get Response
            is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            System.out.println(response);
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();

        } catch (Exception e) {

            e.printStackTrace();
            return null;

        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }

    }


    private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (NameValuePair pair : params) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8").replace("+", "%20"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8").replace("+", "%20"));
        }

        return result.toString();
    }

如果是对或错,因为我的应用程序不幸被停止。我认为这是正确的方式(可能是)。

我的ParseData方法

public void parseData(String result) {
    try {
        JSONObject parentObject = new JSONObject(result);
        JSONArray data = parentObject.getJSONArray("sales_customer_repo");

        //JSONArray data = new JSONArray(getJSONUrl(url,params));
        ArrayList<CustomerData> customerArrayList = new ArrayList<CustomerData>();
        for (int i = 0; i < data.length(); i++) {
            JSONObject c = data.getJSONObject(i);
            String S_No = c.getString("S_No");
            String createdDate = c.getString("created_date");
            String orderNo = c.getString("order_no");
            String goods_name = c.getString("goods_name");
            String supply_qty = c.getString("supply_qty");
            customerArrayList.add(new CustomerData(S_No, createdDate, orderNo, goods_name, supply_qty));
        }
        ImageAdapter imageAdapter = new ImageAdapter(this, customerArrayList);
        listView1 = (ListView) findViewById(R.id.listview_customername);
        listView1.setAdapter(imageAdapter);
        imageAdapter.notifyDataSetChanged();
        registerForContextMenu(listView1);


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

调试我的应用程序此行以达到让我的应用程序崩溃

JSONObject parentObject = new JSONObject(result); JSONArray data = parentObject.getJSONArray(&#34; sales_customer_repo&#34;);

logcat的:

07-04 15:43:59.775 12998-12998/com.example.vari.new_varri E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.vari.new_varri, PID: 12998
                                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                                                                                at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
                                                                                at org.json.JSONTokener.nextValue(JSONTokener.java:94)
                                                                                at org.json.JSONObject.<init>(JSONObject.java:156)
                                                                                at org.json.JSONObject.<init>(JSONObject.java:173)
                                                                                at com.example.vari.new_varri.Sales_Customers_wise.parseData(Sales_Customers_wise.java:311)
                                                                                at com.example.vari.new_varri.Sales_Customers_wise$GetCustomerDataTask.onPostExecute(Sales_Customers_wise.java:191)
                                                                                at com.example.vari.new_varri.Sales_Customers_wise$GetCustomerDataTask.onPostExecute(Sales_Customers_wise.java:176)
                                                                                at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:0)

这对我有用,请检查您使用带有协议的正确网址(http://www.ursite.com):

x <- sample(
    seq(as.Date('1000/01/01'), as.Date('2000/01/01'), by="day"),
    400000, replace = T)

system.time({
    y <- substr(x, 1, 4)
    m <- substr(x, 6, 7)
    d <- substr(x, 9, 10)
})
# user  system elapsed 
# 3.775   0.004   3.779 

system.time({
    y <- format(x,"%y")
    m <- format(x,"%m")
    d <- format(x,"%d")
})
# user  system elapsed 
# 1.118   0.000   1.118 

system.time({
    y <- year(x)
    m <- month(x)
    d <- day(x)
})
# user  system elapsed 
# 0.951   0.000   0.951 

x1 <- as.character(x)
system.time({
    y <- substr(x1, 1, 4)
    m <- substr(x1, 6, 7)
    d <- substr(x1, 9, 10)
})
# user  system elapsed 
# 0.082   0.000   0.082