2015-02-09 68 views
0

顯示我有以下問題:的Android ParserJson在一個TextView

我創建一個包含名稱,姓名,電子郵件,國籍,國家的餐桌「登陸」的數據庫。

我想重新登錄表'login'的信息以在我的移動應用程序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保持空?

非常感謝您的幫助。

邁克爾

+0

你瀏覽器的檢查,你正確的返回值? – Jaky71 2015-02-09 21:23:19

回答

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); 
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")); 
} 
+0

你好,問題是'HttpResponse httpResponse = httpClient.execute(httpGet);'返回一個exeption,我不明白爲什麼 – mickey74 2015-02-11 14:16:06

+0

可以發佈異常嗎? – 2015-02-11 17:28:52

+0

如果你使用本地主機,可能你需要這樣做:http://www.mobitechie.com/android-2/how-to-access-localhost-on-android-over-wifi/ – 2015-02-11 17:44:06

-1

試試這個

while($row = mysql_fetch_array($req)){ 
      $acdata[] = array(
      'name' => $name, 
      'firstname' => $firstname, 
      'mail' => $mail, 
      'nationality' => $nationality, 
      'city' => $city 
      ); 
    } 


    header('Content-type: application/json'); 
    echo json_encode(array('acdata'=>$acdata)); 
+0

那麼,你至少可以在適當的格式上花費一些努力並給出一些解釋。 – Eiko 2016-09-27 13:11:19

相關問題