-3

I 'm creating a list that stores and keeps the values as string using shared Preferences.I want to store time of events(Some events).

My code looks like

package com.defcomdevs.invento16;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.Nullable;
import android.util.Log;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

/**
 * Created by midhun on 18/11/15.
 */
public class SetTimings {

    // context to hold the calling activity
    static Context c;
    String[] event_times;
    // declare file name and mode of access
    public static String MY_PREFS = "MY_PREFS";
    private SharedPreferences mySharedPreferences = new SharedPreferences() {
        @Override
        public Map<String, ?> getAll() {
            return null;
        }

        @Nullable
        @Override
        public String getString(String key, String defValue) {
            return null;
        }

        @Nullable
        @Override
        public Set<String> getStringSet(String key, Set<String> defValues) {
            return null;
        }

        @Override
        public int getInt(String key, int defValue) {
            return 0;
        }

        @Override
        public long getLong(String key, long defValue) {
            return 0;
        }

        @Override
        public float getFloat(String key, float defValue) {
            return 0;
        }

        @Override
        public boolean getBoolean(String key, boolean defValue) {
            return false;
        }

        @Override
        public boolean contains(String key) {
            return false;
        }

        @Override
        public Editor edit() {
            return null;
        }

        @Override
        public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {

        }

        @Override
        public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {

        }
    };
    int prefMode = c.MODE_PRIVATE;
    public static String[] eventslist = new String[50];

    public SetTimings(Context context, String[] strings) {

        int i = 0;

        Log.d("Midhun", strings[1]);
        this.c = context;
        eventslist = c.getResources().getStringArray(R.array.Items);
        SharedPreferences.Editor editor = mySharedPreferences.edit();
        editor.putString(eventslist[i++], strings[i++]);
        editor.putString(eventslist[i++], strings[i++]);
        editor.putString(eventslist[i++], strings[i++]);
        editor.putString(eventslist[i++], strings[i++]);
        editor.putString(eventslist[i++], strings[i++]);
        editor.putString(eventslist[i++], strings[i++]);
        editor.putString(eventslist[i++], strings[i++]);
        editor.putString(eventslist[i++], strings[i++]);
        editor.putString(eventslist[i++], strings[i++]);
        editor.putString(eventslist[i++], strings[i++]);
        editor.apply();
        Log.d("Midhun", mySharedPreferences.getString(eventslist[2], "null"));
    }

    public String[] getTimings(Context c1) {

        eventslist = c1.getResources().getStringArray(R.array.Items);
        for (int i = 0; i < eventslist.length; i++) {
            event_times[i] = String.valueOf(mySharedPreferences.getString(eventslist[i], ""));
        }
        return event_times;
    }
}

i call the class and constructor like this:

setTimings= new SetTimings(this,this.getResources().getStringArray(R.array.Items));

And access the strings like this:

String[] time= setTimings.getTimings(this);

Problem When i run my app it crashes.

Log Report:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] com.defcomdevs.invento16.SetTimings.getTimings(android.content.Context)' on a null object reference

This shows the error is in getTimings() method, I tried with some questions on the SO but didn't work out for me.

Please Highlight my error.And kindly give a solution.Thanks

edit code where i used setTimings:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context=this;
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setLogo(R.mipmap.ic_launcher);
    setSupportActionBar(toolbar);
    getTheAccountName=new GetTheAccountName();
    final Context context=this;
    adapter = new MyAdapter(this, getdata());
    recyclerView = (RecyclerView) findViewById(R.id.recycler);
    recyclerView.setAdapter(adapter);
    recyclerView.setLayoutManager(new GridLayoutManager(this, 2));



    mcollapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
    mcollapsingToolbar.setTitle("INVENTO '16");
    mcollapsingToolbar.setExpandedTitleColor(getResources().getColor(R.color.transparent));
    mcollapsingToolbar.setCollapsedTitleTextColor(getResources().getColor(R.color.white));

    fab_menu_titlescreen= (FloatingActionMenu) findViewById(R.id.menu_item);
    fab_map = (FloatingActionButton) findViewById(R.id.map);
    fab_register = (FloatingActionButton) findViewById(R.id.register);
    fab_reminder = (FloatingActionButton) findViewById(R.id.reminder);
    fab_refresh = (FloatingActionButton) findViewById(R.id.refresh);


    String userName=getTheAccountName.getUsername(context);
    String userId=getTheAccountName.getuserId(context);
    //username= (TextView) findViewById(R.id.userNameText);
    //username.setText(userName);
    userid= (TextView) findViewById(R.id.userNameText);
    userid.setText(userId);

    Log.d("Midhun", "before");
    String[] t= this.getResources().getStringArray(R.array.time);
    //pass the time parameters to the class
    setTimings= new SetTimings(this,t);   //used setTimings

    Log.d("Midhun","after");

and in here

public List<ListItems> getdata() {
    List<ListItems> grid_data = new ArrayList<>();
    int[] icons = {R.drawable.hackbttn100, R.drawable.hackbttn100, R.drawable.hackbttn100, R.drawable.hackbttn100, R.drawable.hackbttn100, R.drawable.hackbttn100, R.drawable.hackbttn100, R.drawable.hackbttn100, R.drawable.hackbttn100, R.drawable.hackbttn100};
    String[] texts = getResources().getStringArray(R.array.Items);
    String[] time= setTimings(context);
    Log.d("Midhun",time[1]);
    for (int i = 0; i < icons.length && i < texts.length; i++) {
        ListItems current = new ListItems();
        current.iconId = icons[i];
        current.IconName = texts[i];
        current.ItemTime = time[i];
        grid_data.add(current);
    }
    return grid_data;
}
Midhun0407
  • 59
  • 6
  • "This shows the error is in `getTimings()` method" - No, your error is saying that `setTimings`, or some other instance of the `SetTimings` class, is null. – Mike M. Nov 19 '15 at 06:26
  • @MikeM. i have given some log statements inside the costructer.But the console is not showing those statements.Seems that flow is not reaching there.what might be the cause. – Midhun0407 Nov 19 '15 at 06:53
  • Dunno. You haven't posted enough of the code where you instantiate and use `setTimings`. – Mike M. Nov 19 '15 at 06:55
  • @MikeM. ihave added the codes for that.can you figure out whats the problem – Midhun0407 Nov 19 '15 at 08:44
  • You're calling `getdata()` in your Adapter instantiation well before instantiating `setTimings`, so it's null in that method. – Mike M. Nov 19 '15 at 08:55
  • I'm assuming you also have a method named `setTimings()`, where the `setTimings` object is used. – Mike M. Nov 19 '15 at 09:02
  • Refer to this link. May be it will helpful to you. [http://stackoverflow.com/questions/4746063/shared-preferences-in-android](http://stackoverflow.com/questions/4746063/shared-preferences-in-android) – Ramesh Bandari Nov 19 '15 at 09:32

3 Answers3

1

It has to do with the following line

editor.putString(eventslist[i++], strings[i++]);

here you are doing i++ twice. this means that you are not referencing the correct array elements and running out-of-bounds as a result

you should probably use a for-loop to do the above. Actually, you can "save" an entire array to sharedpreferences

William Ku
  • 798
  • 5
  • 17
0

Since it's throwing the NullPointerException in getTimings(),you should look for an object which is null and a method of it, is being called. So, the candidates may be : c1 ( of type Context),eventList,mySharedPreference.

Farhad
  • 12,178
  • 5
  • 32
  • 60
0

Thanks to Mike M.

PROBLEM

1.First was that getdata() in my Adapter instantiation is done before instantiating setTimings, so it's null in that method.

2.Second i was assigning array of strings to a non-initialised array of strings eventslist.

3.As pointed out by William Ku i was using i++ twice thus was landing up out of bounds.

Midhun0407
  • 59
  • 6