-3

I have created a login and trying to save the UserName and UserID for session but I am getting an error at this line

mAppPreference.setUserID(userid);

The error is :-

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.android.mivas.AppContoller.AppPreference.setUserID(java.lang.String)' on a null object reference

here is my Login class

public class LoginPagefrag extends Fragment implements OnClickListener, MiFeelingBase {

private Intent i;
private int urlIndex=0;
private Button btnLogin;
private EditText edUserName,edPassword;
private String strUserName,strPassword;
private String strEmailID;
private MultipartEntity reqEntity;
private Dialog dialog;
private ProgressDialog pDialog;
Context cxt;
private SessionManager session;
SharedPreferences myPriference;
AppPreference mAppPreference;

public static final String TAG_USERID = "userid";
public static String TAG_USERNAME = "username";


private static final Pattern EMAIL_PATTERN = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.loginpage, container, false);

    APIAccess.fetchData(LoginPagefrag.this, getActivity(), getActivity());

    btnLogin=(Button)rootView.findViewById(R.id.btnLogin);
    edUserName=(EditText)rootView.findViewById(R.id.edUserName);
    edPassword=(EditText)rootView.findViewById(R.id.edPassword);


   btnLogin.setOnClickListener(this);

   return rootView;

}
@SuppressWarnings("unused")
private void initialiseNoramlVariable() {

    cxt = getActivity();

    mAppPreference = AppPreference.getInstance(cxt);    

}

public void postLogin()
{
    try
    {
     StringBody username=new StringBody(strUserName);
     StringBody password=new StringBody(strPassword);


    reqEntity = new MultipartEntity();

    reqEntity.addPart("username", username);
    reqEntity.addPart("password", password);

    }
    catch(Exception e)
    {
        System.out.println("err" + e);
    }

}

public void postForgotPass()
{
    try
    {
     StringBody emailid=new StringBody(strEmailID);


    reqEntity = new MultipartEntity();

    reqEntity.addPart("email", emailid);

    }
    catch(Exception e)
    {
        System.out.println("err" + e);
    }

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch(v.getId())
    {

    case R.id.btnLogin :
        if(edUserName.getText().toString().equalsIgnoreCase(""))
        {
        //  Toast.makeText(LoginPagefrag.this, "enter username", Toast.LENGTH_SHORT).show();
        }else if(edPassword.getText().toString().equalsIgnoreCase(""))
        {
            //Toast.makeText(LoginPagefrag.this, "enter pass", Toast.LENGTH_SHORT).show();
        }else
        {
            strUserName=edUserName.getText().toString();
            strPassword=edPassword.getText().toString();
            urlIndex=0;
             APIAccess.fetchData(LoginPagefrag.this, getActivity(), getActivity());
        }
        break;
    }
}


@Override
public String httpPost() {
    // TODO Auto-generated method stub
    String response="";
    if(urlIndex==0)
    {
    postLogin();
    response=APIAccess.openConnection(StaticData.SABAKUCH_LOGIN, reqEntity);

    }
    return response;
}

@Override
public String httpAfterPost(String str) {
    // TODO Auto-generated method stub
    if(str!=null)
    {
        if(urlIndex==0)
        {
        if(SabaKuchParsechat.jsonStatus(str)==0)
        {
        //  Toast.makeText(LoginPagefrag.this, SabaKuchParsechat.jsonErrorMessage(str), Toast.LENGTH_SHORT).show();
        }

        else if(SabaKuchParsechat.jsonStatus(str)==1)
        {

            LoginData obj=SabaKuchParsechat.parseLoginData(str);

            Log.d("objj", "hello"+obj);

            String userid = obj.strUserId;              
            String username= obj.strUserName;

            mAppPreference.setUserID(userid);
            mAppPreference.setUserName(username);
            mAppPreference.setServerKey();

            session.setLogin(true);

            Intent iintt =  new Intent(getActivity(),MainActivity.class);
            startActivity(iintt);



        }
        }
    }
    return null;
}
private boolean CheckEmail(String email) {

    return EMAIL_PATTERN.matcher(email).matches();

}
public ConnectivityManager getSystemService(String connectivityService) {
    // TODO Auto-generated method stub
    return null;
}

}

Here is my AppPreference class :-

public class AppPreference extends Application {

Context cxt;

private static final String SHARED_APP_PREFERENCE_NAME = "sabakuchapp_pref_key";
public static AppPreference mAppprefernce;
private SharedPreferences pref;
private Editor mEditor;



public AppPreference() {
    super();
    // TODO Auto-generated constructor stub
}

enum SharedPreferenceKey{
    USER_ID, USER_NAME, SERVER_KEY;
}

private AppPreference (Context context){
    pref = context.getSharedPreferences(SHARED_APP_PREFERENCE_NAME, Context.MODE_PRIVATE);
    mEditor = pref.edit();
}



public AppPreference(Context cxt, SharedPreferences pref, Editor mEditor) {
    super();
    this.cxt = cxt;
    this.pref = pref;
    this.mEditor = mEditor;
}


public static AppPreference getInstance(Context context){
    if(mAppprefernce == null){
        mAppprefernce = new AppPreference(context);
    }
    return  mAppprefernce;
}

public void setUserID(String id){
    mEditor.putString(SharedPreferenceKey.USER_ID.toString(), id);
    mEditor.commit();
}

public String getUserID(){
    return pref.getString(SharedPreferenceKey.USER_ID.toString(), "");
}

public void setUserName(String name){
    mEditor.putString(SharedPreferenceKey.USER_NAME.toString(), name);
    mEditor.commit();
}

public String getUserName(){
    return pref.getString(SharedPreferenceKey.USER_NAME.toString(), "");
}

public void setServerKey(){

    String original = getUserID()+"_" + getUserName() + "_SBK";
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("MD5");
        md.update(original.getBytes());
        byte[] digest = md.digest();
        StringBuffer sb = new StringBuffer();
        for (byte b : digest) {
            sb.append(String.format("%02x", b & 0xff));
        }
        mEditor.putString(SharedPreferenceKey.SERVER_KEY.toString(), sb.toString());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        mEditor.putString(SharedPreferenceKey.SERVER_KEY.toString(), "");
    }       
    mEditor.commit();
    return;
}

public String getServerKey(){
    return pref.getString(SharedPreferenceKey.SERVER_KEY.toString(), "");
}

}

Please let me know what I am missing here. Thanks in advance.

Devraj
  • 1,479
  • 1
  • 22
  • 42
  • Ok so Mr. negative marker. Please solve the issue and tell me why negative marking or is it only a fashion to mark negative whenever you see NULLPOINTER???? – Devraj Jan 12 '16 at 10:08
  • See Selvin, please do me a favor, first try to read my complete problem, – Devraj Jan 12 '16 at 10:09
  • 2
    please do everyone a favor and read "What is a Null Pointer Exception, and how do I fix it?" ... you never assign mAppPreference and asking why you are getting NPE ... – Selvin Jan 12 '16 at 10:11
  • @Devraj: You're here for help, please don't sound this rude. You can see my answer for your problem. – Rohit5k2 Jan 12 '16 at 10:14
  • @Rohit5k2 yes bro, I am trying your solution, and I am really sorry about my words. But when feels bad when some just marked negative before reading the question. I already mentioned that please let me know what I am missing here. Anyways, I am really sorry if I did sound rude. – Devraj Jan 12 '16 at 10:18

3 Answers3

1

You are not calling initialiseNoramlVariable method and therefor mAppPreference does not get initialized.

This should get you going:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.loginpage, container, false);

    APIAccess.fetchData(LoginPagefrag.this, getActivity(), getActivity());

    btnLogin=(Button)rootView.findViewById(R.id.btnLogin);
    edUserName=(EditText)rootView.findViewById(R.id.edUserName);
    edPassword=(EditText)rootView.findViewById(R.id.edPassword);

    btnLogin.setOnClickListener(this);

    cxt = getActivity();
    mAppPreference = AppPreference.getInstance(cxt); 

    return rootView;
}   
vilpe89
  • 4,656
  • 1
  • 29
  • 36
1

You need to initialize your variable mAppPreference.

I mean you have done that in method initialiseNoramlVariable() but never called the method. You should call the method in onCreateView()

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
1
@SuppressWarnings("unused")
private void initialiseNoramlVariable() {

    cxt = getActivity();

    mAppPreference = AppPreference.getInstance(cxt);    

}

You added "unused" warning by yourself. And you never call this method in fact. So mAppPreference is null. If this method is useless, move mAppPreference = AppPreference.getInstance(cxt); to somewhere else such as onCreateView to make sure it could be inited.

Dennis Lu
  • 762
  • 2
  • 9
  • 21