2013-12-09 8 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 (логическое значение) внутри действия, которое является приоритетным, когда вы хотите вызвать их, чтобы «эта» ссылка ссылалась на правильно инициированный контекст.

Если вам необходимо получить доступ к этим методам из нескольких действий, которые Вы могли бы изменить методы, как это:

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); 

Предполагается, что вышеуказанный блок связан с активностью, с которой был запущен андроид, а не с созданием вручную.

+0

LoginHelper.saveLoggedIn (это, правда). В этой строке это не работает – vcav

+0

Вы создали класс LoginHelper, который я разместил, и импортировали его в файл, если бы вы его назвали? Какая ошибка вы получаете? –

+0

Спасибо, сейчас все в порядке. :) – vcav

Смежные вопросы