Android 将json文件保存到内部内存
嘿,伙计们,女孩们,我有这段代码,应该下载一个json对象,然后保存到内存中,我一直被困在这里Android 将json文件保存到内部内存,android,entity,save,internal,Android,Entity,Save,Internal,嘿,伙计们,女孩们,我有这段代码,应该下载一个json对象,然后保存到内存中,我一直被困在这里 try{ //connects to mySQL HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php"); HttpResponse response =
try{
//connects to mySQL
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php");
HttpResponse response = client.execute(post);
//captures the response
entity = response.getEntity();
}catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
is = entity.getContent();
String FILENAME = "story.json";
//gives file name
FileOutputStream output = openFileOutput(FILENAME, MODE_WORLD_READABLE);
//creates new StreamWriter
OutputStreamWriter writer = new OutputStreamWriter(output);
//writes json with file name story.json
writer.write(is);
writer.flush();
//closes writer
writer.close();
}catch(Exception e) {
Log.e("log_tag", "Error saving string "+e.toString());
}
我在writer.write(is)上不断出错;eclipse要求我将其更改为int,从该行编写代码的最佳方式是什么
entity = response.getEntity();
这是我的全部代码
public class MainActivity extends Activity {
String storyObj = "";
Object json = null;
HttpEntity entity = null;
InputStream is = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//button that saves the file from mySQL
Button save = (Button) findViewById(R.id.downloadBtn);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveJson();
}
});
//Button that opens the file from InternalMemory
Button open = (Button) findViewById(R.id.showBtn);
open.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openJson();
}
});
//end of onCreate()
}
//saveJson pull a JSON file from mySQl server then saves that file in its JSON type eg .json
public void saveJson(){
TextView test = (TextView) findViewById(R.id.showView);
try{
//connects to mySQL
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php");
HttpResponse response = client.execute(post);
//captures the response
entity = response.getEntity();
}catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
is = entity.getContent();
String FILENAME = "story.json";
//gives file name
FileOutputStream output = openFileOutput(FILENAME, MODE_WORLD_READABLE);
//creates new StreamWriter
OutputStreamWriter writer = new OutputStreamWriter(output);
//writes json with file name story.json
writer.write(is);
writer.flush();
//closes writer
writer.close();
}catch(Exception e) {
Log.e("log_tag", "Error saving string "+e.toString());
}
//end of saveJson()
}
private char[] Object(Object json2) {
// TODO Auto-generated method stub
return null;
}
public void openJson(){
TextView test = (TextView) findViewById(R.id.showView);
try{
FileInputStream fileInput = openFileInput("story.json");
BufferedReader inputReader = new BufferedReader(new InputStreamReader(fileInput, "UTF-8"), 8);
StringBuilder strBuilder = new StringBuilder();
String line = null;
while ((line = inputReader.readLine()) != null) {
strBuilder.append(line + "\n");
}
fileInput.close();
storyObj = strBuilder.toString();
}catch(IOException e){
Log.e("log_tag", "Error building string "+e.toString());
}
try{
JSONArray jArray = new JSONArray(storyObj);
String storyNames = "";
for(int i = 0;i<jArray.length();i++){
storyNames += jArray.getJSONObject(i).getString("story_name") +"\n";
}
test.setText(storyNames);
}catch(JSONException e) {
Log.e("log_tag", "Error returning string "+e.toString());
}
return;
//and of openJson()
}
//end of class body
}
如果是这样,我在阅读时出错了这是一个奇怪的情况,我编辑了我以前的答案来解决你的这个问题。然而,有人问了另一个问题,我的这部分内容如下: 关于您得到的错误-您正试图将响应的实体直接转换为整数。这将始终失败,因为Integer不是
HttpEntity
的超类。您需要读取字符串中实体的内容,然后将字符串的内容解析为整数:
InputStream entityStream = entity.getcontent();
StringBuilder entityStringBuilder = new StringBuilder();
byte [] buffer = new byte[1024];
int bytesReadCount;
while ((bytesReadCount = entityStream.read(buffer)) > 0) {
entityStringBuilder.append(new String(buffer, 0, bytesReadCount));
}
String entityString = entityStringBuilder.toString();
writer.wrtie(entityString);
这不是高度优化的,但可以完成这项工作。从那时起,您可以随意使用responseInteger
值。但是,如果要执行writer.write
,则需要String
值,而不是Integer
。因此,我建议您使用entityString
试试这段代码
package com.android.test.CacheDemo;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class CachingDemoActivity extends Activity implements OnClickListener{
private static String URL="http://bhaskar1.cntdy.mobi/punjabkesari/appdetails/sectiondetails.json";
private static String FILE_NAME = "CachedResponse";
private Button startAPICallButton;
private Button retrieveFromCacheButton;
/* view lifecycle methods*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.initializeComponents();
}
/*overriden methods*/
public void onClick(View clickedView)
{
if(clickedView == this.startAPICallButton)
{
Toast.makeText(this, "Making the API call... Please wait", Toast.LENGTH_LONG).show();
this.makeAPICall();
}
else if(clickedView == this.retrieveFromCacheButton)
{
Toast.makeText(this, "Retrieving data from the cache!!!", Toast.LENGTH_LONG).show();
this.retrieveStuffFromCache();
}
}
/* private methods*/
private void initializeComponents()
{
this.startAPICallButton = (Button) this.findViewById(R.id.start_api_call_button);
this.startAPICallButton.setOnClickListener(this);
this.retrieveFromCacheButton = (Button) this.findViewById(R.id.retrieve_cache_button);
this.retrieveFromCacheButton.setOnClickListener(this);
}
private void makeAPICall()
{
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
//download the json onto the device.
URL url = new URL(CachingDemoActivity.URL);
URLConnection connection = url.openConnection();
//read the data and store it in a byte array first.
//dont use this code for big json file
//as long as its a json and not very long, this will work just fine!!!
InputStream inStream = connection.getInputStream();
ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
int readByte = 0;
//read the bytes one-by-one from the inputstream to the buffer.
while(true)
{
readByte = inStream.read();
if(readByte == -1)
{
break;
}
byteOutStream.write(readByte);
}
byteOutStream.flush();
inStream.close();
byteOutStream.close();
byte[] response = byteOutStream.toByteArray();
//now response byte array is the complete json in the biary form. We will save this stuff to file.
File cacheDir = CachingDemoActivity.this.getCacheDir();
File jsonFile = new File(cacheDir, FILE_NAME);
FileOutputStream outStream = new FileOutputStream(jsonFile);
//write the whole data into the file
for(int i = 0; i < response.length; i++)
{
outStream.write(response[i]);
}
android.util.Log.e("status - ","API call is complete!!");
//this should do the trick of saving all the stuff in the file with file name CachedResponse!!
//let see if we can retrieve the stuff!!!
}
catch (Exception e)
{
e.printStackTrace();
}
}
}).start();
}
private void retrieveStuffFromCache()
{
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
File jsonFile = new File(CachingDemoActivity.this.getCacheDir(), FILE_NAME);
FileInputStream fInStream = new FileInputStream(jsonFile);
ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
int readByte = 0;
while(true)
{
readByte = fInStream.read();
if(readByte == -1)
{
break;
}
byteOutStream.write(readByte);
}
fInStream.close();
byteOutStream.flush();
byteOutStream.close();
byte[] retrievedStringData = byteOutStream.toByteArray();
String originalJson = new String(retrievedStringData);
android.util.Log.e("json - ", originalJson);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}).start();
}
}
package com.android.test.CacheDemo;
导入java.io.ByteArrayOutputStream;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.io.InputStream;
导入java.net.URL;
导入java.net.URLConnection;
导入android.app.Activity;
导入android.os.Bundle;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.Toast;
公共类CachingDemoActivity扩展了活动实现OnClickListener{
专用静态字符串URL=”http://bhaskar1.cntdy.mobi/punjabkesari/appdetails/sectiondetails.json";
私有静态字符串文件\u NAME=“CachedResponse”;
专用按钮startAPICallButton;
从缓存按钮检索私有按钮;
/*查看生命周期方法*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.initializeComponents();
}
/*重写方法*/
单击公共作废(查看单击查看)
{
如果(clickedView==此.startAPICallButton)
{
Toast.makeText(这是“进行API调用…请稍候”,Toast.LENGTH_LONG.show();
this.makeAPICall();
}
else if(clickedView==this.RetrieveFromCache按钮)
{
Toast.makeText(这是“从缓存中检索数据!!!”,Toast.LENGTH\u LONG.show();
这个.retrieveStuffFromCache();
}
}
/*私有方法*/
私有void initializeComponents()
{
this.startAPICallButton=(Button)this.findViewById(R.id.start\u api\u call\u Button);
this.startAPICallButton.setOnClickListener(this);
this.retrieveFromCacheButton=(按钮)this.findViewById(R.id.retrieve\u cache\u按钮);
this.retrieveFromCacheButton.setOnClickListener(this);
}
私有void makeAPICall()
{
新线程(newrunnable())
{
@凌驾
公开募捐
{
尝试
{
//将json下载到设备上。
URL URL=新URL(CachingDemoActivity.URL);
URLConnection=url.openConnection();
//首先读取数据并将其存储在字节数组中。
//不要将此代码用于大型json文件
//只要它是一个json并且不是很长,这就可以正常工作!!!
InputStream inStream=connection.getInputStream();
ByteArrayOutputStream byteOutStream=新建ByteArrayOutputStream();
int readByte=0;
//从inputstream中逐个读取字节到缓冲区。
while(true)
{
readByte=inStream.read();
如果(readByte==-1)
{
打破
}
字节流外写(readByte);
}
byteOutStream.flush();
流内关闭();
byteOutStream.close();
byte[]response=byteOutStream.toByteArray();
//现在,响应字节数组是完整的双字节json格式。我们将把这些内容保存到文件中。
File cacheDir=CachingDemoActivity.this.getCacheDir();
File jsonFile=新文件(cacheDir,文件名);
FileOutputStream outStream=新的FileOutputStream(jsonFile);
//将整个数据写入文件
for(int i=0;ipackage com.android.test.CacheDemo;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class CachingDemoActivity extends Activity implements OnClickListener{
private static String URL="http://bhaskar1.cntdy.mobi/punjabkesari/appdetails/sectiondetails.json";
private static String FILE_NAME = "CachedResponse";
private Button startAPICallButton;
private Button retrieveFromCacheButton;
/* view lifecycle methods*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.initializeComponents();
}
/*overriden methods*/
public void onClick(View clickedView)
{
if(clickedView == this.startAPICallButton)
{
Toast.makeText(this, "Making the API call... Please wait", Toast.LENGTH_LONG).show();
this.makeAPICall();
}
else if(clickedView == this.retrieveFromCacheButton)
{
Toast.makeText(this, "Retrieving data from the cache!!!", Toast.LENGTH_LONG).show();
this.retrieveStuffFromCache();
}
}
/* private methods*/
private void initializeComponents()
{
this.startAPICallButton = (Button) this.findViewById(R.id.start_api_call_button);
this.startAPICallButton.setOnClickListener(this);
this.retrieveFromCacheButton = (Button) this.findViewById(R.id.retrieve_cache_button);
this.retrieveFromCacheButton.setOnClickListener(this);
}
private void makeAPICall()
{
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
//download the json onto the device.
URL url = new URL(CachingDemoActivity.URL);
URLConnection connection = url.openConnection();
//read the data and store it in a byte array first.
//dont use this code for big json file
//as long as its a json and not very long, this will work just fine!!!
InputStream inStream = connection.getInputStream();
ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
int readByte = 0;
//read the bytes one-by-one from the inputstream to the buffer.
while(true)
{
readByte = inStream.read();
if(readByte == -1)
{
break;
}
byteOutStream.write(readByte);
}
byteOutStream.flush();
inStream.close();
byteOutStream.close();
byte[] response = byteOutStream.toByteArray();
//now response byte array is the complete json in the biary form. We will save this stuff to file.
File cacheDir = CachingDemoActivity.this.getCacheDir();
File jsonFile = new File(cacheDir, FILE_NAME);
FileOutputStream outStream = new FileOutputStream(jsonFile);
//write the whole data into the file
for(int i = 0; i < response.length; i++)
{
outStream.write(response[i]);
}
android.util.Log.e("status - ","API call is complete!!");
//this should do the trick of saving all the stuff in the file with file name CachedResponse!!
//let see if we can retrieve the stuff!!!
}
catch (Exception e)
{
e.printStackTrace();
}
}
}).start();
}
private void retrieveStuffFromCache()
{
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
File jsonFile = new File(CachingDemoActivity.this.getCacheDir(), FILE_NAME);
FileInputStream fInStream = new FileInputStream(jsonFile);
ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
int readByte = 0;
while(true)
{
readByte = fInStream.read();
if(readByte == -1)
{
break;
}
byteOutStream.write(readByte);
}
fInStream.close();
byteOutStream.flush();
byteOutStream.close();
byte[] retrievedStringData = byteOutStream.toByteArray();
String originalJson = new String(retrievedStringData);
android.util.Log.e("json - ", originalJson);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}).start();
}
}