dt3674 2014-02-05 12:53
浏览 54
已采纳

解析从php $ _SESSION []到textview的json数据的问题

i am having problems parsing json data from my php file to my textviews in my android application. for some reason it looks like the value inside $_SESSION['username'] is not being carried throughout the application. however, if i were to try it on my browser it works just fine. Below is my profile.php. i used the first if statement to check weither the json itself was the problem. sure enough, i get the default account in my android app. but i donot get the actual user.

<?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));
}

?>

below is my 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 + "
");
        }
        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;
}
}

Below is the android activity:

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();
}
}
}

and lastly, just incase you ask. my login.java( it works just fine, it does not use the same 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();
}
}
}
  • 写回答

2条回答 默认 最新

  • dth34653 2014-02-10 23:04
    关注

    SOLVED IT!!! i used shared preferences to save the json data which i parsed from the php response. took it straight from the starting ( the login ) so that it wouldnt have a chance to reset my http request. i only hope this is a safe way to do it as i am actually doing this for a user profile activity.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛