简体   繁体   English

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

[英]Write to a text file in one activity and read into ListView in another?

So I'm relatively new to Android Studio. 因此,我对Android Studio还是比较陌生。 I'm just working on a small QR Code scanner. 我正在研究小型QR码扫描仪。 Basically, what I'm trying to do is add whatever the QR code result is to a text file then be able to load that text file into in another activity. 基本上,我想做的是将任何QR码结果添加到文本文件中,然后能够将该文本文件加载到另一个活动中。

I have already added the necessary permissions to the AndroidManifest.xml 我已经向AndroidManifest.xml添加了必要的权限

<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

This is MainActivity.java 这是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();
    }
}

The file is not writing for some reason. 由于某种原因该文件未写入。 It doesn't appear in the phone's storage. 它不会出现在手机的存储器中。 Anyway, here's ResultsActivity.java 无论如何,这是ResultsActivity.java

ResultsActivity.java (Meant to display the scan history) 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();
        }
    }
}

Am I reading the Text File into the ListView properly, by the way? 顺便说一句,我是否将文本文件正确读入ListView? Just wondering. 就是想。

But anyway, my main question is writing into the internal storage and that doesn't seem to be working. 但是无论如何,我的主要问题是写入内部存储,但这似乎没有用。 Any ideas as to what is going on? 有什么想法吗?

First, you shouldn't use such approach - to share simple string between components you can use many inmemory things, such as intents, services, broadcasts and so on. 首先,您不应该使用这种方法-在组件之间共享简单的字符串,您可以使用许多内存事物,例如意图,服务,广播等。 It is simpler to use the SharedPreferences at least. 至少使用SharedPreferences更简单。

Regarding your questions, the mistake is in this two lines of snippets: 关于您的问题,错误在于以下两行代码片段:

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

At this line, you are opening stream to write data into private file (such files are stored within internal application folder). 在这一行,您正在打开流以将数据写入私有文件(此类文件存储在内部应用程序文件夹中)。

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

And here you try to find the file within external storage (it is just a different folder) 在这里,您尝试在外部存储中查找文件(只是一个不同的文件夹)

So, to find your file, you can use corresponding method openFileInput 因此,要查找文件,可以使用相应的方法openFileInput

Hope, it'll help. 希望会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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