2017-01-08 48 views
1

我創建了一個Web服務,我想要得到的JSON對象和數據填充到列表視圖的Android 這是我的PHP代碼獲取JSON數據從PHP服務和數據填充到列表視圖的Android

$sql_query="SELECT * FROM testtable"; 
$query=mysqli_query($con,$sql_query); 
$rows = array(); 
while($r = mysqli_fetch_assoc($query)) { 
    $rows[] = $r; 
} 
print json_encode($rows); 

這是我的Android代碼,現在我想要得到的JSON對象和數據填充到Android的

public class MainActivity extends AppCompatActivity { 
    ListView listView; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 
    public void Show(View view){ 
     String method="show"; 
     BackgroundTask backgroundTask=new BackgroundTask(this); 

    } 
    } 

此列表視圖是第二類的代碼

public class BackgroundTask extends AsyncTask<Void,Void ,String> { 
     Context ctx; 
     String result; 

     AlertDialog alertDialog; 
     BackgroundTask(Context ctx) { 
      this.ctx = ctx; 
     } 

      protected String doInBackground(Void... Voids) { 
    URL url = http://hifzil.com/tayyab/select.php; 
    try { 
     url = new URL(json_get_settings_url); 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } 
    try { 
     HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); 
     InputStream inputStream = httpURLConnection.getInputStream(); 
     BufferedReader bufferedReader = new BufferedReader (new InputStreamReader(inputStream)); 
     StringBuilder stringBuilder = new StringBuilder(); 
     while((result = bufferedReader.readLine()) != null) { 
      stringBuilder.append(result+"\n"); 
     } 
     JSONObject json = new JSONObject(result); 
     bufferedReader.close(); 
     inputStream.close(); 
     httpURLConnection.disconnect(); 
     return stringBuilder.toString().trim(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

     @Override 
     protected void onPreExecute() { 
      alertDialog=new AlertDialog.Builder(ctx).create(); 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      if(result.equals("Saved")){ 
       Toast.makeText(ctx, result, Toast.LENGTH_LONG).show(); 

      } 
     } 

     @Override 
     protected void onProgressUpdate(Void... values) { 
      super.onProgressUpdate(values); 
     } 

    } 
} 

回答

0

我相信你在Android客戶端獲得正確的JSON響應,現在按照下面的步驟。

1)創建具有相同的變量模型類作爲在JSON響應

2)創建解析所有JSON響應轉換成模型類步驟-1

3)創建適配器和提取物的解析方法適用於步驟2模型類的適配器的數據,並將適配器分配給列表視圖。

相關問題