简体   繁体   中英

Can't create File in Internal Storage

Chasing Google Android Trainings I tried to create a File in Internal storage and modify that.

but there is an unknown problem and I can't debug it.

Below I have copied my mainActivity class which contains all code I have written for the pupose, but I really can't debug it!!! I just can see nothing in TextView !!

public class MyActivity extends Activity {

final static String fileName = "myFile.txt";
File file;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initializeFile();
    TextView tv = (TextView) findViewById(R.id.text_view);
    try {
        tv.setText(readFile());
    } catch (IOException e) {
        e.printStackTrace();
    }
    setContentView(R.layout.main);
}


public void initializeFile(){
    try {
        file = new File(getFilesDir() , fileName);
        if(!file.exists()){
            Log.d("BUG","No Files !!");
        }
        FileOutputStream out = openFileOutput(fileName , MODE_PRIVATE);
        out.write("My text".getBytes());
        out.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

public String readFile() throws IOException {
    String s = "";
    Scanner scan = new Scanner(file);
    if (!file.exists())
    {
        Log.d("BUG","NO File(reading)");
    }
    while(scan.hasNext()){
        s += scan.nextLine();
    }
    return s;
}

You should call setContentView(R.layout.main) before you try to obtain TextView tv. Elsewhere there is NPE, cause you main view is not inflated and there is no any view with id R.id.text_view. Everything else works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM