douaikuai2715 2013-07-25 16:40
浏览 35
已采纳

如何从php http请求[关闭]在Android中的数组中存储数据

Here is my php code :

<?php
include('connection.php');
$result = mysql_query("SELECT * FROM links");
while($row = mysql_fetch_array($result))
  {
$response["title"]=$row['title'];
$response["url"]=$row['url'];
echo json_encode($response);
  }

?>

I want to store title and url in an array in android. title[], url[].

I tried searching for http requests but couldn't find anything useful.

  • 写回答

1条回答 默认 最新

  • dongxian5735 2013-07-25 21:56
    关注

    first you should make some changes in .php, something like this:

    $r=mysql_query("select * FROM links",$con);
    while($row=mysql_fetch_array($r))
    {
    $cls[]=$row;
    }
    print(json_encode($cls));
    mysql_close($con);
    ?>
    

    If you get some results when you run this script then the first step is done. Then we go to make some coding in Java.

    This is part from one of my projects so don't just copy. It is needed to make some adjustments for your needs:

    public Map<String, String> getTitlesUrls()
    {
        Map<String,String> TitlesUrl = new HashMap<String,String>();
    
    
    
        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http:/10.0.0.2/yourscript.php");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
        }
        catch(Exception e)
        {
                Log.e("1: log_tag", "Error in http connection "+e.toString());
        }
        //convert response to string
        try
        {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
                StringBuilder sb = new StringBuilder();            
                String line = null;
                while ((line = reader.readLine()) != null) 
                {
                        sb.append(line);
                }
                is.close();
    
                result=sb.toString();
        }
        catch(Exception e)
        {
                Log.e("2: log_tag", "Error converting result "+e.toString());
        }
    
        //parse json data
        try
        {
            JSONArray jArray = new JSONArray(result);           
    
            for(int i=0;i<jArray.length();i++)
            {
                JSONObject json_data = jArray.getJSONObject(i);
            }
    
            JSONObject json_data = jArray.getJSONObject(0);
    
            TitlesUrl.put("Title", String.valueOf(json_data.getString("Title")));
            TitlesUrl.put("URL", String.valueOf(json_data.getString("url")));
    
    
        }
        catch(JSONException e)
        {
                Log.e("3: log_tag", "Error parsing data "+e.toString());
        }
    
        return TitlesUrl;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?