2013-12-09 112 views
0

这是我检查用户是否已登录的代码。无法保存永久登录状态?

但是,每当我运行这段代码时,我总是得到这个错误。

我试图解决它,但我不能。

这里是我的错误

12-09 18:19:43.640: E/AndroidRuntime(832): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127) 
12-09 18:19:43.640: E/AndroidRuntime(832):at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:371) 
12-09 18:19:43.640: E/AndroidRuntime(832): at ndroid.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:366) 
12-09 18:19:43.640: E/AndroidRuntime(832): at com.example.totallyfinish.MainActivity.saveLoggedIn(MainActivity.java:98) 
12-09 18:19:43.640: E/AndroidRuntime(832): at   com.example.totallyfinish.Login$4.onClick(Login.java:295) 
12-09 18:19:43.640: E/AndroidRuntime(832): at android.view.View.performClick(View.java:3480) 
12-09 18:19:43.640: E/AndroidRuntime(832): at android.view.View$PerformClick.run(View.java:13983) 
12-09 18:19:43.640: E/AndroidRuntime(832): at android.os.Handler.handleCallback(Handler.java:605) 
12-09 18:19:43.640: E/AndroidRuntime(832): at android.os.Handler.dispatchMessage(Handler.java:92) 
12-09 18:19:43.640: E/AndroidRuntime(832): at android.os.Looper.loop(Looper.java:137) 
12-09 18:19:43.640: E/AndroidRuntime(832): at android.app.ActivityThread.main(ActivityThread.java:4340) 
12-09 18:19:43.640: E/AndroidRuntime(832): at java.lang.reflect.Method.invokeNative(Native Method) 
12-09 18:19:43.640: E/AndroidRuntime(832): at java.lang.reflect.Method.invoke(Method.java:511) 
12-09 18:19:43.640: E/AndroidRuntime(832): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
12-09 18:19:43.640: E/AndroidRuntime(832): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
12-09 18:19:43.640: E/AndroidRuntime(832): at dalvik.system.NativeStart.main(Native Method) 

帮我找到它吧。

public class MainActivity extends Activity { 

ImageButton Imagebtn_start; 
Boolean isInternetPresent = false; 
ConnectionDetector conDetector; 
private static final int MY_NOTIFICATION_ID=1; 
NotificationManager notificationManager; 
Notification myNotification; 
SharedPreferences prefsNagSetting; 
private static final String NAG_PREFS = "socially_you_nag_prefs"; 
/* THE EDITOR */ 
Editor editor; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    jsonen(); 
    Imagebtn_start = (ImageButton) findViewById(R.id.image_btnstart); 
    conDetector = new ConnectionDetector(getApplicationContext()); 
    Imagebtn_start.setOnClickListener(new OnClickListener() { 
    Intent intentfromLogin = getIntent(); 
     @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 

      isInternetPresent = conDetector.isConnectingToInternet(); 
      Boolean value=true; 

      if (isInternetPresent){ 

        if (isLoggedIn()){ 
         Intent team= new Intent(MainActivity.this,Team.class); 
         startActivity(team); 
        } 
        else{ 

        Intent goLogin=new Intent(MainActivity.this,Login.class); 
        startActivity(goLogin); 
        } 
      } 
      else{ 
       showAlertDialog(MainActivity.this, "No Internet Connection", 
          "You don't have internet connection.", false); 
      } 
     } 
    }); 
} 

private boolean isLoggedIn() { 
    SharedPreferences sharedPreferences = PreferenceManager 
      .getDefaultSharedPreferences(getApplicationContext()); 
    //The false represents the default value, if the variable is not stored 
    boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false); 
    return isLoggedIn; 
} 

public void saveLoggedIn(boolean value) { 
    SharedPreferences sharedPreferences = PreferenceManager 
      .getDefaultSharedPreferences(this); 
    Editor editor = sharedPreferences.edit(); 
    editor.putBoolean("isLoggedIn", value); 
    editor.commit(); 
} 
public void jsonen() 
{ 
    int status=2; 
    JSONObject json=null; 
    String response = null; 
    String teamID=null; 

    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
    //postParameters.add(new BasicNameValuePair("email",edit_txt_EmailAddress.getText().toString()));//// define the parameter 
    postParameters.add(new BasicNameValuePair("userID","396797666")); 

    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() 
     .detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread 
     .penaltyLog().build()); 

    try { 
      response=CustomHttpClient.executeHttpPost("http://10.0.2.2/football365/notification.php", postParameters); 
     // json=new JSONObject(response); 
     // teamID=json.getString("teamID"); 
     // Log.i("Team ID",teamID+""); 
     } 
    catch (Exception e) { 

     e.printStackTrace(); 
    } 


    JSONObject jsonobj = null; 
    String alerttime=null; 
    String beforematch=null; 
    JSONArray jArray = null; 
    String starttime=null; 
try{ 

    jsonobj = new JSONObject (response); 
    jArray=jsonobj.getJSONArray("notifications"); 

    Log.i("Current Time",jArray+""); 
    Log.i("Current Time",getCurrentTime()); 
    String currentTime="2013-12-07 14:03"; 
    for(int i=0;i<jArray.length();i++){ 

     jsonobj=jArray.getJSONObject(i); 

     alerttime=jsonobj.getString("alert"); 
     starttime=jsonobj.getString("startTime"); 
     beforematch=jsonobj.getString("beforeMatchTime"); 

     if(alerttime.equals(currentTime)){ 

       Notification(starttime); 
       Log.i("Wintal", "wint"); 
     } 
    } 


} 
catch(JSONException e){ 
     Log.e("log_tag", "Error parsing data "+e.toString()); 
} 



Log.i("RESULT", jsonobj+""); 
Log.i("time", alerttime+""); 
Log.i("before Match",beforematch+""); 
} 

public void showAlertDialog(Context context, String title, String message, Boolean status){ 
    AlertDialog alertDialog = new AlertDialog.Builder(context).create(); 

    alertDialog.setTitle(title); 

    alertDialog.setMessage(message); 

    alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
     } 
    }); 
    alertDialog.show(); 


} 

public String getCurrentTime(){ 
    Calendar c= Calendar.getInstance(); 
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss "); 
    String strDate = sdf.format(c.getTime()); 
    return strDate; 
} 

public void alert() 
{ 
    Calendar calendar = Calendar.getInstance(); 

     calendar.set(Calendar.MONTH, 12); 
     calendar.set(Calendar.YEAR, 2013); 
     calendar.set(Calendar.DAY_OF_MONTH, 4); 

     calendar.set(Calendar.HOUR_OF_DAY, 1); 
     calendar.set(Calendar.MINUTE, 13); 
     calendar.set(Calendar.SECOND, 0); 
     calendar.set(Calendar.AM_PM,Calendar.PM); 

     Intent myIntent = new Intent(MainActivity.this, myReceiver.class); 
     PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0); 

     AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 
     alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent); 
} 



public void Notification(String s) 
{ 
     String ns = Context.NOTIFICATION_SERVICE; 

     NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); 

     int icon = R.drawable.notification_icon; 
     CharSequence tickerText = "Ready for Play time."; // ticker-text 
     long when = System.currentTimeMillis(); 
     Context context = getApplicationContext(); 
     CharSequence contentTitle = "Play Time"; 
     CharSequence contentText = "Your match is at "+s; 
     Intent notificationIntent = new Intent(this,ScheldueNotification .class); 
     PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
     Notification notification = new Notification(icon, tickerText, when); 
     notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 
     notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 
     // and this 

     mNotificationManager.notify(MY_NOTIFICATION_ID, notification); 

     notification.defaults |= Notification.DEFAULT_SOUND; 
     notification.vibrate = new long[] { 0, 100, 200, 300 }; 
     notification.flags |= Notification.FLAG_AUTO_CANCEL; 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

这就是我一个布尔值保存到编辑器

     try { 
          Log.i("noTeam Win tal","Log in hmar"); 

          userName=jsonobj.getString("userName"); 
          userID=jsonobj.getString("userID"); 

          noteamSaving[0]=userName; 
          noteamSaving[1]=userID; 

          Log.i("USerNameNN", userName+""); 
          Log.i("UserIDNN",userID+""); 

         } catch (JSONException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 

         Intent noteamshi=new Intent(Login.this,NoTeam.class); 
         noteamshi.putExtra("NoTeamSaving", noteamSaving); 
         startActivity(noteamshi); 
         MainActivity m=new MainActivity(); 
         m.saveLoggedIn(true); 
+0

你可以发布你的完整'LogCat'错误。它不完整。 –

+0

您是否正在初始化课堂级别的某些值? –

+0

@ Abishek。我已经更新:)感谢您的关注 – vcav

回答

0
MainActivity m=new MainActivity(); 

这可能不会做你认为它的代码。实例化这样的活动会绕过正常的活动生命周期。该错误是因为活动对象不知道该应用程序的包名是什么。将isLoggedIn()和saveLoggedIn(布尔值)移动到前台的活动中,当您要调用它们时,以便“this”引用引用正确启动的上下文。

如果你需要从几个活动访问这些方法,你可以改变这样的方法:

class LoginHelper { 
    public static boolean isLoggedIn(Context context) { 
     SharedPreferences sharedPreferences = PreferenceManager 
      .getDefaultSharedPreferences(context); 
     //The false represents the default value, if the variable is not stored 
     boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false); 
     return isLoggedIn; 
    } 

    public void saveLoggedIn(Context context, boolean value) { 
     SharedPreferences sharedPreferences = PreferenceManager 
      .getDefaultSharedPreferences(context); 
     Editor editor = sharedPreferences.edit(); 
     editor.putBoolean("isLoggedIn", value); 
     editor.commit(); 
    } 
} 

而一个指针传递给了上下文周边的当前活动。

    try { 
         Log.i("noTeam Win tal","Log in hmar"); 

         userName=jsonobj.getString("userName"); 
         userID=jsonobj.getString("userID"); 

         noteamSaving[0]=userName; 
         noteamSaving[1]=userID; 

         Log.i("USerNameNN", userName+""); 
         Log.i("UserIDNN",userID+""); 

        } catch (JSONException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 

        Intent noteamshi=new Intent(Login.this,NoTeam.class); 
        noteamshi.putExtra("NoTeamSaving", noteamSaving); 
        startActivity(noteamshi); 

        LoginHelper.saveLoggedIn(this, true); 

这是假设上述块来自android启动的活动,而不是您手动实例化的活动。

+0

LoginHelper.saveLoggedIn(this,true)。在这一行中,这不起作用 – vcav

+0

您是否创建了我发布的LoginHelper类并将它导入文件中?你得到的错误是什么? –

+0

谢谢,现在没事了。 :) – vcav