返回的JSONObject始终为null

时间:2014-02-11 06:23:35

标签: java php android mysql

我正在开发一个Android应用程序,它将用户名和密码发送到MySQL数据库并在登录活动中接收响应(“成功”或“错误”)。但返回的JSONObject为null。以下是代码

userauth.php

<?php
    //Connecting to mysql db
    include("db.php");

    //Check for POST request
    //if(isset($_POST['tag']) && $_POST['tag'] !=''){
        //Get tag
    //  $tag = $_POST['tag'];
    //}
    //Getting username and password from android via JSON
    $username = $_POST['username'];
    $password = $_POST['password'];


    //Creating respose array
    $respose = array("tag" => $tag, "success" => 1, "error" =>0);

    //Getting data from json
    //$username='asanka102';
    //$password='asanka102';

    //Querying mysql database against userauth table for user auth
    $sql = "SELECT * FROM userauth WHERE username='$username' AND password='$password'";
    $qry = mysql_query($sql);
    $fin_result = mysql_num_rows($qry);

    //Returning true when user exists & return false when user doen's exist
    //if$fin_result > 0(){
    //  return true;
    //}else{
    //  return false;
    //}
    if($fin_result > 0){
        //User found, login should be granted
        $response["success"] = 1;
        echo json_encode($response);
    }else{
        //User not found, login shold be prohibited
        $response["error"] = 0;
        $response["error_msg"] = 'Invalid login';
        echo json_encode($response);
    }


?>

MainActivity.java

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etUsername = (EditText) findViewById(R.id.et_username);
        etPass = (EditText) findViewById(R.id.et_password);

        errorTxt = (TextView) findViewById(R.id.text_invalid_input);

        loginButton = (Button) findViewById(R.id.button_login);
        loginButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                new GetPassword().execute();


            }
        });

    }



    private class GetPassword extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {

            String username = etUsername.getText().toString();
            String password = etPass.getText().toString();
            UserFunctions userFunctions = new UserFunctions();
            JSONObject json = userFunctions.loginUser(username, password);

            //Do other things



            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
                    if (pDialog.isShowing())
                        pDialog.dismiss();

        }

    }

UserFunctions.java

public class UserFunctions {

    private JSONParser jsonParser;

    private static String login_url = "http://192.168.100.172/android/userauth.php";

    public UserFunctions(){
        jsonParser = new JSONParser();
    }

    /**
     * function make Login Request
     * @param username
     * @param password
     * */
    public JSONObject loginUser(String username, String password){
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", username));
        params.add(new BasicNameValuePair("password", password));
        JSONObject json = jsonParser.getJSONFromUrl(login_url, params);
        // return json
        // Log.e("JSON", json.toString());
        return json;
    }
}

JSONParser.java

public class JSONParser {

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

    // constructor
    public JSONParser() {
        // Empty constructor
    }

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

        // Making HTTP request
        try {
            // 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();

        } 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();
            Log.e("JSON", json);
        } 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;

    }

}

logcat提供了这个

02-11 12:29:10.457: E/Buffer Error(13927): Error converting result java.lang.NullPointerException: lock == null
02-11 12:29:10.457: E/JSON Parser(13927): Error parsing data org.json.JSONException: End of input at character 0 of 
02-11 12:29:10.457: W/dalvikvm(13927): threadid=11: thread exiting with uncaught exception (group=0x41ba5ba8)
02-11 12:29:10.467: D/dalvikvm(13927): GC_FOR_ALLOC freed 280K, 2% free 17142K/17456K, paused 10ms, total 11ms
02-11 12:29:10.477: E/AndroidRuntime(13927): FATAL EXCEPTION: AsyncTask #1
02-11 12:29:10.477: E/AndroidRuntime(13927): Process: collector.lbfinance, PID: 13927
02-11 12:29:10.477: E/AndroidRuntime(13927): java.lang.RuntimeException: An error occured while executing doInBackground()
02-11 12:29:10.477: E/AndroidRuntime(13927):    at android.os.AsyncTask$3.done(AsyncTask.java:300)
02-11 12:29:10.477: E/AndroidRuntime(13927):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
02-11 12:29:10.477: E/AndroidRuntime(13927):    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
02-11 12:29:10.477: E/AndroidRuntime(13927):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
02-11 12:29:10.477: E/AndroidRuntime(13927):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-11 12:29:10.477: E/AndroidRuntime(13927):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-11 12:29:10.477: E/AndroidRuntime(13927):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-11 12:29:10.477: E/AndroidRuntime(13927):    at java.lang.Thread.run(Thread.java:841)
02-11 12:29:10.477: E/AndroidRuntime(13927): Caused by: java.lang.NullPointerException
02-11 12:29:10.477: E/AndroidRuntime(13927):    at collector.lbfinance.MainActivity$GetPassword.doInBackground(MainActivity.java:102)
02-11 12:29:10.477: E/AndroidRuntime(13927):    at collector.lbfinance.MainActivity$GetPassword.doInBackground(MainActivity.java:1)
02-11 12:29:10.477: E/AndroidRuntime(13927):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-11 12:29:10.477: E/AndroidRuntime(13927):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-11 12:29:10.477: E/AndroidRuntime(13927):    ... 4 more

2 个答案:

答案 0 :(得分:1)

$fin_result是否会返回行?

尝试以下

try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        Log.e("JSON", json);
    } 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;

答案 1 :(得分:0)

logcat在is.close(); json = sb.toString(); Log.e("JSON", json);中的JSONParser.java说了什么。