正确使用openFileInput

时间:2015-03-04 05:28:11

标签: android file android-fragments

我是Android Development的新手,我想创建一个将数据存储在文件中的App,然后从文件中读取数据。为此,我创建了2个选项卡。 Tab1显示输入数据的表单。 Tab2显示保存的数据。

FragmentTab1.java

package com.adhish.pagertabstriptutorial;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

public class FragmentTab1 extends Fragment implements View.OnClickListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Get the view from fragmenttab1.xml
        //first inflate the view.
        View v  = inflater.inflate(R.layout.fragmenttab1, container, false);

        //then access the elements

        v.findViewById(R.id.button1).setOnClickListener(this);

        //then return the view
        return v;

    }

    @Override
    public void onClick(View view)
    {
        if(view == getView().findViewById(R.id.button1))
        {
            //Call all the elements of this Fragment here becuase they are accessible easily through
            //getView(); method. Use the getText(); method to get the Text and toString(); to convert
            //it.
            String name = ((EditText)getView().findViewById(R.id.name)).getText().toString();
            String email = ((EditText)getView().findViewById(R.id.email)).getText().toString();

            if(name.isEmpty() || email.isEmpty())
            {
                Toast.makeText(getActivity(), "Cannot store empty values !", Toast.LENGTH_SHORT).show();
            }
            else
            {
                try
                {
                    FileOutputStream fOut = getActivity().openFileOutput("sample_details.txt", Context.MODE_MULTI_PROCESS);
                    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fOut);

                    outputStreamWriter.write(name + " " + email + ";");
                    Log.e("String Concat Done", "Concatenation of the Strings is done to write in the File. Write Success.");
                    outputStreamWriter.flush();
                    Log.e("Flush","Flush Success");
                    outputStreamWriter.close();
                    fOut.close();
                    Log.e("Stream Closed","Both Streams are flushed and closed");

                    Toast.makeText(getActivity(), "Submitted", Toast.LENGTH_SHORT).show();
                }
                catch (Exception e)
                {
                    Toast.makeText(getActivity(), "FAILED !", Toast.LENGTH_SHORT).show();
                    Log.e("Error in File Write",e.toString());
                }
            }
        }
    }
}

FragmentTab2.java

package com.adhish.pagertabstriptutorial;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class FragmentTab2 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Get the view from fragmenttab2.xml
        View v = inflater.inflate(R.layout.fragmenttab2, container, false);

        TextView txt = (TextView)v.findViewById(R.id.optext);

        try
        {
            FileInputStream fIn = getActivity().openFileInput("sample_details.txt");
            InputStreamReader in = new InputStreamReader(fIn);
            BufferedReader bufferedReader = new BufferedReader(in);
            StringBuilder sb = new StringBuilder();

            String line =  null;
            String str = null;

            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line).append("\n");
            }

            txt.setText(line);

            bufferedReader.close();
            in.close();
        }
        catch (Exception e)
        {
            Log.e("File not found.",e.toString());
        }

        return v;
    }

}

文本视图中只显示一行。

请帮我详细说明,因为我对Android很新。 如果存在,请详细说明更好的方法。

我在这里附上我的用户界面: Input Fragment

Output Fragment

感谢。

1 个答案:

答案 0 :(得分:0)

首先使用此代码编辑您的try块

FileOutputStream fOut = openFileOutput(
                "sample_details.txt", Context.MODE_MULTI_PROCESS);
        OutputStreamWriter outputStreamWriter = new       OutputStreamWriter(fOut);
        JSONObject jobj=new JSONObject();
        jobj.put("Name", "name");
        jobj.put("Email", "email");
        outputStreamWriter.write(jobj.toString());
        Log.e("String Concat Done",
                "Concatenation of the Strings is done to write in the File.   Write Success.");
        outputStreamWriter.flush();
        Log.e("Flush", "Flush Success");
        outputStreamWriter.close();
        fOut.close();
        Log.e("Stream Closed", "Both Streams are flushed and closed");

在第二个标签(片段)中,首先获取(读取)字符串:

public static String convertStreamToString(InputStream is) throws Exception
 {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
  sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}

public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();        
return ret;
}

您将通过调用getStringFromFile(filepath)方法获取(读取)字符串 该字符串是JSON格式,因此您必须将其解析为:

 public void Readvalue(String jsonvalue)
 {
   try {
    JSONObject jobj=new JSONObject(jsonvalue);
    String name=jobj.getString("Name");
    String email=jobj.getString("Email");
    System.out.println("Name is : "+name   +"  Email is : "+email);
 } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
 }
 }