Android ParserJson以TextView显示

时间:2015-02-09 21:12:07

标签: php android mysql json

我遇到以下问题:

我使用表格'登录'创建了一个数据库。包含姓名,名字,电子邮件,国籍,国家。

我想重新阅读表格的信息'登录'在我的移动应用程序Android的TextView中显示这些信息。

所以我创建了info.php来将我的表放在JSON中:

<?php
include ("config.php");

// Recup les infos de ma base de données
$req =mysql_query('SELECT name, firstName, mail, nationality, city FROM login WHERE name = "a" ');

$output = array();

while ($row=mysql_fetch_array($req)) {   
$output[]=$row;  
}

$json = array("Login" => $output);
//on encode en JSON
echo json_encode($json);
?>

确实,我创建了我的JSONParser.java

package com.mickKoza.tournamentmanagement;


public class JSONParser {

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

// default no argument constructor for jsonparser class
public JSONParser() {

}


public JSONObject getJSONFromUrl(final String url) {

    // Making HTTP request
    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // Executing POST request & storing the response from server  locally.
        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 {


        // Create a BufferedReader
     BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        // Declaring string builder 
        StringBuilder str = new StringBuilder();
        //  string to store the JSON object.
        String strLine = null;

        // Building while we have string !equal null.
        while ((strLine = reader.readLine()) != null) {
            str.append(strLine + "\n");
        }

        // Close inputstream.
        is.close();
        // string builder data conversion  to string.
        json = str.toString();
    } catch (Exception e) {
        Log.e("Error", " something wrong with converting result " + e.toString());
    }

    // Try block used for pasrseing String to a json object
    try {
        jsonObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("json Parsering", "" + e.toString());
    }

    // Returning json Object.
    return jsonObj;

}



public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Make HTTP request
    try {

        // checking request method
        if(method == "POST"){

            // now defaultHttpClient object
            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();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            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 str = new StringBuilder();
        String strLine = null;
        while ((strLine = reader.readLine()) != null) {
            str.append(strLine + "\n");
        }
        is.close();
        json = str.toString();
    } catch (Exception e) {

  }

    // now will try to parse the string into JSON object
    try {
        jsonObj = new JSONObject(json);
    } catch (JSONException e) {

   }


    return jsonObj;

}

}

创建我的android类InfoMembre.java后

package com.mickKoza.tournamentmanagement;

public class InfoMembre extends Activity {

// Declare Variables
TextView name;
TextView firstName;
TextView email;
TextView nationality;
TextView city;

private static final String INFO_URL = "http://192.168.20.202/BD_Projet/info.php";

// JSON parser class
JSONParser jsonParser = new JSONParser();

ArrayList<HashMap<String, String>> arraylist;

private Button btnLinkToMenu;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_info_membre);

    ArrayList<String> donnees = new ArrayList<String>();

    name = (TextView)findViewById(R.id.name);
    firstName = (TextView)findViewById(R.id.firstName);
    email = (TextView)findViewById(R.id.email);
    nationality = (TextView)findViewById(R.id.country);
    city = (TextView)findViewById(R.id.city);

    try {

    //Renvoie l'objet JSON de la requête
    JSONObject jsonObjet = jsonParser.getJSONFromUrl(INFO_URL);

    /*// On récupère le tableau d'objets qui nous concernent
    JSONArray array = jsonObjet.getJSONArray("Login");
    // Pour tous les objets on récupère les infos
    for (int i = 0; i < array.length(); i++) {
        // On récupère un objet JSON du tableau
        JSONObject obj = array.getJSONObject(i);*/

        String userName = jsonObjet.getString("name");
        String userFirstName = jsonObjet.getString("firstName");
        String userEmail = jsonObjet.getString("mail");
        String userCountry = jsonObjet.getString("nationality");
        String userCity = jsonObjet.getString("city");

        name.setText(userName);
        firstName.setText(userFirstName);
        email.setText(userEmail);
        nationality.setText(userCountry);
        city.setText(userCity);
   // }

    /*String mResponse = jsonObjet.getString("name");
    name.setText(mResponse);*/
    } catch (Exception e) {
        e.printStackTrace();
    }


    // Link to MainMenuActivity Screen      
    btnLinkToMenu = (Button) findViewById(R.id.btnLinkToMenuScreen);
    btnLinkToMenu.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(InfoMembre.this, MainMenuActivity.class);
            startActivity(i);
            finish();
        }

    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.info_membre, menu);
    return true;
}

}

我的activity_info_membre.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.mickKoza.tournamentmanagement.InfoMembre" >

<TextView
    android:id="@+id/infoUser"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="27dp"
    android:text="@string/infoUser" />

<TableLayout
    style="@style/frag1TableLayout"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/infoUser"
    android:layout_marginTop="52dp" >

    <TableRow style="@style/frag1HeaderTableRow" >
    </TableRow>

    <TableRow style="@style/frag1TableRow" >

        <TextView
            style="@style/frag1Col"
            android:text="@string/Name"
            android:padding="4.5dip"
             />

        <TextView
            android:id="@+id/name"
            style="@style/frag1Col" />
    </TableRow>

    <TableRow style="@style/frag1TableRow" >

        <TextView
            style="@style/frag1Col"
            android:text="@string/FirstName"
            android:padding="4.5dip" />

        <TextView
            android:id="@+id/firstName"
            style="@style/frag1Col" />
    </TableRow>

    <TableRow style="@style/frag1TableRow" >

        <TextView
            style="@style/frag1Col"
            android:text="@string/email"
            android:padding="4.5dip" />

        <TextView
            android:id="@+id/email"
            style="@style/frag1Col" />
    </TableRow>

    <TableRow style="@style/frag1TableRow" >

        <TextView
            style="@style/frag1Col"
            android:text="@string/nationality"
            android:padding="4.5dip" />

        <TextView
            android:id="@+id/country"
            style="@style/frag1Col" />
    </TableRow>

    <TableRow style="@style/frag1TableRow" >

        <TextView
            style="@style/frag1Col"
            android:text="@string/city"
            android:padding="4.5dip" />

        <TextView
            android:id="@+id/city"
            style="@style/frag1Col" />
    </TableRow>
</TableLayout>

 <!--  Link to Login Screen -->

    <Button
        android:id="@+id/btnLinkToMenuScreen"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="19dp"
        android:background="@null"
        android:text="@string/btnMenuMain"
        android:textColor="#0000FF"
        android:textStyle="bold" />

 </RelativeLayout>

所以,任何人都可以解释为什么我的TextViews保持空白???

提前感谢您的帮助。

迈克尔

3 个答案:

答案 0 :(得分:0)

像这样修改你的php文件因为我认为存在问题

<?php

try{
    $handler = new PDO('mysql:host=localhost;dbname=database', 'root', 'password');
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(Exception $e){
    echo $e->getMessage();
    die();
}

$query = $handler->query('SELECT name, firstName, mail, nationality, city FROM login WHERE name = "a"');
$records = array();
$records = $query->fetchAll(PDO::FETCH_ASSOC);
$json['login'] = $records;
echo json_encode($json);

答案 1 :(得分:0)

尝试在浏览器中显示数据,如果它不是空的,尝试获取数组对象而不是对象,然后循环以从对象中获取项目。

JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
                Item element = null;

                JSONObject json_local = jArray.getJSONObject(i);
                json_local.getInt("xxxx")
                json_local.getString("xxxxx"),
                json_local.getString("xxxxxx"));
}

答案 2 :(得分:-1)

试试这个

{{1}}