2014-12-03 72 views
0

我正在做一個項目,開始在Android。我試圖從mySQL數據庫讀取以及閱讀。 一切工作正常,但我只是從數據庫中讀取一行。 有誰知道爲什麼?Android JSON和php

這是我的任務是讀書,你只需要看看呼叫到的onCreate(),GetAllCostumberTask 和SetTextToview()方法

package com.example.ultimate; 

import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.ActionBarActivity; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MainActivity extends ActionBarActivity { 

    private TextView responseTextView; 
    private EditText eNombre,eApellido,eEdad,eMovil; 
    private Button b1; 

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


     this.responseTextView = (TextView) this.findViewById(R.id.responseTextView); 
     this.eNombre = (EditText) this.findViewById(R.id.editNombre); 
     this.eApellido = (EditText) this.findViewById(R.id.editApellido); 
     this.eEdad = (EditText) this.findViewById(R.id.editEdad); 
     this.eMovil = (EditText) this.findViewById(R.id.editMovil); 
     this.b1 = (Button) this.findViewById(R.id.button1); 

     new GetAllCustomerTask().execute(new ApiConnector()); 


    } 
    public void funcion(View v){ 
     if((eNombre.getText().toString().length()<1) 
       ||(eApellido.getText().toString().length()<1) 
       ||(eEdad.getText().toString().length()<1) 
       ||(eMovil.getText().toString().length()<1)){ 

      // out of range 
      Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show(); 
     }else{ 
      String[] lista = new String[4]; 

      lista[0] = eNombre.getText().toString(); 
      lista[1] = eApellido.getText().toString(); 
      lista[2] = eEdad.getText().toString(); 
      lista[3] = eMovil.getText().toString(); 
      new MyAsyncTask().execute(lista);  
     } 
    } 



    public void setTextToTextView(JSONArray jsonArray) 
    { 
     String s = ""; 

     for(int i=0; i<jsonArray.length();i++){ 

      JSONObject json = null; 
      try { 
       json = jsonArray.getJSONObject(i); 
       s = s + 
         "Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"\n"+ 
         "Age : "+json.getInt("Age")+"\n"+ 
         "Mobile Using : "+json.getString("Mobile")+"\n\n"; 
       // Toast.makeText(getApplicationContext(), "paso", Toast.LENGTH_LONG).show(); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

     } 

     this.responseTextView.setText(s); 

    } 

    private class MyAsyncTask extends AsyncTask<String, Integer, Double>{ 

     @Override 
     protected Double doInBackground(String... params) { 
      // TODO Auto-generated method stub 
      postData(params); 
      return null; 
     } 

     protected void onPostExecute(Double result){ 

      Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show(); 
     } 
     protected void onProgressUpdate(Integer... progress){ 

     } 

     public void postData(String[] valueIWantToSend) { 
      // Create a new HttpClient and Post Header 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://accessibility.es/prueba/insert.php"); 

      try { 
       // Add your data 
       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
       nameValuePairs.add(new BasicNameValuePair("FirstName", valueIWantToSend[0])); 
       nameValuePairs.add(new BasicNameValuePair("LastName", valueIWantToSend[1])); 
       nameValuePairs.add(new BasicNameValuePair("Age", valueIWantToSend[2])); 
       nameValuePairs.add(new BasicNameValuePair("Movil", valueIWantToSend[3])); 
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

       // Execute HTTP Post Request 
       HttpResponse response = httpclient.execute(httppost); 

      } catch (ClientProtocolException e) { 
       Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show(); 
      } catch (IOException e) { 
       Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show(); 
      }catch(Exception e){ 
       Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show(); 
      } 
     } 

    } 


    private class GetAllCustomerTask extends AsyncTask<ApiConnector,Long,JSONArray> 
    { 
     @Override 
     protected JSONArray doInBackground(ApiConnector... params) { 

      // it is executed on Background thread 

      return params[0].GetAllCustomers(); 
     } 

     @Override 
     protected void onPostExecute(JSONArray jsonArray) { 

      setTextToTextView(jsonArray); 


     } 
    } 

}

這裏是我的ApiConnector

package com.example.ultimate; 

import android.util.Log; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 
import org.json.JSONArray; 
import org.json.JSONException; 

import java.io.IOException; 


public class ApiConnector { 


    public JSONArray GetAllCustomers() 
    { 
     // URL for getting all customers 


     String url = "http://accessibility.es/prueba/script.php"; 

     // Get HttpResponse Object from url. 
     // Get HttpEntity from Http Response Object 

     HttpEntity httpEntity = null; 

     try 
     { 

      DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient 
      HttpGet httpGet = new HttpGet(url); 

      HttpResponse httpResponse = httpClient.execute(httpGet); 

      httpEntity = httpResponse.getEntity(); 



     } catch (ClientProtocolException e) { 

      // Signals error in http protocol 
      e.printStackTrace(); 

      //Log Errors Here 



     } catch (IOException e) { 
      e.printStackTrace(); 
     } 


     // Convert HttpEntity into JSON Array 
     JSONArray jsonArray = null; 

     if (httpEntity != null) { 
      try { 
       String entityResponse = EntityUtils.toString(httpEntity); 

       Log.e("Entity Response : ", entityResponse); 

       jsonArray = new JSONArray(entityResponse); 

      } catch (JSONException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

     return jsonArray; 


    } 


} 

以默認值的PHP腳本。對不起,忘了

<?php 


$con = $con = mysql_connect("localhost","xxxx","xxxx"); 

if (!$con) 
    { 
    die('Could not connect: ' . mysql_error()); 
    } 
mysql_select_db("TestDatabase", $con); 

$result = mysql_query("SELECT * FROM Customer"); 

while($row = mysql_fetch_assoc($result)) 
    { 
$output[]=$row; 
    } 

print(json_encode($output)); 

mysql_close($con); 


?> 

不能因聲譽鏈接圖片,我想。

好的,我現在正在調試它。我發現這個代碼沒有按預期工作。我的意思是,s String沒有更新自己,只保存第一行,但不保存其他行。 任何人都認爲s = s +「」有問題?

for(int i=0; i<jsonArray.length();i++){ 

       JSONObject json = null; 
       try { 
        json = jsonArray.getJSONObject(i); 
        s = s + 
          "Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"\n"+ 
          "Age : "+json.getInt("Age")+"\n"+ 
          "Mobile Using : "+json.getString("Mobile")+"\n\n"; 
        // Toast.makeText(getApplicationContext(), "paso", Toast.LENGTH_LONG).show(); 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

      } 
+1

print(json_encode($ output)); ...嘗試在網頁上,如果它只返回1行嘗試做一個循環並在發送之前爆炸數組 – 2014-12-03 16:55:37

+0

完成後,它會返回每個值。所以它不是腳本 – 2014-12-03 16:58:41

+0

如果它不在PHP中,那麼在Android上。 – 2014-12-03 17:00:28

回答

0

是否有可能您的腳本http://accessibility.es/prueba/script.php只返回一個客戶?

+0

已發佈腳本 – 2014-12-03 16:52:26

0

好的,我找到了答案。我在Age字段中輸入了兩個字符串數據。

因此,當我調用json.getInt(「Age」)時,它會引發一個expcetion。就這樣。愚蠢的我:D