2012-06-02 8 views
1

활동간에 스 와이프하는 동안 내 활동 상태를 저장하려고하지만 할 수 없습니다. 어떤 것은 구원 받았고 다른 것들은 구원받지 못했습니다. 나는 제스처 리스너와 어떻게 든해야한다고 생각합니다.하지만 나는 확신하지 못합니다.활동 상태가 저장되지 않았습니다.

다른 액티비티로 스 와이프 한 다음이 액티비티로 돌아갈 때 - 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

활동을 백그라운드로 보낼 때 백그라운드에서 Async 작업을 실행하지 마십시오. 귀하의 활동은 더 이상 귀하의 활동에 대한 참조가 없도록 언제든지 종료 할 수 있습니다. 당신이 Activity.onRetainNonConfigurationInstance에 모습을 가질 수 상태의 보존에 관한

() 귀하의 코멘트에 대한

+0

덕분에 나는 BG의 비동기 실행하도록해야하지만. 나는 사용자가 다른 활동에서 다른 것을 볼 수있는 동안 자신의 일을 계속할 수있는 활동이 필요합니다. 나는 생각하기에 그것이 저장되지 않은 이유는 왼쪽 또는 오른쪽으로 쓸어 넘기 떄문에 이전에 실행했던 것과 동일한 활동으로 돌아 가기보다는 새로운 활동을 시작했기 때문이라고 생각합니다. 그것은 의미가 있습니까? – Yosi199

+0

서비스를 사용하여 백그라운드 작업을 수행하고 인 텐트를 사용하여 데이터를 다시 액티비티로 보낼 수 있습니다. – Moritz

관련 문제