简体   繁体   English

在Android上写入.txt文件-什么都没发生

[英]Writing .txt file on android - nothing happens

I have an android app which is recording audio and outputting it withe the name audiorecorder to the local storage on the phone. 我有一个android应用程序,它正在录制音频并将其与名称audiorecorder一起输出到手机上的本地存储中。 Now i would like store a .txt file as well in same directory. 现在我想将.txt文件也存储在同一目录中。

I have tried several methods from stack overflow, the app doesn't complain but does not store the .txt as it should. 我从堆栈溢出尝试了几种方法,该应用程序没有抱怨,但没有按原样存储.txt。 I can't figure out why. 我不知道为什么。

The methods of interest is: CreateTxt and generateNote. 感兴趣的方法是:CreateTxt和generateNote。 These are the ones that doesn't do what they are supposed to. 这些是没有按预期执行的操作。

These methods are used within the startR.setOnClickListener method. 这些方法在startR.setOnClickListener方法中使用。

Can anybody see why? 有人知道为什么吗? Thank you in advance. 先感谢您。

package xxxx;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import static android.provider.AlarmClock.EXTRA_MESSAGE;

public class DataCollectionActivity extends AppCompatActivity {
    private MediaPlayer mediaPLayer;
    private MediaRecorder recorder;
    private String OUTPUT_FILE;

    public Button GoToUserAcc;
    public Button GoToLogin;
    public Button GoToTest;

    // Permission Variables
    private static final String LOG_TAG = "AudioRecordTest";
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
    private static String mFileName = null;
    private boolean permissionToRecordAccepted = false;
    private String [] permissions = 
    {Manifest.permission.RECORD_AUDIO, 
    Manifest.permission.WRITE_EXTERNAL_STORAGE, 
    Manifest.permission.INTERNET};

    private static final int 
    REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION = 200;
    private boolean permissionToWriteExternalStoragedAccepted = 
    false;

    private static final int REQUEST_INTERNET_PERMISSION = 200;
    private boolean permissionToUseInternetAccepted = false;

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


        //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);

        Button startR = (Button) findViewById(R.id.Bstart);
        Button stopR = (Button) findViewById(R.id.Bstop);
        Button playRecording = (Button) findViewById(R.id.playBtn);
        Button stopPlaying = (Button) findViewById(R.id.stopBtn);
        final TextView statusTV;
        statusTV = (TextView) findViewById(R.id.tStatus);

        OUTPUT_FILE= Environment.getExternalStorageDirectory().
        getAbsolutePath()+"/audiorecorder.3gpp";


        ActivityCompat.requestPermissions(this, permissions, 
        REQUEST_RECORD_AUDIO_PERMISSION);

        /*------START recording BUTTON------*/

        startR.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                final TextView stv=statusTV;
                try {
                    beginRecording();
                    stv.setText("Recording");
                    //CreateTxt();
                    generateNote("MLdata", "sBody");
                    stv.setText("Created txt");
                } catch (Exception e) {
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw));
                    String exceptionAsString = sw.toString();
                    stv.setText("Error");
                }
            }
        });

        /*------STOP BUTTON------*/

        stopR.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                final TextView stv=statusTV;
                try {
                    stopRecording();
                    stv.setText("Stopped");
                } catch (Exception e) {
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw));
                    String exceptionAsString = sw.toString();
                    statusTV.setText("Error");
                    Log.d("here","dd",e);
                }
            }
        });


    }

    private void stopPlayback() throws Exception{
        if(mediaPLayer != null)
            mediaPLayer.stop();
    }
    private void playRecording() throws IOException {
        ditchMediaPLayer();
        mediaPLayer = new MediaPlayer();
        mediaPLayer.setDataSource(OUTPUT_FILE);
        mediaPLayer.prepare();
        mediaPLayer.start();

    }

    private void ditchMediaPLayer() {
        if (mediaPLayer != null) {
            try{
                mediaPLayer.release();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void stopRecording() {
        if(recorder != null)
            recorder.stop();
    }
    private void beginRecording() throws Exception{
        ditchMediaRecorder();
        File outFile = new File(OUTPUT_FILE);
        //DataCollectionActivity dca = new DataCollectionActivity();
        //dca.CreateTxt();
        if (outFile.exists()) {
            outFile.delete();
        }

        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);

        recorder.setOutputFormat(MediaRecorder.
        OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(OUTPUT_FILE);

        /*API constraints
        Container   WAV
        Encoding    PCM
        Rate    16K
        Sample Format   16 bit    OK
        Channels    Mono         OK
         */
        recorder.setAudioSamplingRate(16);
        //channel 1 equals mono, 2 eqals stereo
        recorder.setAudioChannels(1);

        recorder.prepare();
        recorder.start();
    }

    private void ditchMediaRecorder() {
        if(recorder != null)
            recorder.release();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        if (item.getItemId() == R.id.action_setting){
            Toast.makeText(DataCollectionActivity.this, "You have 
      clicked on setting action menu", Toast.LENGTH_SHORT).show();
        }

        if (item.getItemId() == R.id.action_about_us){
            Toast.makeText(DataCollectionActivity.this, "You have 
       clicked on about us action menu", Toast.LENGTH_SHORT).show();
            goToUserAccount();
        }

        return super.onOptionsItemSelected(item);
    }

    // Requesting permission to RECORD_AUDIO
    //fra android.com


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull 
    String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, 
    grantResults);

        switch (requestCode){
            case REQUEST_RECORD_AUDIO_PERMISSION:
                permissionToRecordAccepted  = grantResults[0] == 
     PackageManager.PERMISSION_GRANTED;
                break;
        }
        if (!permissionToRecordAccepted ) finish();

        //---ny permission ---
        super.onRequestPermissionsResult(requestCode, permissions, 
        grantResults);
        switch (requestCode){
            case REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION:
                permissionToWriteExternalStoragedAccepted  = 
        grantResults[0] == PackageManager.PERMISSION_GRANTED;
                break;
        }
        if (!permissionToRecordAccepted ) finish();

        //---ny permission ---
        super.onRequestPermissionsResult(requestCode, permissions, 
         grantResults);
        switch (requestCode){
            case REQUEST_INTERNET_PERMISSION:
                permissionToUseInternetAccepted  = grantResults[0] == 
         PackageManager.PERMISSION_GRANTED;
                break;
        }
        if (!permissionToRecordAccepted ) finish();

    }

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

    /** Opens up new activity */
    //Vedrører tollbaren som ligenu ikke bliver brugt /virker ikke.
    public void goToUserAccount() {
        Intent intent = new Intent(this, UserAccountActivity.class);
        EditText editText = (EditText) 
    findViewById(R.id.action_about_us);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }

    //Metode som laver en writer.
    public void CreateTxt() throws  IOException {
        //concerning txt file
        int id = 0;
        String typeId = "S";

        EditText db = (EditText) findViewById(R.id.dbNoiseText);
        String dbString = db.getText().toString();

        EditText numPar = (EditText) 
        findViewById(R.id.participatorsText);
        String npar = numPar.getText().toString();

        EditText conversationBool = (EditText) 
        findViewById(R.id.CoverationText);
        String cBool = conversationBool.getText().toString();

        File f = new File(Environment.getExternalStorageDirectory().
        getAbsolutePath()+"dataForML.txt");
        try {
            System.out.print("enters try in createtxt");
            PrintWriter writer = new PrintWriter(f, "UTF-8");
            writer.println(dbString + ", ");
            writer.println(npar + ", ");
            writer.println(cBool + ", ");
            writer.println(typeId + id + ", ");
            writer.println(Environment.getExternalStorageDirectory().
            getAbsolutePath()+"/dataForML.txt");
            //Her skal den skrive binary. Metoden ligger i asrRequest
            writer.println("Path to Acceleroeter CSV file ");
            writer.println("\n");
            writer.println();
            writer.close();
            id++;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //OUTPUT_FILE= Environment.getExternalStorageDirectory().
    getAbsolutePath()+"/audiorecorder.3gpp";

    //generateNoteOnSD("MLdata", "sBody");
    public void generateNote(String sFileName, String sBody) {
        try {
            File root = new 
            File(Environment.getExternalStorageDirectory().
            getAbsolutePath(), "NotesML");
            if (!root.exists()) {
                root.mkdirs();
            }
            File gpxfile = new File(root, sFileName);
            FileWriter writer = new FileWriter(gpxfile);
            writer.append(sBody);
            writer.flush();
            writer.close();
            //Toast.makeText(context, "Saved", 
            Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void thirdTry(){
        String FILENAME = "hello_file";
        String string = "hello world!";
        try{
            FileOutputStream fos = openFileOutput(FILENAME, 
            Context.MODE_PRIVATE);
            fos.write(string.getBytes());
            fos.close();
        } catch (IOException e){
            e.printStackTrace();
        }

    }
}


layout xml comes here
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:layout_marginBottom="10dp"
    android:layout_marginEnd="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="10dp"
    android:orientation="vertical"
    android:weightSum="1">

    <EditText
        android:id="@+id/dbNoiseText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="db noise"
        android:inputType="textPersonName"
        android:textAlignment="center"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/participatorsText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="# participators"
        android:inputType="textPersonName"
        android:textAlignment="center"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/CoverationText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Conversation? Y/N"
        android:inputType="textPersonName"
        android:textAlignment="center" />

    <Button
        android:id="@+id/Bstart"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_marginBottom="10dp"
        android:layout_marginEnd="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:text="Start Recording" />

    <Button
        android:id="@+id/Bstop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_marginBottom="10dp"
        android:layout_marginEnd="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:text="Stop recording" />

    <TextView
        android:id="@+id/tStatus"
        android:layout_width="354dp"
        android:layout_height="42dp"
        android:text="status"
        android:textAlignment="center"
        android:textSize="24sp" />

</LinearLayout>

Manifest comes here
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="dk.itu.percomp17.jumanji">

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

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

    <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=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

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

        <activity android:name=".UserAccountActivity" />
        <activity android:name=".RegisterActivity" />
        <activity android:name=".LoginActivity"/>
        <activity android:name=".DataCollectionActivity"/>
        <activity android:name=".CallingjsActivity">
        </activity>
    </application>

</manifest>

I found out. 我发现。 Following method solved it. 下面的方法解决了它。

// Once a file has been created, use this method to publicize
//the file as it can be seen !!
// But be sure to add "Context context;" outside of the method.
// Plus, remember to add "context = getApplicationContext ();" in the 
//onCreate () method.

public void scanFile(String path) {

    MediaScannerConnection.scanFile(context,
            new String[] { path }, null,
            new MediaScannerConnection.OnScanCompletedListener() {

                public void onScanCompleted(String path, Uri uri) {
                    Log.i("TAG", "Finished scanning " + path);
                }
            });
}

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

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