从Android编写csv文件。

时间:2018-09-07 17:47:25

标签: java android csv permissions

我一直试图从Android应用程序写入csv文件。但是由于某种原因,我仍然没有得到许可。我已授予该应用程序和仿真器的许可,但似乎找不到该文件,这使我相信未创建该文件。

这是活动。

package com.example.rimartinez.hollanderreborn;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.opencsv.CSVWriter;

import java.io.File;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;


public class problem extends Activity {
    Button submit;
    Switch mech_Switch, elect_Switch, clean_Switch;
    String lv_Mech[] = new String[] {"Mec1","Mec2","Mec3","Mec4","Mec5","Mec6","Mec7","Mec8","Mec9","Mec10","Mec11"};
    String lv_Elect[] = new String[] {"Elec1","Elec2","Elec3","Elec4","Elec5","Elec6","Elec7","Elec8","Elec9","Elec10","Elec11"};
    String lv_Clean[] = new String[] {"Clean1","Clean2","Clean3","Clean4","Clean5","Clean6","Clean7","Clean8","Clean9","Clean10","Clean11"};
    File file = new File("/sdcard/string_sample.csv");
    private static final String STRING_ARRAY_SAMPLE = "/sdcard/string_array_sample.csv";
    private int STORAGE_PERMISSION_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.problem_type);
        Intent i = getIntent();
        final String PMemail = i.getStringExtra("plantManageremail");
        final String MMEmail = i.getStringExtra("maintenanceManageremail");
        final String Ltype = i.getStringExtra("Ltype");
        final String PType = i.getStringExtra("Ptype");
        final String LNumber = i.getStringExtra("Lnumber");
        final ListView clean_list = (ListView) findViewById(R.id.lv_Cleaning);
        final ListView elect_list = (ListView) findViewById(R.id.lv_Electrical);
        final ListView mech_list = (ListView) findViewById(R.id.lv_Mechanical);
        clean_list.setVisibility(View.GONE);
        elect_list.setVisibility(View.GONE);
        mech_list.setVisibility(View.GONE);

        submit = (Button) findViewById(R.id.btn_submit);
        submit.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(problem.this,
                        Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(problem.this, "You have already granted this permission!",
                            Toast.LENGTH_SHORT).show();
                } else {
                    requestStoragePermission();
                }
                    // TODO Auto-generated method stub
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            GMailSender sender = new GMailSender(
                                    "email@gmail.com",
                                    "put yourpassword");
                            sender.sendMail("Production line reported down!", " "+Ltype+" number "+LNumber+" has been reported down due to an "+PType+" related problem",
                                    "darthvadersfavorite@gmail.com",
                                    ""+PMemail+","+ MMEmail);
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
                        }
                        try {
                            try (
                                    Writer writer = Files.newBufferedWriter(Paths.get(STRING_ARRAY_SAMPLE));

                                    CSVWriter csvWriter = new CSVWriter(writer,
                                            CSVWriter.DEFAULT_SEPARATOR,
                                            CSVWriter.NO_QUOTE_CHARACTER,
                                            CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                                            CSVWriter.DEFAULT_LINE_END);
                            )
                            {
                                String[] headerRecord = {"Time", "Line Number", "Line Type", "Problem Type"};
                                csvWriter.writeNext(headerRecord);

                                csvWriter.writeNext(new String[]{"Sundar Pichai",LNumber, Ltype, PType});
                                csvWriter.writeNext(new String[]{"Satya Nadella", "satya.nadella@outlook.com", "+1-1111111112", "India"});
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }

        });

        mech_Switch = (Switch) findViewById(R.id.switch_Mechanical);
        elect_Switch = (Switch) findViewById(R.id.switch_Electrical);
        clean_Switch = (Switch) findViewById(R.id.switch_Cleaning);

        //Mechanical Switch
        mech_Switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                elect_Switch.setChecked(false);
                clean_Switch.setChecked(false);
                mech_list.setVisibility(View.VISIBLE);
                clean_list.setVisibility(View.GONE);
                elect_list.setVisibility(View.GONE);

            }
        });

        //Electrical Switch
        elect_Switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                clean_Switch.setChecked(false);
                mech_Switch.setChecked(false);
                elect_list.setVisibility(View.VISIBLE);
                clean_list.setVisibility(View.GONE);
                mech_list.setVisibility(View.GONE);

            }
        });

        //Cleaning Switch
        clean_Switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mech_Switch.setChecked(false);
                elect_Switch.setChecked(false);
                clean_list.setVisibility(View.VISIBLE);
                elect_list.setVisibility(View.GONE);
                mech_list.setVisibility(View.GONE);
            }
        });

        //Mechanical ListView
            ArrayAdapter<String> mech_adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, lv_Mech);
            mech_list.setAdapter(mech_adapter);
            mech_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(problem.this, lv_Mech[position], Toast.LENGTH_SHORT).show();
                }
            });

        //Electrical ListView
            ArrayAdapter<String> elect_adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, lv_Elect);
            elect_list.setAdapter(elect_adapter);
            elect_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(problem.this, lv_Elect[position], Toast.LENGTH_SHORT).show();
                }
            });

        //Cleaning ListView
        ArrayAdapter<String> clean_adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, lv_Clean);
            clean_list.setAdapter(clean_adapter);
            clean_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(problem.this, lv_Clean[position], Toast.LENGTH_SHORT).show();
                }
            });
    }

    private void requestStoragePermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)) {

            new AlertDialog.Builder(this)
                    .setTitle("Permission needed")
                    .setMessage("This permission is needed because of this and that")
                    .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(problem.this,
                                    new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
                        }
                    })
                    .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create().show();

        } else {
            ActivityCompat.requestPermissions(this,
                    new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == STORAGE_PERMISSION_CODE)  {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

有一堆东西不是代码的一部分,但我只是想确保所有东西都在里面以避免混淆。

这是清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.rimartinez.hollanderreborn">

    <uses-permission android:name="android.permission.INTERNET">

    </uses-permission>

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".login">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity"></activity>
        <activity android:name=".line_type_and_number_class"></activity>
        <activity android:name=".problem"></activity>


    </application>

</manifest>

运行程序后找不到文件。任何帮助将不胜感激。不好意思的代码很抱歉,我是新来的。

谢谢

0 个答案:

没有答案