如何在android和phpmysql中使用json

如何在android和phpmysql中使用json,php,android,mysql,json,phpmyadmin,Php,Android,Mysql,Json,Phpmyadmin,我想我的Android应用程序发送一些数据字符串等到服务器,我得到了错误报告,不幸的是,E-Fine已经停止 这是Android代码 JSONParser jsonParser = new JSONParser(); private static String url_create_product = "http://192.168.0.108/koneksi/insert_data.php"; // Progress Dialog private ProgressDialog pDi

我想我的Android应用程序发送一些数据字符串等到服务器,我得到了错误报告,不幸的是,E-Fine已经停止

这是Android代码

JSONParser jsonParser = new JSONParser();
private static String url_create_product = "http://192.168.0.108/koneksi/insert_data.php";

// Progress Dialog
    private ProgressDialog pDialog;

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



btnTilang.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            new BuatFormBaru().execute();

        }
    });

@Override
    protected String doInBackground(String...args) {
            //ubah data dari formulir ke string
            String jenis_kendaraan = spKendaraan.getSelectedItem().toString();
            String jenis_pelanggaran =  spPelanggaran.getSelectedItem().toString();
            String wilayah_hukum =  spWilayah.getSelectedItem().toString();
            String barang_sitaan =  spSita.getSelectedItem().toString();
            String email =  etEmail.getText().toString();
            String hp = etHp.getText().toString();
            String lokasi_sidang =  etLokSidang.getText().toString();
            String barang_sitaan_lain =  etSita.getText().toString();

            //buat parameter
            List<NameValuePair> params = new ArrayList<NameValuePair>(1);
            params.add(new BasicNameValuePair("jenis_kendaraan",jenis_kendaraan));
            params.add(new BasicNameValuePair("jenis_pelanggaran",jenis_pelanggaran));
            params.add(new BasicNameValuePair("wilayah_hukum", wilayah_hukum));
            params.add(new BasicNameValuePair("barang_sitaan", barang_sitaan));
            params.add(new BasicNameValuePair("email", email));
            params.add(new BasicNameValuePair("hp",hp));
            params.add(new BasicNameValuePair("lokasi_sidang",lokasi_sidang));
            params.add(new BasicNameValuePair("barang_sitaan_lain",barang_sitaan_lain));


            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);
            //JSON kirim data httprequest


            // check log cat fro response
            Log.d("Create Response", json.toString());

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

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), HistoryActivity.class);
                    startActivity(i);
                    msg = "Data Terkirim";
                    //Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
                    // closing this screen
                    finish();
                    return json.getString(TAG_MESSAGE);

                } else {
                    // failed to create product
                    msg = "Pengiriman Gagal!";
                    //Toast.makeText(getApplicationContext(),msg, Toast.LENGTH_LONG).show();
                    return json.getString(TAG_MESSAGE);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;

    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
        pDialog.dismiss();
    }

}
这是JSONParser类

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.equals("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.equals("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() + " Data: \n" + json);
    }

    // return JSON String
    return jObj;

}
}
php代码insert_data.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
if (isset($_POST['jenis_kendaraan']) && isset($_POST['jenis_pelanggaran']) && isset($_POST['wilayah_hukum']) && isset($_POST['barang_sitaan']) && isset($_POST['email']) && isset($_POST['hp']) && isset($_POST['lokasi_sidang']) && isset($_POST['barang_sitaan_lain'])) {

$jenis_kendaraan = $_POST['jenis_kendaraan'];
$jenisPelanggaran = $_POST['jenis_pelanggaran'];
$wilayah_hukum = $_POST['wilayah_hukum'];
$barang_sitaan = $_POST['barang_sitaan'];
$email = $_POST['email'];
$hp = $_POST['hp'];
$lokasi_sidang = $_POST['lokasi_sidang'];
$barang_sitaan_lain = $_POST['barang_sitaan_lain'];


// 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 products(jenis_kendaraan, jenis_pelanggaran, wilayah_hukum, barang_sitaan, email, hp, lokasi_sidang, barang_sitaan_lain) VALUES('$jenis_kendaraan', '$jenisPelanggaran', '$wilayah_hukum','$barang_sitaan', '$email', '$hp', '$lokasi_sidang', '$barang_sitaan_lain')");

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

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

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

// echoing JSON response
echo json_encode($response);
}
?>
这是Android Studio中的logcat

05-04 16:52:59.980      925-925/com.example.indraaaeff.e_fine2 D/dalvikvm﹕ Not late-enabling CheckJNI (already on)
05-04 16:53:00.690      925-925/com.example.indraaaeff.e_fine2 W/ActivityThread﹕ Application com.example.indraaaeff.e_fine2 is waiting for the debugger on port 8100...
05-04 16:53:00.750      925-925/com.example.indraaaeff.e_fine2 I/System.out﹕ Sending WAIT chunk
05-04 16:53:00.780      925-931/com.example.indraaaeff.e_fine2 I/dalvikvm﹕ Debugger is active
05-04 16:53:00.960      925-925/com.example.indraaaeff.e_fine2 I/System.out﹕ Debugger has connected
05-04 16:53:00.960      925-925/com.example.indraaaeff.e_fine2 I/System.out﹕ waiting for debugger to settle...
05-04 16:53:01.160      925-925/com.example.indraaaeff.e_fine2 I/System.out﹕ waiting for debugger to settle...
05-04 16:53:01.380      925-925/com.example.indraaaeff.e_fine2 I/System.out﹕ waiting for debugger to settle...
05-04 16:53:01.590      925-925/com.example.indraaaeff.e_fine2 I/System.out﹕ waiting for debugger to settle...
05-04 16:53:01.800      925-925/com.example.indraaaeff.e_fine2 I/System.out﹕ waiting for debugger to settle...
05-04 16:53:02.000      925-925/com.example.indraaaeff.e_fine2 I/System.out﹕ waiting for debugger to settle...
05-04 16:53:02.200      925-925/com.example.indraaaeff.e_fine2 I/System.out﹕ waiting for debugger to settle...
05-04 16:53:02.400      925-925/com.example.indraaaeff.e_fine2 I/System.out﹕ waiting for debugger to settle...
05-04 16:53:02.600      925-925/com.example.indraaaeff.e_fine2 I/System.out﹕ waiting for debugger to settle...
05-04 16:53:02.850      925-925/com.example.indraaaeff.e_fine2 I/System.out﹕ debugger has settled (1326)
05-04 16:53:07.090      925-925/com.example.indraaaeff.e_fine2 I/dalvikvm﹕ Could not find method android.view.ViewGroup.onNestedScrollAccepted, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onNestedScrollAccepted
05-04 16:53:07.090      925-925/com.example.indraaaeff.e_fine2 W/dalvikvm﹕ VFY: unable to resolve virtual method 12225: Landroid/view/ViewGroup;.onNestedScrollAccepted (Landroid/view/View;Landroid/view/View;I)V
05-04 16:53:07.090      925-925/com.example.indraaaeff.e_fine2 D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
05-04 16:53:07.100      925-925/com.example.indraaaeff.e_fine2 I/dalvikvm﹕ Could not find method android.view.ViewGroup.onStopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onStopNestedScroll
05-04 16:53:07.100      925-925/com.example.indraaaeff.e_fine2 W/dalvikvm﹕ VFY: unable to resolve virtual method 12231: Landroid/view/ViewGroup;.onStopNestedScroll (Landroid/view/View;)V
05-04 16:53:07.100      925-925/com.example.indraaaeff.e_fine2 D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
05-04 16:53:07.110      925-925/com.example.indraaaeff.e_fine2 I/dalvikvm﹕ Could not find method android.support.v7.internal.widget.ActionBarOverlayLayout.stopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.setHideOnContentScrollEnabled
05-04 16:53:07.110      925-925/com.example.indraaaeff.e_fine2 W/dalvikvm﹕ VFY: unable to resolve virtual method 9795: Landroid/support/v7/internal/widget/ActionBarOverlayLayout;.stopNestedScroll ()V
05-04 16:53:07.110      925-925/com.example.indraaaeff.e_fine2 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000e
05-04 16:53:07.240      925-925/com.example.indraaaeff.e_fine2 I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
05-04 16:53:07.240      925-925/com.example.indraaaeff.e_fine2 W/dalvikvm﹕ VFY: unable to resolve virtual method 399: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
05-04 16:53:07.240      925-925/com.example.indraaaeff.e_fine2 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
05-04 16:53:07.260      925-925/com.example.indraaaeff.e_fine2 I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
05-04 16:53:07.260      925-925/com.example.indraaaeff.e_fine2 W/dalvikvm﹕ VFY: unable to resolve virtual method 421: Landroid/content/res/TypedArray;.getType (I)I
05-04 16:53:07.260      925-925/com.example.indraaaeff.e_fine2 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
05-04 16:53:07.320      925-925/com.example.indraaaeff.e_fine2 I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawable
05-04 16:53:07.320      925-925/com.example.indraaaeff.e_fine2 W/dalvikvm﹕ VFY: unable to resolve virtual method 362: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
05-04 16:53:07.320      925-925/com.example.indraaaeff.e_fine2 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
05-04 16:53:07.330      925-925/com.example.indraaaeff.e_fine2 I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawableForDensity
05-04 16:53:07.330      925-925/com.example.indraaaeff.e_fine2 W/dalvikvm﹕ VFY: unable to resolve virtual method 364: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
05-04 16:53:07.330      925-925/com.example.indraaaeff.e_fine2 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
05-04 16:53:08.250      925-925/com.example.indraaaeff.e_fine2 D/dalvikvm﹕ GC_FOR_ALLOC freed 126K, 7% free 3005K/3200K, paused 43ms, total 51ms
05-04 16:53:08.270      925-925/com.example.indraaaeff.e_fine2 I/dalvikvm-heap﹕ Grow heap (frag case) to 4.009MB for 1059620-byte allocation
05-04 16:53:08.360      925-934/com.example.indraaaeff.e_fine2 D/dalvikvm﹕ GC_FOR_ALLOC freed 3K, 5% free 4037K/4236K, paused 88ms, total 88ms
05-04 16:53:10.070      925-925/com.example.indraaaeff.e_fine2 D/﹕ HostConnection::get() New Host Connection established 0xb73e9678, tid 925
05-04 16:53:10.190      925-925/com.example.indraaaeff.e_fine2 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
05-04 16:53:10.210      925-925/com.example.indraaaeff.e_fine2 D/OpenGLRenderer﹕ Enabling debug mode 0
05-04 16:53:49.750      925-925/com.example.indraaaeff.e_fine2 D/dalvikvm﹕ GC_FOR_ALLOC freed 139K, 5% free 4354K/4564K, paused 422ms, total 436ms
05-04 16:53:49.860      925-925/com.example.indraaaeff.e_fine2 I/dalvikvm-heap﹕ Grow heap (frag case) to 5.391MB for 1127536-byte allocation
05-04 16:53:50.140      925-934/com.example.indraaaeff.e_fine2 D/dalvikvm﹕ GC_FOR_ALLOC freed 2K, 4% free 5453K/5668K, paused 282ms, total 282ms
05-04 16:53:53.540      925-925/com.example.indraaaeff.e_fine2 I/Choreographer﹕ Skipped 351 frames!  The application may be doing too much work on its main thread.
05-04 16:53:55.070      925-925/com.example.indraaaeff.e_fine2 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
05-04 16:53:55.370      925-925/com.example.indraaaeff.e_fine2 I/Choreographer﹕ Skipped 59 frames!  The application may be doing too much work on its main thread.
05-04 17:01:10.299      925-925/com.example.indraaaeff.e_fine2 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
05-04 17:01:13.299      925-925/com.example.indraaaeff.e_fine2 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
05-04 17:01:13.789      925-925/com.example.indraaaeff.e_fine2 I/Choreographer﹕ Skipped 36 frames!  The application may be doing too much work on its main thread.
05-04 17:01:16.219      925-925/com.example.indraaaeff.e_fine2 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
05-04 17:01:19.269      925-925/com.example.indraaaeff.e_fine2 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
05-04 17:01:43.029      925-925/com.example.indraaaeff.e_fine2 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
05-04 17:01:49.899      925-941/com.example.indraaaeff.e_fine2 D/dalvikvm﹕ GC_FOR_ALLOC freed 341K, 7% free 5976K/6384K, paused 80ms, total 81ms
05-04 17:02:01.689      925-941/com.example.indraaaeff.e_fine2 E/JSON Parser﹕ Error parsing data: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject Data:
    <br />
    <b>Warning</b>:  mysql_connect() [<a href='function.mysql-connect'>function.mysql-connect</a>]: Access denied for user 'root'@'localhost' (using password: NO) in <b>E:\Ampps\www\koneksi\db_connect.php</b> on line <b>28</b><br />
    Access denied for user 'root'@'localhost' (using password: NO)<br />
    <b>Warning</b>:  mysql_close(): no MySQL-Link resource supplied in <b>E:\Ampps\www\koneksi\db_connect.php</b> on line <b>42</b><br />
05-04 17:02:01.699      925-941/com.example.indraaaeff.e_fine2 W/dalvikvm﹕ threadid=12: thread exiting with uncaught exception (group=0xb1afdba8)
05-04 17:02:02.029      925-941/com.example.indraaaeff.e_fine2 E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    Process: com.example.indraaaeff.e_fine2, PID: 925
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at com.example.indraaaeff.e_fine2.MainActivity2$BuatFormBaru.doInBackground(MainActivity2.java:193)
            at com.example.indraaaeff.e_fine2.MainActivity2$BuatFormBaru.doInBackground(MainActivity2.java:150)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
05-04 17:02:03.279      925-925/com.example.indraaaeff.e_fine2 W/EGL_emulation﹕ eglSurfaceAttrib not implemented
05-04 17:02:03.589      925-925/com.example.indraaaeff.e_fine2 I/Choreographer﹕ Skipped 34 frames!  The application may be doing too much work on its main thread.
05-04 17:02:05.119      925-925/com.example.indraaaeff.e_fine2 I/Choreographer﹕ Skipped 87 frames!  The application may be doing too much work on its main thread.
05-04 17:02:05.889      925-925/com.example.indraaaeff.e_fine2 E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.indraaaeff.e_fine2.MainActivity2 has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b20eecf0 V.E..... R......D 0,0-729,192} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:286)
            at com.example.indraaaeff.e_fine2.MainActivity2$BuatFormBaru.onPreExecute(MainActivity2.java:160)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
            at android.os.AsyncTask.execute(AsyncTask.java:535)
            at com.example.indraaaeff.e_fine2.MainActivity2$1.onClick(MainActivity2.java:141)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)             
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)

我不知道为什么我的应用程序不能工作,我真的需要帮助。

我想你的数据库连接有错误

<b>Warning</b>:  mysql_connect() [<a href='function.mysql-connect'>function.mysql-connect</a>]: Access denied for user 'root'@'localhost' (using password: NO) in <b>E:\Ampps\www\koneksi\db_connect.php</b> on line <b>28</b><br />
Access denied for user 'root'@'localhost' (using password: NO)<br />
<b>Warning</b>:  mysql_close(): no MySQL-Link resource supplied in <b>E:\Ampps\www\koneksi\db_connect.php</b> on line <b>42</b><br />
你的连接有问题。
您可以修复它,然后可以再试一次

检查您的连接日志猫说

拒绝使用密码访问用户“root”@“localhost”:否