Wuuzzaa
Wuuzzaa

Reputation: 43

SharedPreferences in separate class

I'm having trouble calling SharedPreferences in a non activity class. Unfortunately I don't get any errors in Android Studio, but saveList() never executes properly.

public class UDP_Client {
...

public void UDPBroatcast() {

    async_cient = new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {

...
        listenForResponses(ds);

    }
  }
}


private void listenForResponses(DatagramSocket socket) throws IOException {
        byte[] buf = new byte[1024];
        try {
            while (true) {
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);
                String s = new String(packet.getData(), 0, packet.getLength());
                String ipaddress = packet.getAddress().getHostAddress();
                if (!(ipaddress.equals(ownIPAddress))) {
                    Log.d(TAG, "Received response: " + s + " From IP: " + ipaddress);
                }
                arrayList.add(ipaddress);
                Log.d(TAG, "Added IP:" + ipaddress + " to ArrayList");
            }
        } catch (SocketTimeoutException e) {
            Log.d(TAG, "Receive timed out");
            SaveIPs.saveList(); //Calling saveList after timeout
        }
    }    

...

public static class SaveIPs {

    private final Context context;
    private static SharedPreferences sharedPrefs;

    public SaveIPs(Context context) {
        this.context = context;
        sharedPrefs = context.getSharedPreferences("Found_Devices", 0);
    }

    private static void saveList() {
        SharedPreferences.Editor edit = sharedPrefs.edit();
        edit.clear();
        Object[] mStringArray = arrayList.toArray();
        for (int i = 0; i < mStringArray.length; i++) {
            Log.d("Saving storage position " + i + " to", (String) mStringArray[i]);
            edit.putString("Server" + i, (String) mStringArray[i]);
        }
        edit.commit();
    }
   }
}

Any idea?

I left out some code for overview purpose.

LogCat:

07-22 13:02:32.891    5232-5271/de.liquidbeam.LED.control D/UDP Discovery﹕ Own IP Address: 192.168.0.117
07-22 13:02:33.282    5232-5271/de.liquidbeam.LED.control D/UDP Discovery﹕ Sending data: <cmd="discover" application="liquidbeam_remote" challenge="myUDP" signature="5e6198975160345df82aa6085ebf7e9c"/>
07-22 13:02:33.282    5232-5271/de.liquidbeam.LED.control E/UDP Discovery﹕ Data sent:Messageto IP: 192.168.0.255
07-22 13:02:33.292    5232-5271/de.liquidbeam.LED.control D/UDP Discovery﹕ Added IP:192.168.0.117 to ArrayList
07-22 13:02:33.322    5232-5271/de.liquidbeam.LED.control D/UDP Discovery﹕ Received response: Hallo!!! From IP: 192.168.0.134
07-22 13:02:33.322    5232-5271/de.liquidbeam.LED.control D/UDP Discovery﹕ Added IP:192.168.0.134 to ArrayList
07-22 13:02:34.323    5232-5271/de.liquidbeam.LED.control D/UDP Discovery﹕ Receive timed out
07-22 13:02:34.333    5232-5271/de.liquidbeam.LED.control W/System.err﹕ java.lang.NullPointerException
07-22 13:02:34.333    5232-5271/de.liquidbeam.LED.control W/System.err﹕ at de.liquidbeam.LED.control.fragments.UDP_Client$SaveIPs.saveList(UDP_Client.java:201)
07-22 13:02:34.333    5232-5271/de.liquidbeam.LED.control W/System.err﹕ at de.liquidbeam.LED.control.fragments.UDP_Client$SaveIPs.access$200(UDP_Client.java:190)
07-22 13:02:34.333    5232-5271/de.liquidbeam.LED.control W/System.err﹕ at de.liquidbeam.LED.control.fragments.UDP_Client.listenForResponses(UDP_Client.java:118)
07-22 13:02:34.333    5232-5271/de.liquidbeam.LED.control W/System.err﹕ at de.liquidbeam.LED.control.fragments.UDP_Client.access$100(UDP_Client.java:36)
07-22 13:02:34.333    5232-5271/de.liquidbeam.LED.control W/System.err﹕ at de.liquidbeam.LED.control.fragments.UDP_Client$1.doInBackground(UDP_Client.java:75)
07-22 13:02:34.333    5232-5271/de.liquidbeam.LED.control W/System.err﹕ at de.liquidbeam.LED.control.fragments.UDP_Client$1.doInBackground(UDP_Client.java:57)
07-22 13:02:34.333    5232-5271/de.liquidbeam.LED.control W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-22 13:02:34.343    5232-5271/de.liquidbeam.LED.control W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-22 13:02:34.343    5232-5271/de.liquidbeam.LED.control W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-22 13:02:34.343    5232-5271/de.liquidbeam.LED.control W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-22 13:02:34.343    5232-5271/de.liquidbeam.LED.control W/System.err﹕ at java.lang.Thread.run(Thread.java:841)

Debuging arrayList:

this = {de.liquidbeam.LED.control.fragments.UDP_Client@830044849896}
socket = {java.net.DatagramSocket@830044852416}
buf = {byte[1024]@830045006728}
packet = {java.net.DatagramPacket@830045008808}
s = {java.lang.String@830045009744}"Hallo!!!"
ipaddress = {java.lang.String@830045009816}"192.168.0.134"
arrayList = {java.util.ArrayList@830044849872} size = 2
[0] = {java.lang.String@830045008192}"192.168.0.117"
[1] = {java.lang.String@830045009816}"192.168.0.134"

Upvotes: 0

Views: 607

Answers (2)

MOSO
MOSO

Reputation: 393

You are getting this exception because first you need to initialize the SaveIPs class constructor. Remove static modifier from class as:

public class SaveIPs { // static its not required hopefully:

then in catch block

        catch (SocketTimeoutException e) 
      {
             Log.d(TAG, "Receive timed out");
             SaveIPs saveip_obj = new SaveIPs(context)//pass the context here  
             saveip_obj.saveList();

      }

You might not be having any data in pref because the sharedPrefs = context.getSharedPreferences("Found_Devices", 0);

was not getting called. If this is not the reason would like to know the line no. at which its pointing towards Nullpointer Exception

Upvotes: 1

prakash
prakash

Reputation: 109

Here my understanding is you have to call saveList method after the getting data from the socket connection,that means you can call saveList method after catch block or create a finally block and inside of this block.

I think ArrayList variable arrayList is null so only it throws NullPointerException.Check the data from the socket connection you are getting data or null.

Upvotes: 1

Related Questions