【问题标题】:Problems parsing json data from php $_SESSION[] to textview将 json 数据从 php $_SESSION[] 解析到 textview 时出现问题
【发布时间】:2017-04-26 17:34:43
【问题描述】:

我在将 json 数据从我的 php 文件解析到我的 android 应用程序中的 textviews 时遇到问题。由于某种原因,$_SESSION['username'] 中的值似乎没有在整个应用程序中携带。但是,如果我要在我的浏览器上尝试它,它工作得很好。 下面是我的profile.php。我使用第一个 if 语句来检查 json 本身是否有问题。果然,我在我的 android 应用程序中获得了默认帐户。但我没有得到实际用户。

<?php

require("config.inc.php");
if(isset($_SESSION['username']))
{
//initial query
$query = "SELECT * from users where username = '".$_SESSION['username'] ."'";
}else{
$query = "SELECT * from users where username = 'default'";
}
//execute query
try {
$stmt   = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}

// Finally, we can retrieve all of the found rows into an array using fetchAll 
$rows = $stmt->fetchAll();


if ($rows) {
$response["success"] = 1;
$response["message"] = "user Available!";
$response["users"]   = array();

foreach ($rows as $row) {
    $post             = array();
$post["id"]  = $row["id"];

    $post["username"] = $row["username"];
    $post["gender"]    = $row["gender"];
    //$post["message"]  = $row["message"];
//$post["event_img"]= $row["event_img"];


    //update our repsonse JSON data
    array_push($response["users"], $post);
    }

    // echoing JSON response
    echo json_encode($response);


} else {
$response["success"] = 0;
$response["message"] = "No user Available!";
die(json_encode($response));
}

?>

下面是我的 jsonparser:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONprofile {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONprofile() {
}
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;
}
}

下面是安卓活动:

package com.wordpress.yourhappening.happening;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Profile extends Activity {
//URL to get JSON Array
private static String url = "http://192.168.1.10/webservice/profile.php";
//JSON Node Names
private static final String TAG_USER = "users";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "username";
JSONArray users = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.profile);
    // Creating new JSON Parser
    JSONParser jParser = new JSONParser();
    // Getting JSON from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    try {
        // Getting JSON Array
        users = json.getJSONArray(TAG_USER);
        JSONObject c = users.getJSONObject(0);
        // Storing  JSON item in a Variable
        String id = c.getString(TAG_ID);
        String name = c.getString(TAG_NAME);
        //Importing TextView
        final TextView uid = (TextView)findViewById(R.id.pr_username);
        final TextView name1 = (TextView)findViewById(R.id.pr_gender);
        //Set JSON Data in TextView
        uid.setText(id);
        name1.setText(name);
} catch (JSONException e) {
    e.printStackTrace();
}
}
}

最后,以防万一你问。我的 login.java(它工作得很好,它不使用相同的 JSONparser)

package com.wordpress.yourhappening.happening;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Profile extends Activity {
//URL to get JSON Array
private static String url = "http://192.168.1.10/webservice/profile.php";
//JSON Node Names
private static final String TAG_USER = "users";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "username";
JSONArray users = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.profile);
    // Creating new JSON Parser
    JSONParser jParser = new JSONParser();
    // Getting JSON from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    try {
        // Getting JSON Array
        users = json.getJSONArray(TAG_USER);
        JSONObject c = users.getJSONObject(0);
        // Storing  JSON item in a Variable
        String id = c.getString(TAG_ID);
        String name = c.getString(TAG_NAME);
        //Importing TextView
        final TextView uid = (TextView)findViewById(R.id.pr_username);
        final TextView name1 = (TextView)findViewById(R.id.pr_gender);
        //Set JSON Data in TextView
        uid.setText(id);
        name1.setText(name);
} catch (JSONException e) {
    e.printStackTrace();
}
}
}

【问题讨论】:

    标签: php android json session


    【解决方案1】:

    我猜服务器将每个 http 请求视为一个单独的会话。据我所知,Android 不会像您的浏览器那样使用 cookie。解决此问题的一种方法是将您的用户名发布在每个 http 请求上,作为附加到 URL 的 $_POST 变量,如下所示:

    HttpPost httppost = new HttpPost(URL);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("username", username));  
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    

    然后在您的 php 文件中,而不是 $_SESSION['username'] 使用 $_POST['username']

    【讨论】:

    • 亚历克斯,谢谢您的回复。但是,我不认为这对我有用。或者也许我不明白。我将你提供的代码放在我有 http 请求的 JSONprofile(我的 JSONPaser 文件)中,但它似乎仍然不起作用。我在徘徊,我已经将用户名存储在共享首选项中,我可以在 JSONparser 中使用它吗?由于某种原因,当我尝试使用它时出现错误:'code' SharedPreferences restoresp = PreferenceManager.getDefaultSharedPreferences(this); String name = restoresp.getString("username","");'code'
    • 我不知道你如何存储你的用户名,在我添加的代码中用户名代表一个字符串。将其存储在易于访问的位置(例如您的活动类中的公共字符串)或使用以下内容将其从您的偏好中拖动: SharedPreferences preferences = getPreferences(MODE_PRIVATE); String username=preferences.getString("username", "default");同样在您的 php 中,您可以通过测试是否设置了 $_SESSION 然后测试是否设置了 $_POST 来使其可以从浏览器或 android 访问。一切顺利。
    • 遵循完全不同的思路,我想知道如果您每次要访问数据时都没有生成全新的 DefaultHttpClient(),服务器是否会将会话识别为相同的。无论如何,最好将其放入您的初始化内容中,并为每个帖子使用相同的内容。
    【解决方案2】:

    解决了!!!我使用共享首选项来保存我从 php 响应中解析的 json 数据。直接从一开始(登录)就可以了,这样它就没有机会重置我的 http 请求了。我只希望这是一种安全的方法,因为我实际上是为用户个人资料活动这样做的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      相关资源
      最近更新 更多