2

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Falmesino
  • 135
  • 1
  • 5
  • 16
  • print a stack trace in your catch block (e.printStackTrace();) and post it here. it'll be easier help. – P.Melch Jul 27 '11 at 10:15
  • where i can get the output from printStackTrace() ? – Falmesino Jul 27 '11 at 10:26
  • copy exception from LogCat http://stackoverflow.com/questions/3280051/how-to-enable-logcat-console-in-eclipse-for-android – Selvin Jul 27 '11 at 10:41
  • Did you program the server side as well? I'd like to see your code for handling the post request and response. – Otra Jul 27 '11 at 15:01
  • @Otra the server side scripts works well, my data and picture were saved and uploaded to cloud, and it returns the response number, it's so confusing, the scripts on doInBackground() not returning any result :( – Falmesino Jul 27 '11 at 15:22
  • I'm wondering if the response isn't getting sent correctly, so if I could see the few lines of code where you set the response server side, that might help. – Otra Jul 27 '11 at 16:29
  • @Otra edited, my server-side code works well – Falmesino Jul 28 '11 at 02:39
  • Try loging the response or result. – Nikola Despotoski Jul 28 '11 at 02:57

2 Answers2

1

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.

chubbsondubs
  • 37,646
  • 24
  • 106
  • 138
  • you're right, that's the line 567 i think the result from doInBackground is null, i've tested it on server-side and it works, but why in the android app it wont return any result? – Falmesino Jul 27 '11 at 15:25
  • Try logging the response. And see what's the output of the serverside. – Nikola Despotoski Jul 28 '11 at 03:01
  • The exception block in your doInBackground() isn't doing what it should. The problem is you are returning e.toString() which will never be meaningful because your doPostExecute() can't tell the difference between valid response and an exception. An exception means something went wrong and you should stop. Let the exception boil out or set it into an instance variable. Then in onPostExecute() look at the instance variable and show an alert. I bet you have a NPE in doBackground() that is being trapped, and NPE.getMessage() returns null hence you have an null passed to onPostExecute(). – chubbsondubs Jul 28 '11 at 03:53
1

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.

Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148