0

对不起,这段代码有什么问题,我在 xampp 中尝试它工作正常。现在我在在线服务器上尝试它会崩溃。在android应用程序中,它将发布到服务器,

这是日志

    -28 08:53:22.582: E/JSON Parser(333): Kesalahan parsing org.json.JSONException:    Value <br of type java.lang.String cannot be converted to JSONObject
     06-28 08:53:22.582: W/dalvikvm(333): threadid=9: thread exiting with uncaught exception (group=0x40015560)
     06-28 08:53:18.312: W/KeyCharacterMap(333): No keyboard for id 0
     06-28 08:53:18.312: W/KeyCharacterMap(333): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
     06-28 08:53:19.982: D/dalvikvm(333): GC_EXTERNAL_ALLOC freed 81K, 51% free 2643K/5379K, external 3181K/3266K, paused 68ms
     06-28 08:53:22.582: E/JSON Parser(333): Kesalahan parsing org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
     06-28 08:53:22.582: W/dalvikvm(333): threadid=9: thread exiting with uncaught exception (group=0x40015560)
     06-28 08:53:22.592: E/AndroidRuntime(333): FATAL EXCEPTION: AsyncTask #1
     06-28 08:53:22.592: E/AndroidRuntime(333): java.lang.RuntimeException: An error occured while executing doInBackground()
     06-28 08:53:22.592: E/AndroidRuntime(333):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
     06-28 08:53:22.592: E/AndroidRuntime(333):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
     06-28 08:53:22.592: E/AndroidRuntime(333):     at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
     06-28 08:53:22.592: E/AndroidRuntime(333):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
     06-28 08:53:22.592: E/AndroidRuntime(333):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
     06-28 08:53:22.592: E/AndroidRuntime(333):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
     06-28 08:53:22.592: E/AndroidRuntime(333):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
     06-28 08:53:22.592: E/AndroidRuntime(333):     at java.lang.Thread.run(Thread.java:1019)
     06-28 08:53:22.592: E/AndroidRuntime(333): Caused by: java.lang.NullPointerException
     06-28 08:53:22.592: E/AndroidRuntime(333):     at hearts2.packet.TambahKorbanBaru$CreateNewVictim.doInBackground(TambahKorbanBaru.java:224)
     06-28 08:53:22.592: E/AndroidRuntime(333):     at hearts2.packet.TambahKorbanBaru$CreateNewVictim.doInBackground(TambahKorbanBaru.java:1)
     06-28 08:53:22.592: E/AndroidRuntime(333):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
     06-28 08:53:22.592: E/AndroidRuntime(333):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)

这是php代码

<?php

 $response = array();

if (isset($_POST['hearts_beat']) && isset($_POST['respiration_rate']) && isset($_POST['mental_status']) && isset($_POST['kondisi']) && isset($_POST['lat']) && isset($_POST['lng'])) {

$hearts_beat = $_POST['hearts_beat'];
$respiration_rate = $_POST['respiration_rate'];
$mental_status = $_POST['mental_status'];
$kondisi = $_POST['kondisi'];
$lat = $_POST['lat'];
$lng = $_POST['lng'];

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

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

// mysql inserting a new row
//tambahin variabel di query ini yah
$result = mysql_query("INSERT INTO korban (hearts_beat, respiration_rate, mental_status, kondisi, lat, lng) VALUES('$hearts_beat', '$respiration_rate', '$mental_status', '$kondisi', '$lat', '$lng')");

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

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

    // echoing JSON response
    echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "try again";

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

这是安卓活动

String pilihanHB[], pilihanMS[];
String kondisi, curr_lati, curr_longi;
String kartu, isiPilihanHB, isiPilihanMS;
Integer statusHB, statusMS;
Spinner spinnerHB;
Spinner spinnerMS;
int indexHB, indexMS;
GpsService gps;

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();

EditText inputRespiration_Rate;

// url untuk nambah korban
private static String url_create_product = "http://blabla.php";

// JSON Node
private static final String TAG_SUCCESS = "success";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.insert_korban_hearts1);

    gps = new GpsService(TambahKorbanBaru.this);

    // dicek dulu apakah GPSnya idup

    if (gps.canGetLocation()) {
        // ambil latitude dan longitude

        double lat = gps.getLatitude();
        double lng = gps.getLongitude();

        curr_lati = String.valueOf(lat);
        curr_longi = String.valueOf(lng);
    }

    spinnerHB = (Spinner) findViewById(R.id.spinner1);
    spinnerMS = (Spinner) findViewById(R.id.spinner2);

    ArrayAdapter<CharSequence> adapterHB = ArrayAdapter.createFromResource(
            this, R.array.hearts_beats_array,
            android.R.layout.simple_spinner_item);

    ArrayAdapter<CharSequence> adapterMS = ArrayAdapter.createFromResource(
            this, R.array.mental_status_array,
            android.R.layout.simple_spinner_item);

    adapterHB
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerHB.setAdapter(adapterHB);
    adapterMS
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerMS.setAdapter(adapterMS);

    spinnerHB.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {

            indexHB = arg0.getSelectedItemPosition();

            // masukin nilai ke Array
            pilihanHB = getResources().getStringArray(
                    R.array.hearts_beats_array);

        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }

    });

    spinnerMS.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {

            indexMS = arg0.getSelectedItemPosition();

            // masukin nilai ke array
            pilihanMS = getResources().getStringArray(
                    R.array.mental_status_array);

        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }

    });

    inputRespiration_Rate = (EditText) findViewById(R.id.inputRespiration_Rate);

    Button btnInsertKorban = (Button) findViewById(R.id.btnInsertKorban);

    // event
    btnInsertKorban.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            // tambah data baru lewat AsyncTask
            new CreateNewVictim().execute();
        }
    });
}

/**
 * Background Async Task nambah data baru
 * */
public class CreateNewVictim extends AsyncTask<String, String, String> {



    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(TambahKorbanBaru.this);
        pDialog.setMessage("Menambahkan data korban..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

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

        isiPilihanHB = String.valueOf(pilihanHB[indexHB]);

        if (indexHB == 0) {
            statusHB = 1;
        } else {
            statusHB = 2;
        }

        isiPilihanMS = String.valueOf(pilihanMS[indexMS]);

        if (indexMS == 0) {
            statusMS = 1;
        } else {
            statusMS = 2;
        }

        Integer hearts_beat = statusHB;
        Integer respiration_rate = Integer.parseInt(inputRespiration_Rate
                .getText().toString());
        Integer mental_status = statusMS;

        // if MS dan HB logika triage

        if (respiration_rate >= 30) {
            kartu = "merah";
        } else if (respiration_rate <= 0) {
            kartu = "hitam";
        } else if (respiration_rate < 30) {
            if (hearts_beat == 2) {
                kartu = "merah";
            } else if (hearts_beat == 1) {
                if (mental_status == 1) {
                    kartu = "kuning";
                } else if (mental_status == 2) {
                    kartu = "merah";
                }
            }
        }

        String string_hearts_beat, string_mental_status, string_respiration_rate;

        string_hearts_beat = hearts_beat.toString();
        string_mental_status = mental_status.toString();
        string_respiration_rate = respiration_rate.toString();

        // disini tambahkan skrip buat nambah data gps pake locking gps
        // lanjutin yah ^^

        // Parameter hubungan ke database
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("hearts_beat", string_hearts_beat));
        params.add(new BasicNameValuePair("respiration_rate",
                string_respiration_rate));
        params.add(new BasicNameValuePair("mental_status",
                string_mental_status));
        params.add(new BasicNameValuePair("kondisi", kartu));
        params.add(new BasicNameValuePair("lat", curr_lati));
        params.add(new BasicNameValuePair("lng", curr_longi));

        // mengambil json objet

        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);

        // nyatet log
        Log.d("Create Response", json.toString());

        // cek sukses
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // kalau sukses nambah
                Intent i = new Intent(getApplicationContext(),
                        SemuaKorbanActivity.class);
                startActivity(i);
                finish();
            } else {
                // jika gagal
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }

    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
    }

}

}

是什么让它崩溃?谢谢你,

4

2 回答 2

1

记下您作为给定 url 写的内容

private static String url_create_product = "htpp://blabla.php";

海事组织应该是http://而不是htpp....

因为调用创建失败,没有响应,json.toString()会返回空指针异常,因为对象"json"为空...

于 2013-07-09T14:45:19.233 回答
0

问题就在这里

JSONObject json = jsonParser.makeHttpRequest(url_create_product,
            "POST", params);

您应该始终对 JSON 使用 try-catch 块。正如 Lena Bru 已经指出的那样,问题的发生是因为您的服务器 url 错误。

于 2013-07-09T14:49:54.427 回答