【发布时间】:2011-03-12 06:54:26
【问题描述】:
我是一名 PHP 开发人员(中级),并在家里练习一些 android 的东西。
我已经创建了一个数组列表,它将获取到我的 Android 应用程序内的一个 sqlite db 并填充一个 ListView。现在我正试图更进一步。
我想将该数组列表内容发送到我的 PHP 服务器,在那里我可以将给定的数据存储到 mysql 并取回我的应用程序。
我将如何实现这一目标?
【问题讨论】:
我是一名 PHP 开发人员(中级),并在家里练习一些 android 的东西。
我已经创建了一个数组列表,它将获取到我的 Android 应用程序内的一个 sqlite db 并填充一个 ListView。现在我正试图更进一步。
我想将该数组列表内容发送到我的 PHP 服务器,在那里我可以将给定的数据存储到 mysql 并取回我的应用程序。
我将如何实现这一目标?
【问题讨论】:
您可以使用 JSON 或 XML 将数据从 android 发送到 php 服务器。 在 PHP 方面,您只需要内置的 json_decode,它将反序列化您的 json 并返回一个对象或关联数组。
【讨论】:
为此,您必须将数据发布到 php 服务器上,然后获取该数据并存储到您的数据库中。
这里我附上一个例子,它在服务器上发送数据并在 json 中获得响应。
HttpPost postMethod = new HttpPost("Your Url");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// test is a one array list
for(int i=0;i<test.size();i++)
{
nameValuePairs.add(new BasicNameValuePair("sample[]", Integer.toString(test.get(i))));
}
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
DefaultHttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null)
{
InputStream inStream = entity.getContent();
result= convertStreamToString(inStream);
jsonObject = new JSONObject(result);
responseHandler.sendEmptyMessage(0);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}.start();
这里的 sample[] 是一个字段,我在其中分配数组值以在服务器上发送。您必须从服务器端获取 sample[] 字段。
public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}
【讨论】: