简体   繁体   中英

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

So I'm relatively new to Android Studio. I'm just working on a small QR Code scanner. 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.

I have already added the necessary permissions to the AndroidManifest.xml

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

This is 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 (Meant to display the scan history)

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? 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.

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

Hope, it'll help.

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