0

所以这是我的代码。发生的情况是,当我第一次启动应用程序时,我尝试选择一个文件,结果代码为 0。第二次单击按钮打开资源管理器时,我选择了文件,结果代码为 -1,所以它成功了打开文件。知道第一次会发生什么吗?我似乎无法理解为什么它给我代码 0?多谢你们。PS 这是糟糕的编码,但我只是想了解 Android 中的文件打开过程。谢谢。

public class MainActivity extends Activity implements OnClickListener {

final int ACTIVITY_CHOOSE_FILE = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button my_button = (Button) findViewById(R.id.activity);
    my_button.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("file/");
        startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.v("onActivityResult","requestCode is: " + requestCode + " resultCode" + resultCode);
    if ((requestCode == ACTIVITY_CHOOSE_FILE) && (resultCode == RESULT_OK)) {
        Log.v("onActivityResult","Passes through if statement");
        //String fileSelected = data.getStringExtra("fileSelected");

        String FilePath = data.getData().getPath();
        TextView my_text = (TextView) findViewById(R.id.textView1);
        my_text.setText(FilePath);
        StringBuilder text = null;

        try{
            Scanner input = new Scanner(FilePath);
            //File dir = Environment.getExternalStorageDirectory();
            //File yourFile = new File(dir, FilePath);

            //Read text from file
            text = new StringBuilder();

            try {
                BufferedReader br = new BufferedReader(new FileReader(FilePath));
                String line;

                while ((line = br.readLine()) != null) {
                    text.append(line);
                    text.append('\n');
                }
            }
            catch (IOException e) {
                //You'll need to add proper error handling here
            }
        }catch(Exception e){
            Log.v("file not opened","THE FILE WAS NOT OPENED");
        }

        my_text.setText(text);
    }                   
}
}
4

1 回答 1

0

此类错误是第 3 方错误,请尝试在另一台设备上使用该应用程序或使用模拟器,看看它是如何进行的。

于 2013-01-26T08:27:59.767 回答