akshay1728
akshay1728

Reputation: 383

Openfileinput returning the nullpointer exception

I am using the following code for creating and writing to the file

 FileOutputStream fOut = mcontext.openFileOutput("msg.txt",Context.MODE_WORLD_READABLE);
    OutputStreamWriter osw = new OutputStreamWriter(fOut);
    osw.write("abc");
    osw.flush();
    osw.close();

But in the LOG cat its giving the null pointer exception at the 1st line of the above code.

Here is the whole code

public class Server implements Runnable 
{
private String address ="127.0.0.1";
private String add="127.0.0.2";
private static Context mcontext;
byte[] buf = new byte[256];
DatagramSocket socket;

@Override

public void run()

{
    try{

    InetAddress serveradd =  InetAddress.getByName(address);
    InetAddress clientadd = InetAddress.getByName(add);
    socket=new DatagramSocket(6000,serveradd);
    Log.d("UDP", "S: Connecting...");


    DatagramPacket packet=new DatagramPacket(buf,buf.length);
    socket.receive(packet);
    Log.d("UDP", "S: Receiving...");

    /* Receive the UDP-Packet */
    String data=new String(packet.getData());
    String phno=data.substring(0,9);
    String identity=data.substring(10,14);




    //FileWriter f = new FileWriter("/sdcard/download/msg.txt");
    // I/O operation
    FileOutputStream fOut = mcontext.openFileOutput("msg.txt",Context.MODE_WORLD_READABLE);
    OutputStreamWriter osw = new OutputStreamWriter(fOut);
    osw.write("gfdffg");
    osw.flush();
    osw.close();



    Log.d("UDP", "S: ReceivedJI: '" + new String(packet.getData()) + "'");
    Log.d("UDP", "S: Done.");
    //Toast.makeText(context.getApplicationContext(),"received"+new String(packet.getData()),Toast.LENGTH_LONG).show();
   // if(TextUtils.isDigitsOnly(phno) && identity.equals("novel"))
   // {
    byte[] bufsend =("hi").getBytes();
    Log.d("UDP", "S: sending.");
    DatagramPacket packetsend=new DatagramPacket(bufsend,bufsend.length,clientadd,5000);
    socket.send(packetsend);
    Log.d("UDP", "S: send.'"+bufsend+"'");
    //}
    //else
   // {
        //Log.d("UDP", "S: not matched.");
   // }
    }
    catch (Exception e)
    {
        Log.e("UDP", "S: Error", e);
        e.printStackTrace();
        //Toast.makeText(context.getApplicationContext(),"received"+e,Toast.LENGTH_LONG).show();    
    }

}

}

Any help will be appreciated

Upvotes: 0

Views: 668

Answers (2)

tolgap
tolgap

Reputation: 9778

When you use mcontext you haven't set it anywhere in your code. So the variable is null. You should give your Runnable a constructor where it accepts a Context:

public Server(Context context) {
    mcontext = context;
}

So you can set the mcontext variable. Also, don't make it static.

Upvotes: 1

Rajendra
Rajendra

Reputation: 1698

add this to manifest.xml

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

Upvotes: 0

Related Questions