php - android 在使用 json 时崩溃

标签 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;
}

我在如下所示的异步任务中使用我的函数:

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/缓冲阅读器:java.io.BufferedReader@244a383c 08-18 14:03:14.322 1444-1459/? E/String Builder: {"code":1,"user":{"user_id":"3","username":"david","password":"david","email":"david"}} 08-18 14:03:14.322 1444-1459/? E/JSON:{"code":1,"user":{"user_id":"3","username":"david","password":"david","email":"david"}} 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 对象有关

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

感谢任何帮助或建议

最佳答案

我没看到你从哪里开始这个 Activity ,你刚刚完成当前的 Activity 试试这个:

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

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

关于php - android 在使用 json 时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32061200/

相关文章:

php - 安全性 - Ajax 和 Nonce 使用

android - 关联多个谷歌帐户的 Android Chrome 上的 GAE Python 应用程序(用户服务)错误

java - 共享首选项无法正确保存

mysql - 数组到字符串转换 C :\xampp\htdocs\8990API\register. php

php - 模板中的 Symfony Action 名称

php - 如果行发生更改,MySQL 更改表更改列会抛出错误

java - 无法在Android应用程序中下载完整文件

mysql - 将 MySQL 服务器从一个机器迁移到另一个机器

mysql 在包含分隔符分隔值的列中选择奇数值

PHP:用购物车中的值(value)更新库存