簡體   English   中英

Android NullPointer異常AsyncTask

[英]Android NullPointer Exception AsyncTask

我想使用asyncTask發送帶有附件的消息,我的php代碼還可以..因為當上傳小尺寸文件時,一切都可以,當我發送不帶附件的消息時,一切都將如我所願..但是,當上傳大尺寸文件時(像> 6 Mb的apk文件)我在此行中得到了空指針異常:(在onPostExecute中查看)

                success2 = json2.getInt("success");

這是asyncTasck

  public class PostDataAsyncTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... strings) {
                try {
       uploadFile(fichier);
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }

    @Override
    protected void onPostExecute(String lenghtOfFile) {
        int  success2= 0;
        try {
            success2 = json2.getInt("success");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(success2==1) {
            ((EditText) findViewById(R.id.etMsg)).setText("");
            if (attach) {
                changerAttach();
                }     }
     } }

這是上載functopn:

  private void uploadFile(String filePath) {
    try {
        try {

            HttpPost httpost = new HttpPost(url_upload);
            MultipartEntity entity = new MultipartEntity();
            entity.addPart("Mdp", new StringBody(mdp));
            entity.addPart("Msg", new StringBody(URLEncoder.encode(msg)));
            entity.addPart("type", new StringBody(type));
            if(type.equals("1")) {
                entity.addPart("Emailm", new StringBody(email));
                entity.addPart("Emailp", new StringBody(emaildest));
            }else {
                entity.addPart("Emailp", new StringBody(email));
                entity.addPart("Emailm", new StringBody(emaildest));
            }
            if (attach){
                entity.addPart("attachement", new FileBody(new File(filePath)));
                entity.addPart("attacher", new StringBody("oui"));
            }else{
                entity.addPart("attacher", new StringBody("non"));
            }

            httpost.setEntity(entity);
            HttpResponse response;
            HttpClient httpclient = new DefaultHttpClient();
            response = httpclient.execute(httpost);

            if (response != null) {
                HttpEntity entity2 = response.getEntity();
                String responseString = EntityUtils.toString(entity2, "UTF-8");
                System.out.println(responseString);
                json2=new JSONObject(responseString);

            } else { //erreur
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }catch (Exception e){

    }
}

注意字符串“ fichier ”我要加載的文件的路徑。

attach是布爾變量,表示我選擇了要上傳的文件。

json2是全局變量(JSONObject),將在上載函數中初始化

我認為這是您需要的(PHP代碼還可以)

注意:我認為並發是導致我的問題的原因,這是真的嗎? 非常感謝

編輯 upload.php

    <?php  
date_default_timezone_set ("Africa/Algiers");
include('connect.php');
$response = array();

if (isset($_REQUEST['Emailm'])&& isset($_REQUEST['Mdp'])&&isset($_REQUEST['type']) && isset($_REQUEST['Emailp'])&&isset($_REQUEST['Msg'])  ) {


    $Emailm = $db->real_escape_string($_REQUEST['Emailm']);  
    $Emailp = $db->real_escape_string($_REQUEST['Emailp']); 
    $Mdp = $db->real_escape_string($_REQUEST['Mdp']);  
    $Msg = $_REQUEST['Msg'];  
    $Mdp = $_REQUEST['Mdp'];  
    $Msg= $db->real_escape_string(htmlentities(urldecode($Msg)));    
    $type= $_REQUEST['type'];
    $target_path1 = "attachement/";   
    if($type=="0"){  //compte patient
    if ($result = $db->query("SELECT * FROM `patient` WHERE `Email_p`='$Emailp' AND `Mdp`='$Mdp'")) {
    $row_cnt = $result->num_rows; }
     }else {  //compte médecin
    if ($result = $db->query("SELECT * FROM `med` WHERE `Email`='$Emailm' AND `Mdp`='$Mdp'")) {
    $row_cnt = $result->num_rows; } 
    }


    $b=false;
    $a=false;

    if ($row_cnt>0) {  
                if($_REQUEST['attacher']=="oui"){   
                $filecount = 0;
                $files = glob($target_path1 . "*");
                if ($files){
                $filecount = count($files);
                }
                $nomFichier=$filecount.basename( $_FILES['attachement']['name'])  ; 
                $target_path1 = $target_path1 . $nomFichier;
                $nomFichierOrigin=basename( $_FILES['attachement']['name']);
                if(move_uploaded_file($_FILES['attachement']['tmp_name'], $target_path1)) {
                $b=true;} 
                }
                else{
                $nomFichier="";
                $nomFichierOrigin="";
                };

                       $h=new DateTime("now") ;
                       $s=$h->format('G:i:s');
                       $s2=$h->format('Y-m-d');
                    if($result = mysqli_query($db,"INSERT INTO `msg`(`cle`, `email_m`, `email_p`, `message`, `attachement`, `type`, `attachementNomOrigin`, `heure`, `date`,`vu`) 
                    VALUES ('','$Emailm','$Emailp','$Msg','$nomFichier','$type','$nomFichierOrigin','$s','$s2','non')"))
                    {$a=true;}

                    if($a==true && $b==true && $_REQUEST['attacher']=="oui"){
                     $dernierId = $db->insert_id;   
                     if ($result = $db->query("SELECT * FROM `med` WHERE `Email`='$Emailm' AND `Mdp`='$Mdp'")) {
                     if (mysqli_num_rows($result) > 0) { 
                      $response["Msg"] = array();
                     while ($row = mysqli_fetch_array($result)) {
                    $Msg = array();
                    $Msg["cle"] = intval($row["cle"]);
                    $Msg["heure"] = $row["heure"];
                    $Msg["date"] = $row["date"];
                    $Msg["email_m"] = $row["email_m"]; 
                    $Msg["email_p"] = $row["email_p"]; 
                    $Msg["message"] = $row["message"]; 
                    $Msg["type"] = $row["type"];  
                    $Msg["attachement"] = $row["attachement"]; 
                    $Msg["attachementNomOrigin"] = $row["attachementNomOrigin"]; 
                    array_push($response["Msg"], $Msg);
                     }

                    $response["success"] = 1;
                    $response["message"] = "Succès";
                    }}} else 

                    if($a==true && $_REQUEST['attacher']=="non"){
                    $response["success"] = 1;
                    $response["message"] = "Succès"; 
                    }else{

                    $response["success"] = 0;
                    $response["message"] = "Erreur lors de l'envoi";
                    }

                    echo json_encode($response);
    } else { 
        $response["success"] = 0;
        $response["message"] = "Email ou Mot de passe incorrect";

        echo json_encode($response);
    }
}else { 
    $response["success"] = 0;
    $response["message"] = "Champs manqués";

    echo json_encode($response);
}
?>

logCat:

04-20 18:05:00.149    4509-4509/eddine.charef.mechalikh.swipedemo E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at eddine.charef.mechalikh.swipedemo.message$PostDataAsyncTask.onPostExecute(message.java:231)
            at eddine.charef.mechalikh.swipedemo.message$PostDataAsyncTask.onPostExecute(message.java:207)
            at android.os.AsyncTask.finish(AsyncTask.java:631)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4813)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:559)
            at dalvik.system.NativeStart.main(Native Method)
04-20 18:05:00.219    4509-6923/eddine.charef.mechalikh.swipedemo I/System.out﹕ {"Msg":[{"cle":271,"heure":"18:01:18","date":"2015-04-20","email_m":"mecha","email_p":"a","message":"hhhh","type":"0","attachement":"12Maps.apk","attachementNomOrigin":"Maps.apk"}],"success":1,"message":"Msg telecharg\u00e9s"}

在jsonParser我奇怪

System.out.println(String.valueOf(json);

而且即使出現異常,您也可以在logcat中看到json對象...所以這是一個計時問題..您怎么看?

Edit2 JsonParser.java

public class JSONParser {

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

// constructor
public JSONParser() {

}

// 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));

            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();
    }catch (Exception e){};

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        System.out.println(json);
        //HERE IS THE SYSTEM.OUT.PRINT THAT I TALK ABOUT
        //YOU CAN SEE THE RESULT IN THE LOGCAT
    } 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);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

}

給你一個關於所面臨的想法:我想清除tha EdittextHere: 屏幕截圖 發送消息后,這就是為什么我在postExecute中檢查成功標記的原因..如果您有其他方法,我將非常感激..請注意,這是我的第一個應用程序,因此我不知道其他方法

問題是在PHP代碼..這是正確的

    <?php  
date_default_timezone_set ("Africa/Algiers");
include('connect.php');
$response = array();

if (isset($_REQUEST['Emailm'])&& isset($_REQUEST['Mdp'])&&isset($_REQUEST['type']) && isset($_REQUEST['Emailp'])&&isset($_REQUEST['Msg'])  ) {

    $Emailm = $db->real_escape_string($_REQUEST['Emailm']);  
    $Emailp = $db->real_escape_string($_REQUEST['Emailp']); 
    $Mdp = $db->real_escape_string($_REQUEST['Mdp']);  
    $Msg = $_REQUEST['Msg'];  
    $Mdp = $_REQUEST['Mdp'];  
    $Msg= $db->real_escape_string(htmlentities(urldecode($Msg)));    
    $type= $_REQUEST['type'];
    $target_path1 = "attachement/";   
    if($type=="0"){  //compte patient
    if ($result = $db->query("SELECT * FROM `patient` WHERE `Email_p`='$Emailp' AND `Mdp`='$Mdp'")) {
    $row_cnt = $result->num_rows; 
 }
     }else {  //compte médecin
    if ($result = $db->query("SELECT * FROM `med` WHERE `Email`='$Emailm' AND `Mdp`='$Mdp'")) {
    $row_cnt = $result->num_rows; 
 } 
    }


    $b=false;
    $a=false;

    if ($row_cnt>0) {  
                if($_REQUEST['attacher']=="oui"){       
                $filecount = 0;
                $files = glob($target_path1 . "*");
                if ($files){
                $filecount = count($files); 
                }
                $nomFichier=$filecount.basename( $_FILES['attachement']['name']) . ".a"; 
                $target_path1 = $target_path1 . $nomFichier;
                $nomFichierOrigin=basename( $_FILES['attachement']['name']);
                if(move_uploaded_file($_FILES['attachement']['tmp_name'], $target_path1)) {
                $b=true; } 
                }
                else{
                $nomFichier="";
                $nomFichierOrigin=""; 
                };

                       $h=new DateTime("now") ;
                       $s=$h->format('G:i:s');
                       $s2=$h->format('Y-m-d');
                    if($result = mysqli_query($db,"INSERT INTO `msg`(`cle`, `email_m`, `email_p`, `message`, `attachement`, `type`, `attachementNomOrigin`, `heure`, `date`,`vu`) 
                    VALUES ('','$Emailm','$Emailp','$Msg','$nomFichier','$type','$nomFichierOrigin','$s','$s2','non')"))
                    {$a=true;$dernierId = $db->insert_id;
                     }

                    if($a==true && $b==true && $_REQUEST['attacher']=="oui"){


                     if ($result = $db->query("SELECT * FROM msg WHERE cle='$dernierId'")) {
                     if (mysqli_num_rows($result) > 0) { 
                      $response["Msg"] = array();
                     while ($row = mysqli_fetch_array($result)) {
                    $Msg = array();
                    $Msg["cle"] = intval($row["cle"]);
                    $Msg["heure"] = $row["heure"];
                    $Msg["date"] = $row["date"];
                    $Msg["email_m"] = $row["email_m"]; 
                    $Msg["email_p"] = $row["email_p"]; 
                    $Msg["message"] = $row["message"]; 
                    $Msg["type"] = $row["type"];  
                    $Msg["attachement"] = $row["attachement"]; 
                    $Msg["attachementNomOrigin"] = $row["attachementNomOrigin"]; 
                    array_push($response["Msg"], $Msg);
                     }

                    $response["success"] = 1;
                    $response["message"] = "Succès"; 
                    }}} else 

                    if($a==true && $_REQUEST['attacher']=="non"){ 
                    $response["success"] = 1;
                    $response["message"] = "Succès"; 
                    }else{ 
                    $response["success"] = 0;
                    $response["message"] = "Erreur lors de l'envoi";
                    }


    } else {  
        $response["success"] = 0;
        $response["message"] = "Email ou Mot de passe incorrect";


    }
}else { 

    $response["success"] = 0;
    $response["message"] = "Champs manqués";


} echo json_encode($response);
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM