保存JSON文件到内存

人气:1,262 发布:2022-09-10 标签: android internal entity save

问题描述

嘿家伙和女孩我有这个code,应该下载一个JSON对象,然后将其保存到内存中,我不断收到困在这里

hey there guys and girls i have this code that should download a json object and then save it to internal memory, i keep getting stuck here

    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误差修改(是); Eclipse询问我将其更改为int,什么将是code的最佳方式来自行

i keep getting erros on writer.write(is); eclipse asks me to change it to an int, what would be the best way to code from the line

entity = response.getEntity();

???

下面是我的全部code

here is my full code

    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    
}

希望你能帮助我这个,被这么长时间得到它的工作!

hope you can help me with this, been taking so long to get it to work!!!

增加了额外的code,从鲍里斯......这是哪里我把code?

added extra code from boris... is this where i put the code ?

    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();
        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();
        Integer responseInteger = Integer.valueOf(entityString);
    }catch(Exception e) {
         Log.e("log_tag", "Error in http connection "+e.toString());
    }

如果这是我得到的读取错误

if it is i get an error on read

推荐答案

这是奇怪的情况,我编辑我的previous的答案来解决你的这个问题。但是:另外一个问题是问,所以在这里不用我 previous答案的这一部分:

This is weird case, I edited my previous answer to fix this problem of yours. However: another question was asked, so here goes this portion of my previous answer:

关于你的错误 - 你想直接投回应的实体为整数。这总是会失败,因为Integer是不是 HttpEntity 超。你需要阅读的实体的内容在字符串,然后解析字符串的内容为整数:

About the error you get - you are trying to cast the entity of the response directly to an Integer. This will always fail, because Integer is not superclass of HttpEntity. You need to read the contents of the entity in a String and then parse the contents of the string to integer:

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 则需要字符串价值,而不是整数。因此,我建议你使用 entityString

this is not highly optimized, but does the job. From then on you can use the responseInteger value as you like . However if you want to do writer.write you will need String value, not Integer. Thus I recommend you to use entityString.

127