在一个活动中写入文本文件并在另一个活动中读入ListView?

时间:2016-06-08 18:55:38

标签: java android listview

所以我对Android Studio来说相对较新。我正在使用小型QR码扫描仪。基本上,我尝试做的是将QR码结果添加到文本文件中,然后将该文本文件加载到另一个活动中。

我已经为AndroidManifest.xml

添加了必要的权限
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

这是 MainActivity.java

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.camera2.CameraManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.zxing.Result;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import me.dm7.barcodescanner.zxing.ZXingScannerView;

public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
    private ZXingScannerView mScannerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mScannerView = new ZXingScannerView(this);   // Programmatically initialize the scanner view
        setContentView(mScannerView);

        mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
        mScannerView.startCamera();         // Start camera
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int selectedId = item.getItemId();

        switch (selectedId)
        {
            case R.id.mniHistory:
                startActivity(new Intent(MainActivity.this, ResultsActivity.class));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();           // Stop camera on pause
    }

    @Override
    public void handleResult(final Result rawResult) {
        // Do something with the result here

        Log.e("handler", rawResult.getText()); // Prints scan results
        Log.e("handler", rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode)

        // Alert Box (the one that asks if you want to send)
        AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
        builder1.setTitle("Scan Result");
        builder1.setMessage(rawResult.getText() + "\n" + "Would you like to send this?");
        builder1.setCancelable(true);

        builder1.setPositiveButton(
                "Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        // ADD SCAN TO TEXT FILE
                        try {
                            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("History.txt", Context.MODE_PRIVATE));
                            outputStreamWriter.write(rawResult.getText());
                            outputStreamWriter.close();
                        } catch (IOException e) {
                            Log.e("Exception", "File write failed: " + e.toString());
                        }
                        // DONE ADDING TO HISTORY
                        dialog.cancel();
                    }
                });

        builder1.setNegativeButton(
                "No",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                        mScannerView.resumeCameraPreview(MainActivity.this);
                    }
                });

        AlertDialog alert11 = builder1.create();
        alert11.show();
    }
}

由于某种原因,文件没有写入。它不会出现在手机的存储空间中。 无论如何,这里是ResultsActivity.java

ResultsActivity.java(显示扫描历史记录)

import android.content.Intent;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class ResultsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_results);
        ArrayList<String> completeList = new ArrayList<String>();

        ListView listView1;

        listView1 = (ListView) findViewById(R.id.ResultsListView);

        try {
            String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/History.txt";
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "Cp1252"), 100);

            String line;
            // ArrayList<String> lines = new ArrayList<String>();
            while ((line = br.readLine()) != null) {
                completeList.add(line);
            }

            br.close();

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, completeList);


            listView1.setAdapter(adapter);


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

顺便说一句,我是否正确地将文本文件读入ListView?就是想。

但无论如何,我的主要问题是写入内部存储,但似乎并没有起作用。关于发生了什么的任何想法?

1 个答案:

答案 0 :(得分:0)

首先,您不应该使用这种方法 - 在组件之间共享简单的字符串,您可以使用许多内存,例如意图,服务,广播等。至少使用SharedPreferences更简单。

关于你的问题,错误在于这两行片段:

OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("History.txt", Context.MODE_PRIVATE));

在此行,您打开流以将数据写入私有文件(此类文件存储在内部应用程序文件夹中)。

String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/History.txt";

在这里,您尝试在外部存储中找到该文件(它只是一个不同的文件夹)

因此,要查找文件,您可以使用相应的方法openFileInput

希望,这会有所帮助。