如何将数据持久保存从PHP到Android
答
使用HttpClient的。然后,用你的InputStream,检查此链接:
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
,并将其写入你想要的文件。
一个快速和肮脏的例子:
// This goes inside a try...
HttpClient htc = new DefaultHttpClient();
HttpGet get = new HttpGet("http://www.google.com");
HttpResponse htr = null;
htr = htc.execute(get);
InputStream is = htr.getEntity().getContent();
File saveFile = new File(getApplicationContext().getFilesDir().getPath() + File.separatorChar + "datos.txt");
FileOutputStream fos = new FileOutputStream(saveFile);
// Validate if exists and so on...
int c;
while ((c = is.read()) != -1)
{
fos.write(c);
}
// Catch, finally, close, etc...
您可能还需要缓冲的读取和写入的代码。
另一种方法就是使用:
InputStream is = URL("http://www.google.com").getContent();
这是给你的。我喜欢HttpClient,因为你可以处理更多的事情。
@VicentePlata你可以给我一个使用内部存储的例子吗?我认为最好的一个我必须使用sharedpreference,但我不知道如何使用它:(我试图把它放在我的httpconnection类中,但它给了我错误 – Livi 2011-04-23 03:58:17
完成请看我编辑的答案 – 2011-04-23 04:48:48
@ VicentePlata我尝试了你的答案,我试着首先用烤面包片显示细节
Toast.makeText(getApplicationContext(), c,Toast.LENGTH_SHORT).show();
,但没有反应:$ – Livi 2011-04-23 06:48:49