使用json时android崩溃了

时间:2015-08-17 23:15:07

标签: php android mysql json

下面我发布了我的JSONParser代码:

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("JSONN ", 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;

}

这里我用我的函数开始登录:

public JSONObject loginUser(String username, String password){

    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("username", username));
    params.add(new BasicNameValuePair("password", password));
    JSONObject json = jsonParser.getJSONFromUrl(loginURL+login_tag+".php", params);

    return json;
}

我在Async任务中使用我的函数,如下所示:

public void login(View view){
    new ProcessLogin().execute();
}

/**
 * Async Task to get and send data to My Sql database through JSON respone.
 **/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {


    private ProgressDialog pDialog;

    String username, password;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        usernameField = (EditText) findViewById(R.id.editText1);
        passwordField = (EditText) findViewById(R.id.editText2);

        username = usernameField.getText().toString();
        password = passwordField.getText().toString();

    }

    @Override
    protected JSONObject doInBackground(String... args) {

        UserFunctions userFunction = new UserFunctions();
        JSONObject json = userFunction.loginUser(username, password);
        return json;
    }

    @Override
    protected void onPostExecute(JSONObject json) {

        try {

            int code = json.getInt("code");

            Log.d("myLog", "JSON get code :" + String.valueOf(code));

            if (code == 1) {

                Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG).show();
                   Intent upanel = new Intent(getApplicationContext(), MainActivity.class);
                       finish();
                } else {


                }

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

    }
}

这是我的PHP代码:

<?php
$con=mysqli_connect("localhost","root","","my_db");
//echo "Welcome, I am connecting Android to PHP, MySQL";

if (mysqli_connect_errno($con))
{
   //echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

//$username = 'admin';
//$password = 'admin';

$username = $_POST['username'];
$password = $_POST['password'];





//Für die Überprüfung
$result = mysqli_query($con,"SELECT * FROM user where Username='$username' and Password='$password'");


 //if($result){




//$user = $user_details 
//$flag['code'] =0;
$response['code'] = 0;

if(mysqli_num_rows($result)==1){
    $flag['code']=1;

    //Für UserDetails

    $user_details = mysqli_fetch_array($result);


    //User wird im JSON Object gespeichert
    $response["code"] = 1;
    $response["user"]["user_id"] = $user_details["user_id"];
    $response["user"]["username"] = $user_details["Username"];
    $response["user"]["password"] = $user_details["Password"];
    $response["user"]["email"] = $user_details["E-Mail"];



} else {
    $response['code'] = 0;
    //$flag['code']=0;

}

// }    


//print(json_encode($flag));
//print(json_encode($user_details));
print json_encode($response);


mysqli_close($con);
?>

我知道哈希密码会更好,但我想稍后再这样做。 我添加了更多日志,现在我有了这个日志:

08-18 14:03:14.313 1444-1459 /? E / HTTPClient:org.apache.http.conn.EofSensorInputStream@1abaea2f 08-18 14:03:14.317 1444-1459 /? E / Buffered Reader:java.io.BufferedReader@244a383c 08-18 14:03:14.322 1444-1459 /? E / String Builder:{&#34;代码&#34;:1,&#34;用户&#34;:{&#34; user_id&#34;:&#34; 3&#34;,&#34;用户名& #34;:&#34;大卫&#34;&#34;密码&#34;:&#34;大卫&#34;&#34;电子邮件&#34;:&#34;大卫&#34;}} 08-18 14:03:14.322 1444-1459 /? E / JSON:{&#34;代码&#34;:1,&#34;用户&#34;:{&#34; user_id&#34;:&#34; 3&#34;,&#34;用户名&# 34;:&#34;大卫&#34;&#34;密码&#34;:&#34;大卫&#34;&#34;电子邮件&#34;:&#34;大卫&#34;}} 08-18 14:03:14.439 55-55 /? D / gralloc:在创建缓冲区的过程中注册缓冲区。这可能会导致内存排序问题。 08-18 14:03:14.439 55-55 /? E / libEGL:称为未实现的OpenGL ES API 08-18 14:03:14.440 55-55 /? E / SurfaceFlinger:glCheckFramebufferStatusOES错误0 08-18 14:03:14.440 55-55 /? E / SurfaceFlinger:在截取屏幕时出现GL_FRAMEBUFFER_COMPLETE_OES错误

该应用不会制作截图或类似的东西。 我认为错误可能与JSON对象

有关

这只是其中的一部分,但我认为这应该足够了。

感谢任何帮助或建议

2 个答案:

答案 0 :(得分:0)

我认为你的代码一直在崩溃,因为你以一种它不应该的方式初始化变量。请将它们放在try-catch块之外,例如:

DefaultHttpClient httpClient = null;

try {
    httpClient = new DefaultHttpClient();
} catch(...) {
    ...
}

请注意正确关闭您的溪流。正确的流开闭行为应编码如下:

BufferedReader reader = null;

try {
    try {
       reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
    } finally {
        if(reader != null)
            reader.close();
    }
} catch (IOException e) {
    e.printStackTrace();
}

如果这没有帮助,请向我们提供更具体的信息,确切地说代码会一直崩溃并将错误消息附加到您的帖子中。否则我们无法为您提供帮助。

答案 1 :(得分:0)

我没看到你开始活动的地方,你刚刚完成当前的尝试:

Intent upanel = new Intent(getApplicationContext(), MainActivity.class);
startActivity(upanel);
//finish();

除此之外,JSON看起来有效并且日志不显示崩溃。