转换结果时出错java.lang.NullPointerException,解析数据时出错org.json.JSONException:字符0处的输入结束

时间:2015-04-09 15:35:45

标签: java php android json pdo

我正在尝试使用JSON,PDO和MySQL设置登录页面。我有三次检查我的代码,它似乎仍然没有工作。 logcat似乎显示JSON解析器无法从pdo页面读取响应,但是当我使用表单测试时,会显示我的JSON响应。请帮帮我

我的登录活动:

Button btnLogin;
TextView passreset;
EditText inputUsername;
EditText inputPassword;
private TextView ForgotPass;

private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();

private static final String LOGIN_URL = "http://10.0.2.2/ZCASPlatform/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.activity_login);

    inputUsername = (EditText)findViewById(R.id.usernametxt);
    inputPassword = (EditText)findViewById(R.id.passwordtxt);
    btnLogin = (Button)findViewById(R.id.loginBtn);
    ForgotPass =(TextView)findViewById(R.id.passres);

     btnLogin.setOnClickListener(new View.OnClickListener() 
     {
         public void onClick(View v)
            {

                {
                        new AttemptLogin().execute();
                }
            } 
     });
}




class AttemptLogin extends AsyncTask<String, String, String> 
{
    boolean failure = false;

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String...args)
    {
        int success;
        String username = inputUsername.getText().toString();
        String password = inputPassword.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);
             Log.d("Login attempt", json.toString());
             success = json.getInt(TAG_SUCCESS);

             if (success == 1)
             {
                 Log.d("Login Successful!", json.toString());
                 Intent i = new Intent(LoginActivity.this, MainActivity.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;
    }

    protected void onPostExecute(String file_url)
    {
        pDialog.dismiss();
        if (file_url != null)
        {
            Toast.makeText(LoginActivity.this, file_url, Toast.LENGTH_LONG).show();
        }
    }   
}

我的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;

}  

我的login.php

if(!empty($_POST))
{
    $query = "SELECT id, username, password FROM user WHERE username = :username";
    $query_params = array(':username' => $_POST ['username']);

    try
    {
        $stmt = $db->prepare($query);
        $result =$stmt->execute($query_params);
    }
    catch(PDOException $ex)
    {
        $response["success"] = 0;
        $response["message"] = "Login Error.Please Try Again";
        die(json_encode($response));
    }
    $validated_info = false;
    $row = $stmt->fetch();

    if ($row)
    {
        if($_POST['password'] === $row['password'])
        {
            $login_ok = true;
        }
    }
    if ($login_ok)
    {
        $response["success"] = 1;
        $response["message"] = "Login Successful";
        die(json_encode($response));
    }
    else
    {
        $response["success"] = 0;
        $response["message"] = "Invalid Credentials";
        die(json_encode($response));
    }
}

最后我的logcat响应如下:

04-06 16:51:51.513:E / Buffer Error(22626):转换结果java.lang.NullPointerException时出错 04-06 16:51:51.518:E / JSON Parser(22626):解析数据时出错org.json.JSONException:

字符0的输入结束

0 个答案:

没有答案