2016-11-30 35 views
2

我想从我的数据库中检索数据,我写了这个代码如何在Android应用程序中将从MySQL检索到的数据插入到数组中?

<?php 
require "conn.php"; 

$mysql_qry = "select * from domande"; 
$res = mysqli_query($conn,$mysql_qry); 
$result = array(); 

while($row = mysqli_fetch_array($res)){ 
array_push($result, 
array('id_domanda'=>$row[0], 
'domanda'=>$row[1], 
'username'=>$row[2] 
)); 
} 

echo json_encode(array("result"=>$result)); 

mysqli_close($conn); 

?> 

应该返回数组。我已经能够显示一个警告对话框数组中这样说:

class BackgroundWorkerDomande extends AsyncTask<String,Void,String> { 

     Context context; 
     AlertDialog alertDialog; 
     BackgroundWorkerDomande (Context ctx){ 
      context = ctx; 
     } 
     @Override 
     protected String doInBackground(String... params) { 
      String type = params[0]; 


      if (type=="getquestion"){ 
       try { 


        URL url = new URL(params[3]); 
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
        httpURLConnection.setRequestMethod("POST"); 
        httpURLConnection.setDoOutput(true); 
        httpURLConnection.setDoInput(true); 


        InputStream inputStream = httpURLConnection.getInputStream(); 
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1")); 
        String result = ""; 
        String line = ""; 
        while ((line = bufferedReader.readLine()) != null) { 
         result += line; 
        } 
        bufferedReader.close(); 
        inputStream.close(); 
        httpURLConnection.disconnect(); 
        return result; 
       } catch (MalformedURLException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 



      return null; 
     } 

     @Override 
     protected void onPreExecute() { 


      alertDialog = new AlertDialog.Builder(context).create(); 
      alertDialog.setTitle("Status"); 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      alertDialog.setMessage(result); 
      alertDialog.show(); 



     } 

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

,但如果我想插入的结果在我的MainActivity宣布一个新的阵列我应该怎么办?我只是在互联网上遵循一些教程来编写这段代码,所以我不完全知道它是如何工作的。 (对不起,我的英文不好)

回答

0

由于您发布了工作代码,但没有指定确切的问题,所以很难确切知道您想要什么。特别是,“将结果插入新数组”是什么意思?从表面上看,我看到:

ArrayList<String> results; 
results.add (result); 

不过,我会做一个建议:在你的PHP代码,而不是发布整个结果作为一个字符串,可以分解成田和张贴那些作为阵列?然后,在接收端,如果要使用各个字段值,则不需要从result解析它们。

相关问题