-2

I am trying to save my settings in a file, but always when it comes to writing into the file, I get NullPointerException

02-05 09:54:21.021 4102-4102/? I/art: Not late-enabling -Xcheck:jni (already on)
02-05 09:54:21.092 4102-4102/com.example.andy.newshit W/System: ClassLoader referenced unknown path: /data/app/com.example.andy.newshit-1/lib/x86_64
02-05 09:54:22.588 4102-4180/com.example.andy.newshit D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-05 09:54:22.618 4102-4180/com.example.andy.newshit I/OpenGLRenderer: Initialized EGL, version 1.4
02-05 09:54:22.630 4102-4180/com.example.andy.newshit W/EGL_emulation: eglSurfaceAttrib not implemented
02-05 09:54:22.630 4102-4180/com.example.andy.newshit W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f76333968c0, error=EGL_SUCCESS
02-05 09:54:26.746 4102-4102/com.example.andy.newshit W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
02-05 09:54:26.795 4102-4180/com.example.andy.newshit W/EGL_emulation: eglSurfaceAttrib not implemented
02-05 09:54:26.795 4102-4180/com.example.andy.newshit W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f7633396c80, error=EGL_SUCCESS
02-05 09:54:28.031 4102-4180/com.example.andy.newshit W/EGL_emulation: eglSurfaceAttrib not implemented
02-05 09:54:28.031 4102-4180/com.example.andy.newshit W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f7626d5a640, error=EGL_SUCCESS
02-05 09:54:28.142 4102-4180/com.example.andy.newshit E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f7637d5a780
02-05 09:54:28.145 4102-4180/com.example.andy.newshit E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f7637d59e50
02-05 09:54:28.146 4102-4180/com.example.andy.newshit D/OpenGLRenderer: endAllStagingAnimators on 0x7f7626dba000 (ListPopupWindow$DropDownListView) with handle 0x7f7626edad00
02-05 09:54:32.604 4102-4102/com.example.andy.newshit D/AndroidRuntime: Shutting down VM
02-05 09:54:32.604 4102-4102/com.example.andy.newshit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.andy.newshit, PID: 4102 java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference
at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:183)
at com.example.andy.newshit.Filehandling.writeFile(Filehandling.java:20)
at com.example.andy.newshit.IPandPort.setIP(IPandPort.java:45)
at com.example.andy.newshit.SettingsActivity$1.onClick(SettingsActivity.java:29)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

This is my Class which I have to handle the files

package com.example.andy.newshit;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * Created by buddy on 05.02.16.
 */
public class Filehandling extends AppCompatActivity{

    public void writeFile(String Filename, String Text) throws IOException {
        FileOutputStream fos = openFileOutput(Filename, Context.MODE_PRIVATE);
        fos.write(Text.getBytes());
        fos.close();
    }

    public void readFile(String File) throws IOException {
        try {
            BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput(File)));
            String inputString;
            StringBuffer stringBuffer = new StringBuffer();
            inputString = inputReader.readLine();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}

I really hope I can get some help.

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57

4 Answers4

1

100% sure & Tested .. Using this code File will be Read from device :

public void readFile(String File) throws IOException {
        File cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "/stackover");
        //for make the directory if not exist
        if (!cacheDir.exists())
            cacheDir.mkdirs();
        File f = new File(cacheDir, File);
        FileInputStream fin = new FileInputStream(f);
        InputStreamReader isr = new InputStreamReader(fin);
        char[] ib = new char[1000];
        String str ="";
        int cr ;
        while( (cr=isr.read(ib))>0)
        {
            String s = String.copyValueOf(ib,0,cr);
            str+=s;
            ib = new char[1000];
        }
        isr.close();

    Toast.makeText(getApplicationContext(),str+"", Toast.LENGTH_SHORT).show();
    }
}
Rajesh Satvara
  • 3,842
  • 2
  • 30
  • 50
0

From the stack frace, it is obvious you are calling Filehanlding Activity method from SettingsActivity.

You cannot do this. In order to use Context-related methods, Filehandling needs to be a created Activity.

In order to do what you want from SettingsActivity's OnClickListener, you have to make Filehandling an util class which receives Context of a working Activity.

public final class Filehandling {

    private Filehandling() {
    }

    public static void writeFile(Context context, String Filename, String Text) throws IOException {
        FileOutputStream fos = context.openFileOutput(Filename, Context.MODE_PRIVATE);
        fos.write(Text.getBytes());
        fos.close();
    }

    public sttaic void readFile(Context context, String File) throws IOException {
        try {
            BufferedReader inputReader = new BufferedReader(new InputStreamReader(context.openFileInput(File)));
            String inputString;
            StringBuffer stringBuffer = new StringBuffer();
            inputString = inputReader.readLine();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}

public class IPandPort {


    public static void setIp(Context context) {
        try {
            FileHandling.writeFile(context, "file.txt", "yourtext");
        } catch (IOException e) {
            // TODO
        }
    }
}

And from SettingsActivity, you can do like this

btn.setOnClickListener(bew View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Pass a Context as SettingsActivity from anonymous listener. Note if it's not an inner class you can just pass "this"
        IPandPort.setIp(SettingsActivity.this);
    }
});
Yaroslav Mytkalyk
  • 16,950
  • 10
  • 72
  • 99
0

100% sure

Using this code File will be Writeen in your Internel storage with satyam folder. Try and have a happy Coding...

     public void writeFile(String Filename, String Text) throws IOException {

                File cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "/satyam");
                //for make the directory if not exist
                if (!cacheDir.exists())
                    cacheDir.mkdirs();

               File f = new File(cacheDir, Filename);
                FileOutputStream fout = new FileOutputStream(f);
                OutputStreamWriter osw = new OutputStreamWriter(fout);

                osw.write(Text);
                osw.flush();
                osw.close();
Toast.makeText(getApplicationContext(),"Success",Toast.LENGTH_SHORT).show();
         }
Rajesh Satvara
  • 3,842
  • 2
  • 30
  • 50
-1

First try to check file exist or not which you want to read

 File data = new File(filePath);
        if(data.exists()) {
  // your  code to read file     
  }

Update

write data to a file properly :

public void writeFile(String Filename, String Text) throws IOException {
  String path = Environment.getExternalStorageDirectory() + File.separator + "/"+Filename + File.separator;
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File data = new File(path);
        if (!data.createNewFile()) {
            data.delete();
            data.createNewFile();
        } 
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(data));
        objectOutputStream.writeObject(Text.getBytes());
        objectOutputStream.close();
}
Kapil Rajput
  • 11,429
  • 9
  • 50
  • 65
  • 1
    It doesn't exist. It should be created if I am not completely wrong – buddyspencer Feb 05 '16 at 09:21
  • @buddyspencer file should be created while writing the file not while reading in your case and comeon why downvote i dont think i suggest you something wrong. – Kapil Rajput Feb 05 '16 at 09:25
  • I'm pretty sure I haven't voted anything... And you are right. I now created the file first and I don't run in a exception anymore. Thx – buddyspencer Feb 05 '16 at 09:31
  • @KapilRajput I downvoted because the real problem is when writing a file. Also, contex.openFileInput() throws FileNotFoundException if File does not exist, so no need to check if file exists in this case at all. – Yaroslav Mytkalyk Feb 05 '16 at 09:35