将字符串保存到内部存储器,然后显示它

3

嘿,我有一个代码,当你点击第一个按钮时,它应该从SQL服务器保存文件,然后在按下第二个按钮时显示文件。第一个按钮似乎有效,但第二个按钮会导致它崩溃。这是我的代码:

    public class MainActivity extends Activity {
/** Called when the activity is first created. */

String result = "";
InputStream is = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    Button saveFile = (Button) findViewById(R.id.downloadBtn);
    saveFile.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            returnJson();

        }
    });


    Button showFile = (Button) findViewById(R.id.showBtn);
    showFile.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            TextView showText = (TextView) findViewById(R.id.showView);


        String FILENAME = "Story_One";
        String showStoryNames = "";

        FileInputStream fis = null;
        try {
            fis = openFileInput(FILENAME);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            fis.read(showStoryNames.getBytes());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            fis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }




        }
    });

    //end of onCreate
}

public void returnJson(){


    try{
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://10.0.2.2/textures_story_list.php");

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

    }catch(Exception e) {
        //one.setText("error3");
    }

    try{


        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);                      
        StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();

    }catch(Exception e) {
        //one.setText("error2");            
        }

    try{
        JSONArray jArray = new JSONArray(result);
        String storyNames = "";
        for(int i = 0;i<jArray.length();i++){
                storyNames += jArray.getJSONObject(i).getString("story_name") + "\n"; 

        String FILENAME = "Story_One";
        String string = storyNames;

        FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
        fos.write(string.getBytes());
        fos.close();
        }
        }
    catch(JSONException e) {
        //one.setText("error1");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
        return;

//end of returnJson()   
}



//end of method body
}

我希望你能帮我确认保存到内部存储的代码是否正确,以及为什么第二个按钮会导致崩溃问题。

好的,这是我正在使用的代码:

    public void returnJson(){

    TextView one = (TextView) findViewById(R.id.textView1);

    try{
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://10.0.2.2/story_one.php");

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

    }catch(Exception e) {
        one.setText("error3");
    }

    try{


        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);                      
        StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();

    }catch(Exception e) {
        one.setText("error2");          
        }

    try{
        JSONArray jArray = new JSONArray(result);
        String storyNames = "";
        for(int i = 0;i<jArray.length();i++){
                storyNames += jArray.getJSONObject(i).getString("story_name") + "\n"; 
        }
        one.setText(storyNames);
    }
    catch(JSONException e) {
        one.setText("error1");
    }
        return;


//end of returnJson()   
}

有人能告诉我哪些代码不需要,哪些是需要的,以及将它放在哪里才能保存story_one.php的结果吗?是否可以将其保留为json,在story_one文件使用时再进行转换?


当程序崩溃时,请发布您的错误日志。 - Tofeeq Ahmad
什么是错误/堆栈跟踪? - dor506
如何发布错误日志? - daniel
如果您只想存储单个字符串,可以使用SharedPreferences。 - KK_07k11A0585
2个回答

5
尝试使用以下代码读取之前保存的文件。
try{
    FileInputStream fIn = openFileInput("filename.txt");
    InputStreamReader isr = new InputStreamReader(fIn);
    char[] inputBuffer = new char[len];
    //len is the length of that saved string in the file

    isr.read(inputBuffer);

    String readString = new String(inputBuffer);
 }catch(IOException e){

    }

谢谢Rakshi,这个方法也可以用于我从story_one.php获取的JSON数据,而无需进行转换吗? - daniel
那么,要将其从JSON转换出来,我应该使用readString,而要转换的字符串是什么? - daniel
我提了一个新问题,你能看一下吗?上次你真的帮了我大忙。链接是http://stackoverflow.com/questions/9370701/how-to-save-a-file-type-as-json-on-android-to-internal-memory。 - daniel

4
尝试以下代码将字符串写入文件。
try{

String text = "String that goes in the file"
FileOutputStream fOut = openFileOutput("filename.txt",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(text);
int len = text.length();
osw.flush();
osw.close();
}catch(IOException ioe){
} 

如果您的代码可以成功保存文件,那么我该如何显示已保存的文件呢? - daniel
1
你可以在字符串中使用一些分隔符并将其保存到文件中,稍后可以拆分字符串以填充列表。希望这能帮助到你。 - Rakshi
我添加了我用来从MySQL获取外部数据的代码。 - daniel
稍后在应用程序中,当用户选择阅读故事时,需要将story_one填充到TextView中。因此,我的应用程序用户可以从MySQL数据库保存故事,选择将其保存到他们的手机或SD卡中,然后他们可以选择要阅读哪个故事。 - daniel
为什么你要使用文件来存储手机数据,而不是使用SQLite数据库呢? - Rakshi
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接