解析数据时出错org.json.JSONException:字符0处的输入结束

时间:2014-08-21 00:00:06

标签: android

我尝试登录应用程序,但我一直遇到"解析数据时出错org.json.JSONException:"

的字符0输入结束

我的Login.java看起来像这样

public class Login extends Activity实现OnClickListener {     私人EditText用户,传递;

private Button mSubmit, mRegister;

 // Progress Dialog
private ProgressDialog pDialog;

// JSON parser class

JSONParser jsonParser = new JSONParser();

//php login script location:

//localhost :
//testing on your device

//put your local ip instead,  on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1


//testing on Emulator:

private static final String LOGIN_URL =" my url";

//从真实服务器进行测试:

//JSON element ids from repsonse of php script:

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.activity_login);
  //setup input fields

    user = (EditText)findViewById(R.id.username);

    pass = (EditText)findViewById(R.id.password);





    //setup buttons

    mSubmit = (Button)findViewById(R.id.button1);

    mRegister = (Button)findViewById(R.id.button2);
  //register listeners

    mSubmit.setOnClickListener(this);

    mRegister.setOnClickListener(this);

}

@Override

public void onClick(View v) {

    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.button1:
            new AttemptLogin().execute();
        break;
    case R.id.button2:
         Intent i = new Intent(this, Register.class);

            startActivity(i);
        break;

    default:
        break;
 }

}

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


     * */


    boolean failure = false;


    @Override

    protected void onPreExecute() {



        super.onPreExecute();

        pDialog = new ProgressDialog(Login.this);

        pDialog.setMessage("Attempting login...");
     pDialog.setIndeterminate(false);
     pDialog.setCancelable(true);
    pDialog.show();

    }
@Override

    protected String doInBackground(String... args) {
    /** String username = user.getText().toString();


     String password = pass.getText().toString();**/

    String username,password;
     username = user.getText().toString();


     password = pass.getText().toString();



        // TODO Auto-generated method stub

         // Check for success tag

        int success;

        try {

            // Building Parameters

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("username", username));

            params.add(new BasicNameValuePair("password", password));

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

            // getting product details by making HTTP request

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



            // 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());
          Intent i = new Intent(Login.this, ReadComments.class);

                finish();

                startActivity(i);

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

        // dismiss the dialog once product deleted

        pDialog.dismiss();

        if (file_url != null){

            Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();

        }

    }

}

}

我的JSONParser.java看起来像这样: `

  

公共类JSONParser {

static InputStream is = null;   static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
    HttpResponse httpResponse = httpClient.execute(httpPost);
        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;
}
  

//函数从url获取json

     

//通过发布HTTP POST或GET mehtod

     

public JSONObject makeHttpRequest(String url,String method,List 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();
       Log.e("Buffer Error", "ClientProtocolException " + e.toString());
   } catch (IOException e) {
       e.printStackTrace();

       Log.e("Buffer Error", "IOException " + e.toString());
   }

   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;

} }

我的login.php看起来很喜欢

&LT; ?PHP的

//加载并连接到MySQL数据库的东西
要求(&#34;的config.inc.php&#34);

if(!empty($ _ POST)){     //根据用户名获取用户的信息。

$query = "

        SELECT

            id,username,password  

        FROM users  

        WHERE  

            username = :username

    ";  



$query_params = array(  

    ':username' => $_POST['username']  

);

try {  

    $stmt   = $db->prepare($query);  

    $result = $stmt->execute($query_params);  

}  

catch (PDOException $ex) {  

    // For testing, you could use a die and message.  

    //die("Failed to run query: " . $ex->getMessage());         

    //or just use this use this one to product JSON data:  

    $response["success"] = 0;  

    $response["message"] = "Database Error1. Please Try Again!";  
    // echo json_encode($response);  
   // die(json_encode($response));  
}  



//This will be the variable to determine whether or not the user's information is   correct.  

//we initialize it as false.  

$validated_info = false;  

//fetching all the rows from the query  

$row = $stmt->fetch();  

if ($row) {  

    //if we encrypted the password, we would unencrypt it here, but in our case we just  

    //compare the two passwords  

    if ($_POST['password'] === $row['password']) {  

        $login_ok = true;  

    }

}



// If the user logged in successfully, then we send them to the private members-only page  

// Otherwise, we display a login failed message and show the login form again  

if ($login_ok) {  

    $response["success"] = 1;  

    $response["message"] = "Login successful!";  
   //  echo json_encode($response);  
   // die(json_encode($response));  

} else {  

    $response["success"] = 0;  

    $response["message"] = "Invalid Credentials!";  
  //   echo json_encode($response);  
 //   die(json_encode($response))  

}   

死(json_encode($ response));
} else {

&GT;

    <h1>Login</h1>

    <form action="login.php" method="post">

        Username:<br />

        <input type="text" name="username" placeholder="username" />

        <br /><br />

        Password:<br />

        <input type="password" name="password" placeholder="password" value="" />

        <br /><br />

        <input type="submit" value="Login" />

    </form>

    <a href="register.php">Register</a>

<?php

}

&GT;

最后是我的logcat`

  

&#39; 08-21 01:28:53.663:D / request!(32513):开始
  08-21 01:28:54.507:D / dalvikvm(32513):GC_FOR_MALLOC释放134K,47%免费3032K / 5639K,外部507K / 517K,暂停101ms
  08-21 01:29:04.921:E / JSON Parser(32513):解析数据时出错org.json.JSONException:字符0的输入结束   08-21 01:29:04.929:W / dalvikvm(32513):threadid = 9:线程退出未捕获异常(组= 0x40018578)
  08-21 01:29:04.952:E / AndroidRuntime(32513):致命异常:AsyncTask#1
  08-21 01:29:04.952:E / AndroidRuntime(32513):java.lang.RuntimeException:执行doInBackground()时发生错误
  08-21 01:29:04.952:E / AndroidRuntime(32513):在android.os.AsyncTask $ 3.done(AsyncTask.java:200)
  08-21 01:29:04.952:E / AndroidRuntime(32513):at java.util.concurrent.FutureTask $ Sync.innerSetException(FutureTask.java:274)
  08-21 01:29:04.952:E / AndroidRuntime(32513):at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
  08-21 01:29:04.952:E / AndroidRuntime(32513):at java.util.concurrent.FutureTask $ Sync.innerRun(FutureTask.java:308)
  08-21 01:29:04.952:E / AndroidRuntime(32513):at java.util.concurrent.FutureTask.run(FutureTask.java:138)
  08-21 01:29:04.952:E / AndroidRuntime(32513):at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
  08-21 01:29:04.952:E / AndroidRuntime(32513):at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:581)
  08-21 01:29:04.952:E / AndroidRuntime(32513):at java.lang.Thread.run(Thread.java:1019)
  08-21 01:29:04.952:E / AndroidRuntime(32513):引起:java.lang.NullPointerException
  08-21 01:29:04.952:E / AndroidRuntime(32513):at com.example.prova1.Login $ AttemptLogin.doInBackground(Login.java:179)   08-21 01:29:04.952:E / AndroidRuntime(32513):at com.example.prova1.Login $ AttemptLogin.doInBackground(Login.java:1)
  08-21 01:29:04.952:E / AndroidRuntime(32513):在android.os.AsyncTask $ 2.call(AsyncTask.java:185)
  08-21 01:29:04.952:E / AndroidRuntime(32513):at java.util.concurrent.FutureTask $ Sync.innerRun(FutureTask.java:306)
  08-21 01:29:04.952:E / AndroidRuntime(32513):...还有4个   08-21 01:29:12.710:E / WindowManager(32513):活动com.example.prova1.Login泄露了最初添加的窗口com.android.internal.policy.impl.PhoneWindow$DecorView@4054add8
  08-21 01:29:12.710:E / WindowManager(32513):android.view.WindowLeaked:Activity com.example.prova1.Login泄漏了窗口com.android.internal.policy.impl.PhoneWindow$DecorView@4054add8最初添加在这里
  08-21 01:29:12.710:E / WindowManager(32513):在android.view.ViewRoot。(ViewRoot.java:263)
  08-21 01:29:12.710:E / WindowManager(32513):在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:171)
  08-21 01:29:12.710:E / WindowManager(32513):在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:114)
  08-21 01:29:12.710:E / WindowManager(32513):在android.view.Window $ LocalWindowManager.addView(Window.java:424)
  08-21 01:29:12.710:E / WindowManager(32513):在android.app.Dialog.show(Dialog.java:241)
  08-21 01:29:12.710:E / WindowManager(32513):at com.example.prova1.Login $ AttemptLogin.onPreExecute(Login.java:134)
  08-21 01:29:12.710:E / WindowManager(32513):在android.os.AsyncTask.execute(AsyncTask.java:391)
  08-21 01:29:12.710:E / WindowManager(32513):at com.example.prova1.Login.onClick(Login.java:97)
  08-21 01:29:12.710:E / WindowManager(32513):在android.view.View.performClick(View.java:2485)
  08-21 01:29:12.710:E / WindowManager(32513):在android.view.View $ PerformClick.run(View.java:9080)
  08-21 01:29:12.710:E / WindowManager(32513):在android.os.Handler.handleCallback(Handler.java:587)
  08-21 01:29:12.710:E / WindowManager(32513):在android.os.Handler.dispatchMessage(Handler.java:92)
  08-21 01:29:12.710:E / WindowManager(32513):在android.os.Looper.loop(Looper.java:130)   08-21 01:29:12.710:E / WindowManager(32513):在android.app.ActivityThread.main(ActivityThread.java:3687)
  08-21 01:29:12.710:E / WindowManager(32513):at java.lang.reflect.Method.invokeNative(Native Method)
  08-21 01:29:12.710:E / WindowManager(32513):at java.lang.reflect.Method.invoke(Method.java:507)
  08-21 01:29:12.710:E / WindowManager(32513):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:867)   08-21 01:29:12.710:E / WindowManager(32513):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
  08-21 01:29:12.710:E / WindowManager(32513):at dalvik.system.NativeStart.main(Native Method)`

任何帮助都将受到高度赞赏。谢谢!

1 个答案:

答案 0 :(得分:1)

我在PHP中看到你返回一个 JSONarray ,并在你的代码中解析它像 JSONobject

首先尝试将其解析为 JSONarray ,然后获取 JSONobect

JSONArray jsonarray = new JSONArray(json);
JSONObject jsonobj = jsonarray.getJSONObject(0);
int x = jsonobj.getInt("success");