解析数据时出错org.json.JSONException:在{main}的字符6的main之后预期':'

时间:2015-06-24 20:17:48

标签: php android json

我正在通过使用php webservice连接到数据库来创建一个Android登录应用程序。我遇到以下错误,无法理解错误的来源。

  

解析数据时出错:org.json.JSONException:在main之后预期':'   {main}的字符6

现在一直在寻找解决方案几个小时但找不到任何解决方案。

Login.java类:

public class Login extends Activity implements View.OnClickListener {

    private EditText user, pass;
    Button bLogin;

    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();
    private static final String LOGIN_URL = "http://192.168.10.6/login.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        user = (EditText)findViewById(R.id.username);
        pass = (EditText)findViewById(R.id.password);
        bLogin = (Button)findViewById(R.id.login);
        bLogin.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.login:
                new AttemptLogin().execute();
                break;

            default:
                break;
        }
    }

    class AttemptLogin extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            Handler h= new Handler();
            h.post(new Runnable() {
                @Override
                public void run() {
                    pDialog = new ProgressDialog(Login.this);
                    pDialog.setMessage("Attempting login.");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(true);
                    pDialog.show();
                }
            });
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
            // Check for success tag
            int success;
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {

                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password));

                Log.d("request!", "starting");

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

                if (json != null) {
                    // check your log for json response
                    Log.d("Login attempt :", json.toString());
                }

                // json success tag
                success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    Log.d("Login Successful!", json.toString());
                    //Options.PHONE=username;
                    Intent ii = new Intent(Login.this,NewActivity.class);
                    //here Options.class is the activity where we will move once login is authenticated.
                    startActivity(ii);
                    finish();
                    // this finish() method is used to tell android os that we are done with current
                    // activity now! Moving to other activity



                    return json.getString(TAG_MESSAGE);
                }else{
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;

        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {

            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
            }

        }

    }

}

JSONParser.java类:

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj ;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(final String url) {

        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {

// Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
            String line = null;

// Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

// Close the input stream.
            is.close();
// Convert the string builder data to an actual string.
            json = sb.toString();
            Log.i("JSON Parser:", json );
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result :" + e.toString());
        }


// Try to 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 the JSON Object.
        return jObj;

    }

    // function get json from url
// by making HTTP POST or GET method
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {

// Making HTTP request
        try {

// check for request method
            if(method.equalsIgnoreCase("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.equalsIgnoreCase("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 {
            int jsonStart = json.indexOf("{");
            int jsonEnd = json.lastIndexOf("}");

            if (jsonStart >= 0 && jsonEnd >= 0 && jsonEnd > jsonStart) {
                json = json.substring(jsonStart, jsonEnd + 1);
                json = json.replaceFirst("<font>.*?</font>", "");
            } else {
                // deal with the absence of JSON content here
                Log.d("Error in string :", json);
            }
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data :" + e.toString());
        }

// return JSON String
        return jObj;

    }
}

Login.php:

<?php
$conn = mysqli_connect("127.0.0.1","root","divy");
$db= mysqli_select_db($conn,"users");
$password=$_POST["password"];
$username=$_POST["username"];

if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['password'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "Please Enter Both first Username and Password.";

//die will kill the page and not execute any code below, it will also
//display the parameter... in this case the JSON data our Android
//app will parse

die(json_encode($response));
}
$query = "SELECT * FROM yardusers WHERE username = '$username'and password ='$password' " ;

$sql1 = mysql_query($query);
if(!empty($query)) {
die(mysql_error());
}
$row = mysql_fetch_array($sql1, MYSQL_BOTH);

if (!empty($row)) {
$response["success"] = 1;

$response["message"] = "Present, this username is already in use";
die(json_encode($response));
}
else{

$response["success"] = 0;
$response["message"] = "Invalid Username or Password.";
die(json_encode($response));
}
}
else{

$response["success"] = 0;
$response["message"] = "One or both fields are empty";
die(json_encode($response));
}
//error_reporting(E_ALL ^ E_DEPRECATED);
mysql_close();
?>

Logcat:

06-24 23:32:22.535    2612-2612/com.devikanigam.login I/art﹕ Not late-enabling -Xcheck:jni (already on)
06-24 23:32:22.587    2612-2612/com.devikanigam.login W/ActivityThread﹕ Application com.devikanigam.login is waiting for the debugger on port 8100...
06-24 23:32:22.596    2612-2612/com.devikanigam.login I/System.out﹕ Sending WAIT chunk
06-24 23:32:22.602    2612-2619/com.devikanigam.login I/art﹕ Debugger is active
06-24 23:32:22.807    2612-2612/com.devikanigam.login I/System.out﹕ Debugger has connected
06-24 23:32:22.807    2612-2612/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 23:32:23.014    2612-2612/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 23:32:23.225    2612-2612/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 23:32:23.444    2612-2612/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 23:32:23.665    2612-2612/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 23:32:23.874    2612-2612/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 23:32:24.084    2612-2612/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 23:32:24.293    2612-2612/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 23:32:24.504    2612-2612/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 23:32:24.713    2612-2612/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 23:32:24.924    2612-2612/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 23:32:25.135    2612-2612/com.devikanigam.login I/System.out﹕ debugger has settled (1340)
06-24 23:32:25.189    2612-2631/com.devikanigam.login D/OpenGLRenderer﹕ Render dirty regions requested: true
06-24 23:32:25.192    2612-2612/com.devikanigam.login D/﹕ HostConnection::get() New Host Connection established 0xae0cfe80, tid 2612
06-24 23:32:25.198    2612-2612/com.devikanigam.login D/Atlas﹕ Validating map...
06-24 23:32:25.267    2612-2631/com.devikanigam.login D/﹕ HostConnection::get() New Host Connection established 0xb0a1f130, tid 2631
06-24 23:32:25.272    2612-2631/com.devikanigam.login I/OpenGLRenderer﹕ Initialized EGL, version 1.4
06-24 23:32:25.291    2612-2631/com.devikanigam.login D/OpenGLRenderer﹕ Enabling debug mode 0
06-24 23:32:25.321    2612-2631/com.devikanigam.login W/EGL_emulation﹕ eglSurfaceAttrib not implemented
06-24 23:32:25.321    2612-2631/com.devikanigam.login W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6c02c40, error=EGL_SUCCESS
06-24 23:33:00.696    2612-2632/com.devikanigam.login D/request!﹕ starting
06-24 23:33:00.874    2612-2631/com.devikanigam.login W/EGL_emulation﹕ eglSurfaceAttrib not implemented
06-24 23:33:00.874    2612-2631/com.devikanigam.login W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5a5ade0, error=EGL_SUCCESS
06-24 23:33:00.915    2612-2632/com.devikanigam.login E/JSON Parser﹕ Error parsing data :org.json.JSONException: Expected ':' after main at character 6 of {main}
06-24 23:33:00.915    2612-2632/com.devikanigam.login E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: com.devikanigam.login, PID: 2612
    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:818)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference
            at com.devikanigam.login.Login$AttemptLogin.doInBackground(Login.java:111)
            at com.devikanigam.login.Login$AttemptLogin.doInBackground(Login.java:66)
            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:818)
06-24 23:33:01.046    2612-2624/com.devikanigam.login I/art﹕ Background partial concurrent mark sweep GC freed 2070(210KB) AllocSpace objects, 0(0B) LOS objects, 54% free, 848KB/1872KB, paused 37.235ms total 101.141ms
06-24 23:33:02.622    2612-2612/com.devikanigam.login E/WindowManager﹕ android.view.WindowLeaked: Activity com.devikanigam.login.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{7ad1d70 V.E..... R......D 0,0-729,232} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:298)
            at com.devikanigam.login.Login$AttemptLogin$1.run(Login.java:83)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

1 个答案:

答案 0 :(得分:0)

如果您想要Android应用。要始终接收JSON,那么您应该在所有可能的if-else分支中使用STATICFILES_DIRS = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

目前你有:

die(json_encode($response));

首先,... $query = "SELECT * FROM yardusers WHERE username = '$username'and password ='$password' "; $sql1 = mysql_query($query); if(!empty($query)) { die(mysql_error()); // <-- Does not return JSON. } $row = mysql_fetch_array($sql1, MYSQL_BOTH); ... 将成为您的Android应用。崩溃(当然,除非你实现了正确的异常处理),其次die(mysql_error());条件总是如此,所以你的Android应用程序。将永远崩溃。

也许你的意思是:

if(!empty($query))