android:缓冲区错误&解析数据(JSON Parser)=总是旋转

时间:2014-05-13 14:42:17

标签: android json parsing

这是我的java:

package com.example.bo_withoop;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.bo_withoop.JSONParser;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class slot_parkir extends Activity
{
    Button satu_a, satu_b, satu_c, satu_d, satu_e;
    Button dua_a, dua_b, dua_c, dua_d, dua_e;
    Button tiga_a, tiga_b, tiga_c, tiga_d, tiga_e;
    private ProgressDialog pDialog;
    int lantai = 0;
    int waktu_masuk = 0;
    int waktu_keluar = 0;
    String tempat_parkir;
    int id_user = 0;

    private static String url_create_booking = "http://192.168.1.101/skripsi/create_booking.php";
    JSONParser jsonParser = new JSONParser();
    private static final String TAG_SUCCESS = "success";

    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.slot_parkir);

        //button lantai 1
        satu_a = (Button) findViewById(R.id.satu_a);
        satu_b = (Button) findViewById(R.id.satu_b);
        satu_c = (Button) findViewById(R.id.satu_c);
        satu_d = (Button) findViewById(R.id.satu_d);
        satu_e = (Button) findViewById(R.id.satu_e);
        //button lantai 2
        dua_a = (Button) findViewById(R.id.dua_a);
        dua_b = (Button) findViewById(R.id.dua_b);
        dua_c = (Button) findViewById(R.id.dua_c);
        dua_d = (Button) findViewById(R.id.dua_d);
        dua_e = (Button) findViewById(R.id.dua_e);
        //button lantai 3
        tiga_a = (Button) findViewById(R.id.tiga_a);
        tiga_b = (Button) findViewById(R.id.tiga_b);
        tiga_c = (Button) findViewById(R.id.tiga_c);
        tiga_d = (Button) findViewById(R.id.tiga_d);
        tiga_e = (Button) findViewById(R.id.tiga_e);
        //parsing lantai
        Intent i = getIntent();
        Bundle a = i.getExtras();

        if (a != null)
        {
            lantai = a.getInt("lantai");
            waktu_masuk = a.getInt("waktu_masuk");
            waktu_keluar = a.getInt("waktu_keluar");
            id_user = a.getInt("id_user");
        }
        if(lantai == 1)
        {
            satu_a.setVisibility(Button.VISIBLE);
            satu_a.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    tempat_parkir = "1A";
                    Toast.makeText(getApplicationContext(), "test: "+lantai+waktu_masuk+waktu_keluar+id_user , Toast.LENGTH_SHORT).show();
                    new CreateNewBooking().execute();

                }
            });
            satu_b.setVisibility(Button.VISIBLE);
            satu_c.setVisibility(Button.VISIBLE);
            satu_d.setVisibility(Button.VISIBLE);
            satu_e.setVisibility(Button.VISIBLE);
        }
        else if(lantai == 2)
        {
            dua_a.setVisibility(Button.VISIBLE);
            dua_b.setVisibility(Button.VISIBLE);
            dua_c.setVisibility(Button.VISIBLE);
            dua_d.setVisibility(Button.VISIBLE);
            dua_e.setVisibility(Button.VISIBLE);
        }
        else if(lantai == 3)
        {
            tiga_a.setVisibility(Button.VISIBLE);
            tiga_b.setVisibility(Button.VISIBLE);
            tiga_c.setVisibility(Button.VISIBLE);
            tiga_d.setVisibility(Button.VISIBLE);
            tiga_e.setVisibility(Button.VISIBLE);
        }

    }
    class CreateNewBooking extends AsyncTask<String, String, Integer> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(slot_parkir.this);
            pDialog.setMessage("Creating booking..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected Integer doInBackground(String... args) {
            String lantai ="";
            lantai =  lantai.toString();
            String waktu_masuk ="";
            waktu_masuk = waktu_masuk.toString();
            String waktu_keluar = "";
            waktu_keluar =  waktu_keluar.toString();
            String id_user = "";
            id_user =   id_user.toString();
            String qr_code = "123";

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("lantai", lantai));
            params.add(new BasicNameValuePair("waktu_masuk", waktu_masuk));
            params.add(new BasicNameValuePair("waktu_keluar", waktu_keluar));
            params.add(new BasicNameValuePair("id_user", id_user));
            params.add(new BasicNameValuePair("qr_code", qr_code));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_booking,
                    "POST", params);

            int success;
            // check for success tag
            try {
                 success = json.getInt(TAG_SUCCESS);

                    if (success == 1) {
                } else {
                }
                    }
             catch (JSONException e) {
                 success=0;
                e.printStackTrace();
             }
            catch (Exception e){
                e.printStackTrace();
                success=0;
            }

            return success;}

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(int success) {
            // dismiss the dialog once done
            if (success == 1) {
            } else {
                // failed to create product
                Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
            }
            pDialog.dismiss();

        }

    }
}

我的php文件是:

<?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */

// array for JSON response
$response = array();

// check for required fields

    $lantai = $_POST['lantai'];
    $waktu_masuk = $_POST['waktu_masuk'];
    $waktu_keluar= $_POST['waktu_keluar'];
    $id_user = $_POST['id_user'];
    $qr_code = $_POST['qr_code'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO transaksi(lantai, waktu_masuk, waktu_keluar, id_user, qr_code) VALUES('$lantai', '$waktu_masuk', '$waktu_keluar'', $id_user, '$qr_code)");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Book succeedd";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = mysql_error();

        // echoing JSON response
        echo json_encode($response);
    }

?>

这是我的JSONParser.java:

package com.example.bo_withoop;

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() {

    }

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

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } 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;

    }
}

来自logcat的错误是:

  • E / Buffer Error(11003):转换结果java.lang.NullPointerException时出错
  • E / JSON Parser(11003):解析数据时出错org.json.JSONException:
  • 字符0处的输入结束

所以,当我将这个程序运行到AVD或我的移动设备时,它会卡住并继续加载创建预订。我该怎么办这个问题?感谢。

0 个答案:

没有答案