doInBackground null异常

时间:2014-08-10 12:52:37

标签: android

首先,很明显我不是机器人专家..

在我的应用程序中,我有从服务器发送和接收数据的活动。但是在那个特定的活动中,我只想启动一个php脚本(不放任何参数),它从数据库中选择数据并将它们发送回活动。 LogCat说,问题在于doInBackground方法。

由于

活动

package com.example.tranfer;

import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DataInsert extends Activity{

Button buttonresults ;
TextView abc;
private static final String LOGIN_URL = "http://xxxxxxxxxxxxxxxxx";
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.data_insert);



    buttonresults = (Button)findViewById(R.id.buttonresults);
    buttonresults.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new TakeResults().execute();
        }

    });

}

 class TakeResults extends AsyncTask<Void,String,JSONObject>{

     public void onPreExecute() {
            super.onPreExecute();
            Log.d("meg", "meg");

            pDialog = new ProgressDialog(DataInsert.this);
            pDialog.setMessage("Καταχωρώ τα στοιχεία...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

    protected JSONObject doInBackground(JSONObject... params) {
        // TODO Auto-generated method stub
        JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", null);
        return json;
    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        Log.d("mega", "mega");
        if (file_url != null) {
            Toast.makeText(DataInsert.this, file_url, Toast.LENGTH_LONG)
                    .show();
        }

    }
}
}

JSONParser

package com.example.tranfer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}


public JSONObject getJSONFromUrl(final String url) {

    // Making HTTP request
    try {
        // Construct the client and the HTTP request.
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // Execute the POST request and store the response locally.
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // Extract data from the response.
        HttpEntity httpEntity = httpResponse.getEntity();
        // Open an inputStream with the data content.
        is = httpEntity.getContent();

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

    try {
        // Create a BufferedReader to parse through the inputStream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"));

        // Declare a string builder to help with the parsing.
        StringBuilder sb = new StringBuilder();
        // Declare a string to store the JSON object data in string form.
        String line = null;

        // Build the string until null.
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        // Close the input stream.
        is.close();
        // Convert the string builder data to an actual string.
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // Try to parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // Return the JSON Object.
    return jObj;

}


// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));//ךכבר..ךכבר..
            // נףן לו נב‗הורו........
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params,"utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           

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

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        Log.d("JSONParser", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
        Log.d("JSONParser2", jObj.toString());

    } catch (JSONException e) {
        Log.d("wrong2", jObj.toString());
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

phpscript

 <?php
    $con=mysql_connect("localhost","xxxxx","xxxxxx" );
    $database = "etruck1";
    $ok = mysql_select_db($database, $con);
    mysql_set_charset("UTF8", $con);

    $sql = mysql_query( "SELECT startPoli1 , finalPoli1 FROM customer ");
    if($sql === FALSE) 
    { 
    die(mysql_error()); 
    }
    $results = array();
    while($row = mysql_fetch_array($sql))
    {
   $results[] = array(
        'startPoli1' => $row['startPoli1'],
        'finalPoli1' => $row['finalPoli1'],     
         );
         echo $row['startPoli1'];        
         echo $row['finalPoli1'];
    }
    echo json_encode($results, JSON_UNESCAPED_UNICODE );
    mysql_close($con); 
    ?>

logcat的

08-10 15:59:52.543: E/AndroidRuntime(14696): FATAL EXCEPTION: AsyncTask #2
08-10 15:59:52.543: E/AndroidRuntime(14696): java.lang.RuntimeException: An error occured while executing doInBackground()
08-10 15:59:52.543: E/AndroidRuntime(14696):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-10 15:59:52.543: E/AndroidRuntime(14696):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-10 15:59:52.543: E/AndroidRuntime(14696):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-10 15:59:52.543: E/AndroidRuntime(14696):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-10 15:59:52.543: E/AndroidRuntime(14696):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-10 15:59:52.543: E/AndroidRuntime(14696):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-10 15:59:52.543: E/AndroidRuntime(14696):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-10 15:59:52.543: E/AndroidRuntime(14696):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-10 15:59:52.543: E/AndroidRuntime(14696):    at java.lang.Thread.run(Thread.java:856)
08-10 15:59:52.543: E/AndroidRuntime(14696): Caused by: java.lang.NullPointerException
08-10 15:59:52.543: E/AndroidRuntime(14696):    at org.apache.http.client.utils.URLEncodedUtils.format(URLEncodedUtils.java:160)
08-10 15:59:52.543: E/AndroidRuntime(14696):    at com.example.tranfer.JSONParser.makeHttpRequest(JSONParser.java:118)
08-10 15:59:52.543: E/AndroidRuntime(14696):    at com.example.tranfer.DataInsert$TakeResults.doInBackground(DataInsert.java:62)
08-10 15:59:52.543: E/AndroidRuntime(14696):    at com.example.tranfer.DataInsert$TakeResults.doInBackground(DataInsert.java:1)
08-10 15:59:52.543: E/AndroidRuntime(14696):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-10 15:59:52.543: E/AndroidRuntime(14696):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-10 15:59:52.543: E/AndroidRuntime(14696):    ... 5 more

2 个答案:

答案 0 :(得分:0)

是的问题在于AsyncTask,你应该像AsseTask那样传递参数

class TakeResults extends AsyncTask<Void,String,JSONObject>{

     public void onPreExecute() {
            super.onPreExecute();
            Log.d("meg", "meg");

            pDialog = new ProgressDialog(DataInsert.this);
            pDialog.setMessage("Καταχωρώ τα στοιχεία...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

    protected JSONObject doInBackground(Void... params) {
        // TODO Auto-generated method stub
        JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", null);
        return json;
    }

    protected void onPostExecute(JSONObject file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        Log.d("mega", "mega");
        if (file_url != null) {
            Toast.makeText(DataInsert.this, file_url, Toast.LENGTH_LONG)
                    .show();
        }

    }

答案 1 :(得分:0)

您将null作为第三个参数传递给makeHttRequest方法。

JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", null);

null作为第一个参数传递给以下方法。

String paramString = URLEncodedUtils.format(params,"utf-8");

这导致了NPE。