HTTP POST 成功,但 AsyncTask 返回 NullPointerException?

发布于 2024-11-26 07:31:38 字数 7139 浏览 1 评论 0原文

我的 Android 应用程序中有输入表单 输入的数据将保存到在线数据库中,

现在我可以使用 AsyncTask 保存数据并上传图片。

数据上传成功,但是AsyncTask返回java.lang.NullPointerException

这是我的AsyncTask类:

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

    ProgressDialog pd = new ProgressDialog(FormAsetTambah.this);

    BufferedReader in = null;

    final TextView errorText = (TextView) findViewById(R.id.error_text);

    protected void onPreExecute(){
        pd.setMessage(Functions.GetString(getApplicationContext(), R.string.progress_dialog_loading));
        pd.show();
    }

    @Override
    protected String doInBackground(String... arg0) {

        try {

            String URL_DESTINATION = URLVariables.get_base_url()+"aset_tambah_pic.php";

            Bitmap bm = BitmapFactory.decodeFile(arg0[7]);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(CompressFormat.JPEG, 50, bos);

            HttpClient httpClient = CustomHttpClient.getHttpClient();
            HttpPost postRequest = new HttpPost(URL_DESTINATION);           

            MultipartEntity reqEntity = new MultipartEntity(
            HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("uploadedfile", new FileBody(new File(arg0[7])));
            reqEntity.addPart("nama", new StringBody(arg0[0]));
            reqEntity.addPart("detail", new StringBody(arg0[1]));
            reqEntity.addPart("keterangan", new StringBody(arg0[2]));
            reqEntity.addPart("longitude", new StringBody(arg0[3]));
            reqEntity.addPart("latitude", new StringBody(arg0[4]));
            reqEntity.addPart("kategori", new StringBody(arg0[5]));
            reqEntity.addPart("daerah", new StringBody(arg0[6]));
            postRequest.setEntity(reqEntity);

            HttpResponse response = httpClient.execute(postRequest);

            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");

            while((line = in.readLine()) != null){
                sb.append(line+NL);
            }

            in.close();

            String result = sb.toString();

            return result;

        }catch(Exception e){            
            return e.toString();
        }

    }

    protected void onPostExecute(String result){

        try{

            String output = result.toString().trim();
            error_text.setText(output);

            if(output.equals("1")){
                Functions.MakeToast(getApplicationContext(), ERR_SAVED);
                Intent daftarAset = new Intent(getApplicationContext(), DaftarAset.class);
                startActivity(daftarAset);
                finish();
            }else if(output.equals("2")){
                Functions.MakeToast(getApplicationContext(), ERR_QUERY);
            }else{
                Functions.MakeToast(getApplicationContext(), ERR_HTTPFAIL);
            }

        }catch(Exception e){
            Functions.MakeToast(getApplicationContext(), "onPostExecute fail : "+e.toString()); // it failed here
        }
        pd.dismiss();
    }

}

你知道我的错在哪里吗? 或者有什么建议/解决方案可以让它变得更好?

更新

上的异常

07-27 21:54:09.222: WARN/System.err(17600): java.lang.NullPointerException
07-27 21:54:09.222: WARN/System.err(17600):     at com.ngimagrid.nigmago.FormAsetTambah$SaveData.onPostExecute(FormAsetTambah.java:567)
07-27 21:54:09.222: WARN/System.err(17600):     at com.ngimagrid.nigmago.FormAsetTambah$SaveData.onPostExecute(FormAsetTambah.java:1)
07-27 21:54:09.222: WARN/System.err(17600):     at android.os.AsyncTask.finish(AsyncTask.java:417)
07-27 21:54:09.222: WARN/System.err(17600):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
07-27 21:54:09.222: WARN/System.err(17600):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
07-27 21:54:09.222: WARN/System.err(17600):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-27 21:54:09.222: WARN/System.err(17600):     at android.os.Looper.loop(Looper.java:123)
07-27 21:54:09.222: WARN/System.err(17600):     at android.app.ActivityThread.main(ActivityThread.java:3687)
07-27 21:54:09.222: WARN/System.err(17600):     at java.lang.reflect.Method.invokeNative(Native Method)
07-27 21:54:09.222: WARN/System.err(17600):     at java.lang.reflect.Method.invoke(Method.java:507)
07-27 21:54:09.222: WARN/System.err(17600):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
07-27 21:54:09.222: WARN/System.err(17600):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
07-27 21:54:09.222: WARN/System.err(17600):     at dalvik.system.NativeStart.main(Native Method)

这是我在 logcat UPDATE

,这是我的服务器端代码:

<?php

    require_once("functions.php");

    $nama = trim($_POST['nama']);
    $detail = trim($_POST['detail']);
    $keterangan = trim($_POST['keterangan']);
    $longitude= trim($_POST['longitude']);
    $latitude = trim($_POST['latitude']);

    $kategori = trim($_POST['kategori']);
    $daerah = trim($_POST['daerah']);

    $target_path = "images/";
    $file_tmp_name = $_FILES['uploadedfile']['tmp_name'];
    $file_name = str_replace(array(" ","-"), "_", strtolower(basename($_FILES['uploadedfile']['name'])));
    $target_path = $target_path.$file_name; 


    if(empty($nama) || empty($detail) || empty($keterangan) || empty($longitude) || empty($latitude) || empty($kategori) || empty($daerah) || empty($file_tmp_name)){

        echo "5";

    }else{

        openDB();

        $get_id_kategori = mysql_fetch_array(mysql_query("SELECT `id_kategori` FROM `aset_kategori` WHERE `kategori`='$kategori'"));
        $get_id_daerah = mysql_fetch_array(mysql_query("SELECT `id_daerah` FROM `aset_daerah` WHERE `daerah`='$daerah'"));

        $tanggal = date("Y-m-d H:i:s");

        $sql = "INSERT INTO  `aset` (`id_aset` ,`id_daerah` ,`id_kategori` ,`nama` ,`detail` ,`longitude` ,`latitude` ,`keterangan` ,`status` ,`tanggal`)
                    VALUES (NULL ,  '$get_id_daerah[0]',  '$get_id_kategori[0]',  '$nama',  '$detail', '$longitude',  '$latitude',  '$keterangan',  'Y',  '$tanggal');";

        if(mysql_query($sql)){
            if(!file_exists($target_path)){
                if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {

                    $id_aset = mysql_fetch_array(mysql_query("SELECT `id_aset` FROM `aset` ORDER BY `id_aset` DESC LIMIT 1"));
                    mysql_query("INSERT INTO `aset_foto` (`id_foto`, `id_aset`, `foto`) VALUES (NULL, '$id_aset[0]', '$file_name');");  

                    echo "1";   // success          
                } else{         
                    echo "2"; // failed         
                }
            }else{
                echo "3";   // failed
            }
        }else{
            echo "4";   //failed
        }

        closeDB();

    }

?>

如果响应等于 1,则保存过程成功

I have input form in my Android application
the inputed data will saved to online database

now I can save the data and upload the picture using AsyncTask.

the data were uploaded successfully, but the AsyncTask returning java.lang.NullPointerException

here's my AsyncTask class:

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

    ProgressDialog pd = new ProgressDialog(FormAsetTambah.this);

    BufferedReader in = null;

    final TextView errorText = (TextView) findViewById(R.id.error_text);

    protected void onPreExecute(){
        pd.setMessage(Functions.GetString(getApplicationContext(), R.string.progress_dialog_loading));
        pd.show();
    }

    @Override
    protected String doInBackground(String... arg0) {

        try {

            String URL_DESTINATION = URLVariables.get_base_url()+"aset_tambah_pic.php";

            Bitmap bm = BitmapFactory.decodeFile(arg0[7]);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(CompressFormat.JPEG, 50, bos);

            HttpClient httpClient = CustomHttpClient.getHttpClient();
            HttpPost postRequest = new HttpPost(URL_DESTINATION);           

            MultipartEntity reqEntity = new MultipartEntity(
            HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("uploadedfile", new FileBody(new File(arg0[7])));
            reqEntity.addPart("nama", new StringBody(arg0[0]));
            reqEntity.addPart("detail", new StringBody(arg0[1]));
            reqEntity.addPart("keterangan", new StringBody(arg0[2]));
            reqEntity.addPart("longitude", new StringBody(arg0[3]));
            reqEntity.addPart("latitude", new StringBody(arg0[4]));
            reqEntity.addPart("kategori", new StringBody(arg0[5]));
            reqEntity.addPart("daerah", new StringBody(arg0[6]));
            postRequest.setEntity(reqEntity);

            HttpResponse response = httpClient.execute(postRequest);

            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");

            while((line = in.readLine()) != null){
                sb.append(line+NL);
            }

            in.close();

            String result = sb.toString();

            return result;

        }catch(Exception e){            
            return e.toString();
        }

    }

    protected void onPostExecute(String result){

        try{

            String output = result.toString().trim();
            error_text.setText(output);

            if(output.equals("1")){
                Functions.MakeToast(getApplicationContext(), ERR_SAVED);
                Intent daftarAset = new Intent(getApplicationContext(), DaftarAset.class);
                startActivity(daftarAset);
                finish();
            }else if(output.equals("2")){
                Functions.MakeToast(getApplicationContext(), ERR_QUERY);
            }else{
                Functions.MakeToast(getApplicationContext(), ERR_HTTPFAIL);
            }

        }catch(Exception e){
            Functions.MakeToast(getApplicationContext(), "onPostExecute fail : "+e.toString()); // it failed here
        }
        pd.dismiss();
    }

}

do you know where's my fault?
or any advice/solution to make it better?

Update

Here's my exception on logcat

07-27 21:54:09.222: WARN/System.err(17600): java.lang.NullPointerException
07-27 21:54:09.222: WARN/System.err(17600):     at com.ngimagrid.nigmago.FormAsetTambah$SaveData.onPostExecute(FormAsetTambah.java:567)
07-27 21:54:09.222: WARN/System.err(17600):     at com.ngimagrid.nigmago.FormAsetTambah$SaveData.onPostExecute(FormAsetTambah.java:1)
07-27 21:54:09.222: WARN/System.err(17600):     at android.os.AsyncTask.finish(AsyncTask.java:417)
07-27 21:54:09.222: WARN/System.err(17600):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
07-27 21:54:09.222: WARN/System.err(17600):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
07-27 21:54:09.222: WARN/System.err(17600):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-27 21:54:09.222: WARN/System.err(17600):     at android.os.Looper.loop(Looper.java:123)
07-27 21:54:09.222: WARN/System.err(17600):     at android.app.ActivityThread.main(ActivityThread.java:3687)
07-27 21:54:09.222: WARN/System.err(17600):     at java.lang.reflect.Method.invokeNative(Native Method)
07-27 21:54:09.222: WARN/System.err(17600):     at java.lang.reflect.Method.invoke(Method.java:507)
07-27 21:54:09.222: WARN/System.err(17600):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
07-27 21:54:09.222: WARN/System.err(17600):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
07-27 21:54:09.222: WARN/System.err(17600):     at dalvik.system.NativeStart.main(Native Method)

UPDATE

here's my server side code:

<?php

    require_once("functions.php");

    $nama = trim($_POST['nama']);
    $detail = trim($_POST['detail']);
    $keterangan = trim($_POST['keterangan']);
    $longitude= trim($_POST['longitude']);
    $latitude = trim($_POST['latitude']);

    $kategori = trim($_POST['kategori']);
    $daerah = trim($_POST['daerah']);

    $target_path = "images/";
    $file_tmp_name = $_FILES['uploadedfile']['tmp_name'];
    $file_name = str_replace(array(" ","-"), "_", strtolower(basename($_FILES['uploadedfile']['name'])));
    $target_path = $target_path.$file_name; 


    if(empty($nama) || empty($detail) || empty($keterangan) || empty($longitude) || empty($latitude) || empty($kategori) || empty($daerah) || empty($file_tmp_name)){

        echo "5";

    }else{

        openDB();

        $get_id_kategori = mysql_fetch_array(mysql_query("SELECT `id_kategori` FROM `aset_kategori` WHERE `kategori`='$kategori'"));
        $get_id_daerah = mysql_fetch_array(mysql_query("SELECT `id_daerah` FROM `aset_daerah` WHERE `daerah`='$daerah'"));

        $tanggal = date("Y-m-d H:i:s");

        $sql = "INSERT INTO  `aset` (`id_aset` ,`id_daerah` ,`id_kategori` ,`nama` ,`detail` ,`longitude` ,`latitude` ,`keterangan` ,`status` ,`tanggal`)
                    VALUES (NULL ,  '$get_id_daerah[0]',  '$get_id_kategori[0]',  '$nama',  '$detail', '$longitude',  '$latitude',  '$keterangan',  'Y',  '$tanggal');";

        if(mysql_query($sql)){
            if(!file_exists($target_path)){
                if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {

                    $id_aset = mysql_fetch_array(mysql_query("SELECT `id_aset` FROM `aset` ORDER BY `id_aset` DESC LIMIT 1"));
                    mysql_query("INSERT INTO `aset_foto` (`id_foto`, `id_aset`, `foto`) VALUES (NULL, '$id_aset[0]', '$file_name');");  

                    echo "1";   // success          
                } else{         
                    echo "2"; // failed         
                }
            }else{
                echo "3";   // failed
            }
        }else{
            echo "4";   //failed
        }

        closeDB();

    }

?>

if the response equals 1, then the saving proccess was successful

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

故事与诗 2024-12-03 07:31:38

在 IDE 或任意文本编辑器中打开 GoTo 行功能。输入 567,这就是失败的行号。不幸的是,如果没有实际的完整源代码,我们无法判断该片段中出现了第 567 行。

看起来有问题的行可能是:

String output = result.toString().trim();
error_text.setText(output);

结果可能为 null,或者 toString() 可能返回 null。 error_text 也可以为 null。

On open up your GoTo line functionality in your IDE or any descent text editor. Type in 567, and that's the line number that is failing. Unfortunately, without the actual full source we can't tell what line number 567 occurs in this fragment.

The lines that looks suspect of issues could be:

String output = result.toString().trim();
error_text.setText(output);

The result could be null, or toString() could be returning null. error_text could also be null.

雪落纷纷 2024-12-03 07:31:38

我想我明白了。
我建议在您的 doInBackground() 方法中返回 in.readline().trim(); (也尝试不修剪)

为什么?因为在您的脚本中,您仅 echo-ing 一个字符(即使使用 .read() 也可以完成,因此无需迭代 onPostExecute

() 方法中,我建议先Log 结果并查看它的值是什么。做任何事。

I think I got it.
I suggest in your doInBackground() method to return in.readline().trim(); (also try without trimming)

Why? Because in your script you are echo-ing only one character (which may be done even with .read(), so there is no need to iterate through the InputStreamReader object.

In onPostExecute() method, I suggest to Log the result and see what's its with the value, before you do anything.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文