开发者

android FileInputStream crashes

开发者 https://www.devze.com 2023-03-21 06:11 出处:网络
I am an amateur programmer developing for android. I am just trying get the basics down right now, but I am having an error and I don\'t know why.

I am an amateur programmer developing for android. I am just trying get the basics down right now, but I am having an error and I don't know why.

I am creating a activity that has a save and a load button, which using the fileOutputStream and fileInputStream to achieve this task.

The problem I am having is if I hit the load b开发者_开发知识库utton the first time I use the activity, my application crashes. Can anyone help me with how to skip the load section if the file hasn't been created yet? What should I use within my if statement.

Thanks a ton, here is my code:

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class InternalData extends Activity implements OnClickListener {

    String FILENAME = "InternalString";
    EditText sharedData;
    TextView dataResults;
    FileOutputStream fos;
    String d;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sharedpreferences);
        Button save = (Button) findViewById(R.id.bSave);
        Button load = (Button) findViewById(R.id.bLoad);
        sharedData = (EditText) findViewById(R.id.etSharedPrefs);
        dataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
        save.setOnClickListener(this);
        load.setOnClickListener(this);
        try {
            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.bSave:
            d = sharedData.getText().toString();

            try {

                fos.write(d.getBytes());
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            break;
        case R.id.bLoad:
            FileInputStream fis = null;
            try {
                if (openFileInput(FILENAME) != null){
                fis = openFileInput(FILENAME);
                byte[] data = new byte[fis.available()];
                while(fis.read(data) != -1){
                    String readData = new String(data);
                    dataResults.setText(readData);
                }}
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            break;
        }
    }
}

Thanks for the help Lukas, I have updated my code, and I was wondering if you could look it over to make sure I am using the AsyncTask properly. Thanks again!

public class InternalData extends Activity implements OnClickListener {

String FILENAME = "InternalString";
EditText sharedData;
TextView dataResults;
FileOutputStream fos;
String d;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sharedpreferences);
    Button save = (Button) findViewById(R.id.bSave);
    Button load = (Button) findViewById(R.id.bLoad);
    sharedData = (EditText) findViewById(R.id.etSharedPrefs);
    dataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
    save.setOnClickListener(this);
    load.setOnClickListener(this);

}

public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.bSave:
        d = sharedData.getText().toString();

        try {
            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
            fos.write(d.getBytes());
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        break;
    case R.id.bLoad:

            AsyncTask<String, Integer, String> dat = new loadInternalData().execute(FILENAME);  

        break;
    }
}

public class loadInternalData extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        FileInputStream fis = null;
        String collected = null;
        try {
            fis = openFileInput(FILENAME);
            byte[] data = new byte[fis.available()];
            while (fis.read(data) != -1){
                collected = new String(data);

            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                fis.close();
                return collected;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return collected;
    }
     @Override
     protected void onPostExecute( String result ) 
     {
             super.onPostExecute(result);
             Log.i( "InteralStorage", "onPostExecute(): " + result );
             dataResults.setText( result );

     }
}

}


You are calling openFileInput twice. Just call it once.

Instead of this

if (openFileInput(FILENAME) != null){
    fis = openFileInput(FILENAME);
}

Do this:

fis = openFileInput(FILENAME);
if (fis != null) {
    // Read file
}


If you execute something on the UI-Thread, it shouldn't take longer then 5 seconds or an ANR will be triggered.

If you want to do something that might take longer then those 5 seconds, you'll want to do it in a Service or an AsyncTask.

Also, if your App gets force closed and you don't know why, you should always have a look at the LogCat output which can be shown in Eclipse. Also, you should include it with every question you ask here (about Android).

0

精彩评论

暂无评论...
验证码 换一张
取 消