2012-06-02 44 views
1

我想在活动之间滑动时保存我的活动状态,但我不能。有些东西被保存了,其他的都没有了。我认为它必须以某种方式来处理我所支持的gestureListener,但我不确定。活动状态未保存

当我滑动到不同的活动,然后回到这一个 - AsyncTask仍在运行,处理程序仍在更新GUI,但是,我在此活动中显示的视图和按钮都在其初始组态。

我做错了什么?

public class Main extends Activity implements OnClickListener, 
     SimpleGestureListener { 
    /** Called when the activity is first created. */ 


    static String checkedIN = ""; 

    private int hoursSum; 
    private int minutesSum; 
    static int dayIs; 
    static String madeSoFar = ""; 

    static int hoursCount = 0; 
    static String formattedSeconds = ""; 
    static String formattedMinutes = ""; 
    public static NumberFormat formatter = new DecimalFormat("#0.00"); 
    static boolean killcheck = false; 
    static String time = ""; 
    static Handler mHandler; 

    private boolean clicked = false; 
    private boolean wasShift = false; 
    static String startString; 
    static String finishString; 
    private SimpleGestureFilter detector; 
    private Typeface tf, tf2, roboto; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     setContentView(R.layout.main); 

     // **************** Set Fonts ************** 
     roboto = Typeface.createFromAsset(getAssets(), "fonts/robotothin.ttf"); 
     tf = Typeface.createFromAsset(getAssets(), "fonts/Advert.ttf"); 
     tf2 = Typeface.createFromAsset(getAssets(), "fonts/passion.ttf"); 

     // **************** Gesture implementation ************ 

     detector = new SimpleGestureFilter(this, this); 

     // **************** Date and Time Objects ************* 

     final Date date = new Date(); 
     final Date today = Calendar.getInstance().getTime(); 
     DateFormat DF = new SimpleDateFormat("dd/MM/yyyy"); 
     final String DateInString = DF.format(today); 
     String myString = DateFormat.getDateInstance().format(date); 
     final TextView dateDisplay = (TextView) findViewById(R.id.dateDisplay); 
     dateDisplay.setText(myString); 

     final DBAdapter DB = new DBAdapter(this); 

     // ************* Apply custom fonts *************** 

     TextView Title = (TextView) findViewById(R.id.textView2); 
     Title.setTypeface(tf); 
     final TextView Author = (TextView) findViewById(R.id.textView3); 
     Author.setTypeface(roboto); 
     TextView Current = (TextView) findViewById(R.id.textView1); 
     Current.setTypeface(roboto); 
     DigitalClock DG = (DigitalClock) findViewById(R.id.digitalClock1); 
     DG.setTypeface(roboto); 
     TextView dater = (TextView) findViewById(R.id.date); 
     dater.setTypeface(roboto); 
     TextView dateDisp = (TextView) findViewById(R.id.dateDisplay); 
     dateDisp.setTypeface(roboto); 
     CheckedTextView CV = (CheckedTextView) findViewById(R.id.radioButton1); 
     CV.setTypeface(roboto); 

     // *************************************************// 

     final Button checkIn = (Button) findViewById(R.id.CheckIn); 
     checkIn.setTypeface(roboto); 
     CheckedTextView check = (CheckedTextView) findViewById(R.id.radioButton1); 
     Boolean enable = false; 
     check.setEnabled(enable); 

     mHandler = new Handler() { 

      public void handleMessage(Message msg) { 

       time = "Time: " + hoursCount + ":" + formattedMinutes + ":" 
         + formattedSeconds + " Money: " + madeSoFar; 

       Author.setText(time); 
      } 
     }; 

     // **************** Click Listener for first Check In Button 

     checkIn.setOnClickListener(new OnClickListener() { 

      int startHours; 
      int startMinutes; 
      int finishHours; 
      int finishMinutes; 

      @Override 
      public void onClick(View v) { 
       // Check Out 
       if (clicked == true) { 
        killcheck = true; 
        checkedIN = "Check In"; 
        checkIn.setText(checkedIN); 
        finishHours = Utility.getHoursTime(); 
        finishMinutes = Utility.getMinutesTime(); 
        finishString = Integer.toString(Utility.getHoursTime()) 
          + ":" + Integer.toString(Utility.getMinutesTime()) 
          + " -"; 

        clicked = false; 
        wasShift = true; 

        hoursSum = finishHours - startHours; 
        minutesSum = finishMinutes - startMinutes; 

        // Check In 
       } else if (clicked == false) { 
        checkedIN = "Check Out"; 
        checkIn.setText(checkedIN); 
        killcheck = false; 
        new ShiftProgress().execute(); 
        startHours = Utility.getHoursTime(); 
        startMinutes = Utility.getMinutesTime(); 
        startString = Integer.toString(Utility.getHoursTime()) 
          + ":" + Integer.toString(Utility.getMinutesTime()) 
          + " -"; 

        String s = "In Shift "; 
        CheckedTextView radio = (CheckedTextView) findViewById(R.id.radioButton1); 
        radio.setText(s); 
        clicked = true; 

       } 
      } 
     }); 

     Button addShift = (Button) findViewById(R.id.addShift); 
     addShift.setTypeface(tf2); 

     // **************** On click listener for adding a shift 

     addShift.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       if (wasShift == true) { 

        changeDateToString(DateInString); 

        DB.open(); 
        final Cursor cursor = DB.getAllShifts(); 
        startManagingCursor(cursor); 
        cursor.moveToLast(); 
        int count = cursor.getPosition(); 
        final int position = count + 2; 
        cursor.moveToNext(); 

        GregorianCalendar GC = new GregorianCalendar(); 

        DB.addToDBTotal(DateInString, "Money: " + madeSoFar, 
          hoursSum, minutesSum, 
          Utility.getDay(GC.get(Calendar.DAY_OF_WEEK)), 
          position, startString, finishString); 

        DBAdapter.close(); 
        wasShift = false; 

        printAny(getApplicationContext(), "Added to Shifts", 
          Toast.LENGTH_SHORT); 

       } else { 
        printAny(getApplicationContext(), "Please Check In First", Toast.LENGTH_SHORT); 

       } 

      } 
     }); 

    } 



    // **************** METHOD DECLERATIONS **** 

    public void viewShifts() { 

     Intent myIntent = new Intent(Main.this, Shifts.class); 

     startActivity(myIntent); 
    } 

    public void changeDateToString(String s) { 

     Utility.INSTANCE.setDate(s); 
    } 

    public void changeDurationToString(String s) { 

     Utility.INSTANCE.setDuration(s); 
    } 

    public void printAny(Context c, CharSequence s, int i) { 

     Context context = c; 
     CharSequence text = s; 
     final int duration = i; 

     Toast toast = Toast.makeText(context, text, duration); 
     toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0); 
     toast.show(); 

    } 

     @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     MenuInflater inflater = getMenuInflater(); 
     inflater.inflate(R.menu.menu, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle item selection 
     switch (item.getItemId()) { 
     case R.id.exit: 
      System.exit(1); 
      DBAdapter.close(); 

      return true; 
     case R.id.view: 
      viewShifts(); 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
     } 
    } 

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

    } 

    @Override 
    public void onSwipe(int direction) { 

     Intent intent = new Intent(); 

     switch (direction) { 

     case SimpleGestureFilter.SWIPE_RIGHT: 
      intent.setClass(this, Shifts.class); 
      startActivity(intent); 
      break; 
     case SimpleGestureFilter.SWIPE_LEFT: 
      intent.setClass(this, Shifts.class); 
      startActivity(intent); 
      break; 

     } 

    } 

    @Override 
    public boolean dispatchTouchEvent(MotionEvent me) { 
     this.detector.onTouchEvent(me); 
     return super.dispatchTouchEvent(me); 
    } 

    @Override 
    public void onDoubleTap() { 
     // TODO Auto-generated method stub 

    } 

    public class ShiftProgress extends AsyncTask<String, Integer, String> { 

     @Override 
     protected String doInBackground(String... params) { 

      int count = 0; 
      int seconds = 0; 
      int minutesTime = 0; 
      int minutesCount = 1; 

      for (;;) { 
       if (seconds % 60 == 0) { 
        minutesTime = count/60; 
        seconds = 0; 

       } 

       if (seconds < 10) { 

        formattedSeconds = String.format("%02d", seconds); 

       } 

       else if (seconds >= 10) { 

        formattedSeconds = String.valueOf(seconds); 

       } 

       if (minutesTime < 10) { 

        formattedMinutes = String.format("%02d", minutesTime); 

       } 

       else if (minutesTime >= 10) { 

        formattedMinutes = String.valueOf(minutesTime); 

       } 

       if (minutesTime % 60 == 0) { 
        hoursCount = minutesCount/60; 
        minutesTime = 0; 

       } 
       double sal = 40; 
       double SEC = 3600; 
       double salper = count * (sal/SEC); 
       madeSoFar = String.valueOf(formatter.format(salper)); 

       try { 
        mHandler.obtainMessage(1).sendToTarget(); 
        Thread.sleep(1000); 
        seconds++; 
        count++; 

       } catch (InterruptedException e) { 

        e.printStackTrace(); 
       } 
       if (killcheck) { 
        break; 

       } 
      } 

      // int length = count /360; 
      return null; 
     } 

     protected void onProgressUpdate(Integer... progress) { 
     } 

     protected void onPostExecute(Long result) { 
     } 

    } 

    @Override 
    public void onSaveInstanceState() { 
     // TODO Auto-generated method stub 
     Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG); 
    } 

    @Override 
    public void onRestoreInstanceState(Bundle savedInstanceState) { 
     super.onRestoreInstanceState(savedInstanceState); 
     // Restore UI state from the savedInstanceState. 
     // This bundle has also been passed to onCreate. 

     checkedIN = savedInstanceState.getString("checkIN"); 
     clicked = savedInstanceState.getBoolean("button"); 
     Toast.makeText(this, "Activity state Restored", Toast.LENGTH_LONG); 
    } 

    @Override 
    public void onPause(Bundle b) { 
     // TODO Auto-generated method stub 
     b.putString("checkIN", checkedIN); 
     b.putBoolean("button", clicked); 
     Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG); 
     super.onPause(); 
    } 

    @Override 
    public void onSaveInstanceState(Bundle outState) { 
     outState.putString("checkIN", checkedIN); 
     outState.putBoolean("button", clicked); 

     Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG); 

     // etc. 
     super.onSaveInstanceState(outState); 
    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     Toast.makeText(this, "Activity is getting killed", Toast.LENGTH_LONG) 
       .show(); 
    } 

} 

回答

0

当您的活动发送到后台时,您不应该让后台在后台运行异步任务。你的活动可以在任何时候退出,这样你就不会再参考你的活动了。

关于的保存状态,你可以看看Activity.onRetainNonConfigurationInstance()

+0

感谢您的评论,虽然我必须让在BG异步运行。我需要该活动继续做她的事情,而用户能够在其他活动中查看其他内容。 顺便说一句,我认为它没有被保存的原因是因为,当我向左或向右滑动时 - 然后我开始一个新的活动,而不是回到之前运行的同一个活动。这有意义吗? – Yosi199

+0

您可以使用服务来执行后台操作,并使用意图将数据发送回活动。 – Moritz