尝试在Null对象引用上调用虚方法

时间:2016-01-12 10:05:53

标签: android nullpointerexception sharedpreferences

  

我创建了一个登录名并尝试保存UserName和UserID   会话,但我在这一行收到错误

mAppPreference.setUserID(userid);
  

错误是: -

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

这是我的登录类

  

public class LoginPagefrag extends Fragment实现了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;
}

}

  

这是我的AppPreference类: -

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(), "");
}

}

请告诉我这里缺少的东西。提前谢谢。

3 个答案:

答案 0 :(得分:1)

您没有调用initialiseNoramlVariable方法,因此 mAppPreference 未初始化。

这应该让你前进:

@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;
}   

答案 1 :(得分:1)

您需要初始化变量mAppPreference

我的意思是你已经在方法initialiseNoramlVariable()中完成了,但从未调用过该方法。您应该在onCreateView()

中调用该方法

答案 2 :(得分:1)

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

    cxt = getActivity();

    mAppPreference = AppPreference.getInstance(cxt);    

}

您自己添加了"unused"警告。你实际上从不称呼这种方法。因此mAppPreferencenull。如果此方法无效,请将mAppPreference = AppPreference.getInstance(cxt);移至其他地方,例如onCreateView,以确保其可以被引用。