Android - NPE attemp to invoke Shared Preferences null object Volley

188
December 25, 2017, at 10:07 PM

i have taken the data from the server and apikey then afterwards i save it in the sharedpreferences. when i want to take the apikey, i have constraint with error like below:

E/Volley: [1903] NetworkDispatcher.run: Unhandled exception java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference at com.mimdudin.carekkerje.Activities.TabAddFragment1$3.getHeaders(TabAddFragment1.java:127) at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:93) at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96) at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)

here is the activity where I managed to save apikey in sharefpreferences:

LoginActivity.java
package com.mimdudin.carekkerje.Activities;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
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.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
import com.mimdudin.carekkerje.Helper.AppController;
import com.mimdudin.carekkerje.R;
import com.mimdudin.carekkerje.Util.AppConfig;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends AppCompatActivity {
    private static final String TAG = LoginActivity.class.getSimpleName();
    private EditText inputEmail;
    private EditText inputPassword;
    private Button btnLogin;
    private Button btnRegister;
    private SharedPreferences pref;
    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        pref = getSharedPreferences("data", MODE_PRIVATE);
        setUpUi();
        //buat progress dialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);
        pref = getSharedPreferences("data", Context.MODE_PRIVATE);
        final int login = pref.getInt("login", 0);
        if(login == 1){
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();
                if (!email.isEmpty() && !password.isEmpty()) {
                    checkLogin(email, password);
                } else {
                    Toast.makeText(LoginActivity.this,
                            "Email & Password Tidak boleh kosong", Toast.LENGTH_SHORT).show();
                }
            }
        });
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
    private void checkLogin(final String email, final String password) {
        String tag_string_req = "req_login";
        progressDialog.setMessage("Logging in....");
        showDialog();
        StringRequest strRequest = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, "onResponse: " + response.toString());
                hideDialog();
                try {
                    JSONObject jsonObj = new JSONObject(response);
                    boolean error = jsonObj.getBoolean("error");
                    if (!error){
                        String uid = jsonObj.getString("apiKey");
                        String nama = jsonObj.getString("nama");
                        String email = jsonObj.getString("email");
                        String no_hp = jsonObj.getString("no_hp");
                        SharedPreferences.Editor editor = pref.edit();
                        editor.putString("apiKey", uid);
                        editor.putString("nama", nama);
                        editor.putString("email", email);
                        editor.putString("no_hp", no_hp);
                        editor.putInt("login", 1);
                        editor.commit();
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        String message = jsonObj.getString("message");
                        Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(LoginActivity.this, "JSON error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("Error: " + error.getMessage());
                Log.d(TAG, "onErrorResponse: " + error.getMessage());
                if (error instanceof NetworkError || error instanceof NoConnectionError|| error instanceof TimeoutError){
                    Toast.makeText(LoginActivity.this, "Please check your Connection", Toast.LENGTH_SHORT).show();
                }
                hideDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
//kirim params email dan password ke server
                Map<String, String> params = new HashMap<>();
                params.put("email", email);
                params.put("pass", password);
                return params;
            }
        };
        AppController.getInstance().addToRequestQueue(strRequest, tag_string_req);
    }
    public void showDialog(){
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
    }
    public void hideDialog(){
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
    private void setUpUi() {
        inputEmail = findViewById(R.id.inputEmail);
        inputPassword = findViewById(R.id.inputPassword);
        btnLogin = findViewById(R.id.btnLogin);
        btnRegister = findViewById(R.id.btnRegister);
    }
}

AND

in this tab i want to take the apikey which i have previously saved in sharefpreferences:

TabAddFragment1.java
package com.mimdudin.carekkerje.Activities;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
import com.mimdudin.carekkerje.Adapter.AddRecyclerViewadapter;
import com.mimdudin.carekkerje.Helper.AppController;
import com.mimdudin.carekkerje.Model.Add;
import com.mimdudin.carekkerje.R;
import com.mimdudin.carekkerje.Util.AppConfig;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * A simple {@link Fragment} subclass.
 */
public class TabAddFragment1 extends Fragment {
    private RecyclerView recyclerView;
    private AddRecyclerViewadapter addRecyclerViewadapter;
    private List<Add> addList;
    private SharedPreferences sharedPreferences;
    public TabAddFragment1() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this
        View view = inflater.inflate(R.layout.tabadd1, container, false);
        recyclerView = view.findViewById(R.id.recyclerViewAdd);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        addList = new ArrayList<>();
        addList = getAdd();
        addRecyclerViewadapter = new AddRecyclerViewadapter(getContext(), addList);
        recyclerView.setAdapter(addRecyclerViewadapter);
        addRecyclerViewadapter.notifyDataSetChanged();
        sharedPreferences = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
        return view;
    }
    private List<Add> getAdd() {
        String tag_headers_req = "req_apikey";
        StringRequest strRequest = new StringRequest(Request.Method.POST, AppConfig.URL_GETADD,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("onResponse: ", response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            boolean error = jsonObject.getBoolean("error");
                            if (!error){
                                JSONArray jsonArr = jsonObject.getJSONArray("transaksi");
                                for (int i = 0; i < jsonArr.length(); i++){
                                    JSONObject allObj = jsonArr.getJSONObject(i);
                                    Add add = new Add();
                                    add.setTitleAdd(allObj.getString("title"));
                                    add.setPreviewAdd(allObj.getString("deskripsi"));
                                    add.setTanggalAdd(allObj.getString("tanggal"));
                                    add.setImg_logoAdd(allObj.getString("img_logo"));
                                    SharedPreferences.Editor editor = sharedPreferences.edit();
                                    editor.putString("title", add.getTitleAdd());
                                    editor.putString("deskripsi", add.getPreviewAdd());
                                    editor.putString("tanggal", add.getTanggalAdd());
                                    editor.putString("img_logo", add.getImg_logoAdd());
                                    editor.apply();
                                    addList.add(add);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("Error: " + error.getMessage());
                if (error instanceof TimeoutError || error instanceof NoConnectionError || error instanceof NetworkError){
                    Toast.makeText(getContext(), "Please check your connection!", Toast.LENGTH_SHORT).show();
                }
            }
        })
        {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                String apiKey = sharedPreferences.getString("apiKey", "User tidak ditemukan");
                headers.put("apiKey", apiKey);
                return headers;
            }
        };
        AppController.getInstance().addToRequestQueue(strRequest, tag_headers_req);
        return  addList;
    }
}

hope you can help me in solving this problem.

READ ALSO
TableViewer add item false with java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.String;

TableViewer add item false with java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.String;

I want to add some items in the table when user pressing the Add buttonBut I got a java

211
AspectJ - pointcut for methods of interface&#39;s implementation

AspectJ - pointcut for methods of interface's implementation

I have several implementations of SomeInterfaceThe question is what is the pointcut for the method executeSomething in all implementation of SomeInterface

187
Showing Listview in Fragment

Showing Listview in Fragment

I am a beginner in programming and am stuck working on my first ever project which will be a real motivation if I succeedI am trying to get my listview to show in my tabbed fragment

169
Is it possible to use databinding in widgets?

Is it possible to use databinding in widgets?

i'm trying to build a widget that uses a layout that's inside the appThe binding works in the app but not on the widget

196