non static method write can not be referenced from a static context

1

I'm a beginner in and in general programming, I was following a video lesson to write a string to a txt file, when I came across the following error:

  

Error: (49, 31) error: non-static method write (String) can not be   referenced from a static context

I checked and the code seemed to be correct before the teacher.

Here is the java code:

package minhasanotacoes.cursoandroid.com.minhaanotacoes;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import java.io.IOException;
import java.io.OutputStreamWriter;

import static java.io.OutputStreamWriter.*;

public class MainActivity extends Activity {

    private EditText texto;
    private ImageView botaoSalvar;

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        texto =  findViewById(R.id.texto_ID);
        botaoSalvar = findViewById(R.id.botao_salvar_id);

        botaoSalvar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String textoDigitado = texto.getText().toString();


            }
        });
    }

    private void gravarNoArquivo(String texto) {
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("anotacao.txt", Context.MODE_PRIVATE));
            OutputStreamWriter.write(texto);
        } catch(IOException e) {
            Log.v("MainActivity", e .toString());
        }
    }
}
    
asked by anonymous 18.11.2017 / 13:57

1 answer

3

Your error is in:

private void gravarNoArquivo(String texto) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("anotacao.txt", Context.MODE_PRIVATE));
        OutputStreamWriter.write(texto);
    } catch(IOException e) {
        Log.v("MainActivity", e .toString());
    }
}

You are calling method write in OutputStreamWriter , should be outputStreamWriter.write(texto)

Calling like this: OutputStreamWriter.write(texto); , will not work, class OutputStreamWriter does not have the static method write with this signature, so the error, you should call the method on the object you just created

    
18.11.2017 / 14:05