non Static method write cannot be referenced from a Static context

Asked

Viewed 295 times

1

I’m a beginner in and in programming overall, I was following a classroom video to record a string in a txt file, when I came across the following error:

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

I checked and the code seemed to be correct in front of the teacher’s.

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());
        }
    }
}

1 answer

3

Your mistake 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 the method write in OutputStreamWriter, should be outputStreamWriter.write(texto)

Calling it that: OutputStreamWriter.write(texto);, it won’t work, the class Outputstreamwriter does not have the static method write with this signature, so the error, you must call the method in the object you have just created

Browser other questions tagged

You are not signed in. Login or sign up in order to post.