2015-08-15 3 views
0

У меня есть 36 кнопок (я показываю только 2 в этом вопросе) в действии Pim. каждая кнопка назначает/сохраняет ключ в моих общих предпочтениях, которые загружаются в действие S1m, но проблема в том, что он никогда не загружает мои ключи.Общие настройки никогда не загружаются в android

P1m

public class P1m extends Activity { 

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

    public void ten(View view) { 
     Toast toast = Toast.makeText(this, "Plan saved!", Toast.LENGTH_SHORT); 
     toast.show(); 
     SharedPreferences preferences = PreferenceManager 
       .getDefaultSharedPreferences(this); 
     SharedPreferences.Editor editor = preferences.edit(); 
     editor.putString("train", "p1m_10"); 
     editor.commit(); 
     finish(); 
     Intent intent = new Intent(this, MainMenu.class); 
     startActivity(intent); 
    } 

    public void fifteen(View view) { 
     Toast toast = Toast.makeText(this, "Plan saved!", Toast.LENGTH_SHORT); 
     toast.show(); 
     SharedPreferences preferences = PreferenceManager 
       .getDefaultSharedPreferences(this); 
     SharedPreferences.Editor editor = preferences.edit(); 
     editor.putString("train", "p1m_15"); 
     editor.commit(); 
     finish(); 
     Intent intent = new Intent(this, MainMenu.class); 
     startActivity(intent); 
    } 
} 

S1M

public class S1m extends Activity implements IBaseGpsListener { 
    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     Toast.makeText(this, "Service destroyed", Toast.LENGTH_LONG).show(); 
     timer.cancel(); 
    } 

    private TextView q; 
    private CountDownTimer timer; 
    private Vibrator mVibrator; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.sprint_ui); 
     LocationManager locationManager = (LocationManager) this 
       .getSystemService(Context.LOCATION_SERVICE); 
     locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 
       0, this); 
     this.updateSpeed(null); 

     CheckBox chkUseMetricUntis = (CheckBox) this 
       .findViewById(R.id.chkMetricUnits); 
     chkUseMetricUntis 
       .setOnCheckedChangeListener(new OnCheckedChangeListener() { 

        @Override 
        public void onCheckedChanged(CompoundButton buttonView, 
          boolean isChecked) { 
         // TODO Auto-generated method stub 
         S1m.this.updateSpeed(null); 
        } 
       }); 

     // LOAD SHARED PREF P1m//////////////////////////////////////////// 

     SharedPreferences preferences11 = PreferenceManager 
       .getDefaultSharedPreferences(this); 
     String name2 = preferences11.getString("train", ""); 

     if (name2.equals("p1m_10")) { 
      final Handler handler = new Handler(); 
      Timer timer = new Timer(); 
      timer.schedule(new TimerTask() { 
       private Vibrator mVibrator; 

       public void run() { 
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
        mVibrator.vibrate(1000 * 10);// sprint time vibration 
        // HANDLER 
        Runnable runnable = new Runnable() { 
         public void run() { 
          // calculate result1 
          TextView theFact = (TextView) findViewById(R.id.txtCurrentSpeed); 
          String shareFact = theFact.getText().toString(); 
          TextView theFact1 = (TextView) findViewById(R.id.result1); 
          theFact1.setText(String.valueOf(shareFact)); 
          // calculate result1 
         } 
        }; 
        handler.postDelayed(runnable, 3333); 
        // HANDLER END // 
        // HANDLER 
        Runnable runnable1 = new Runnable() { 
         public void run() { 
          // calculate result2 
          TextView theFact = (TextView) findViewById(R.id.txtCurrentSpeed); 
          String shareFact = theFact.getText().toString(); 
          TextView theFact1 = (TextView) findViewById(R.id.result2); 
          theFact1.setText(String.valueOf(shareFact)); 
          // calculate result2 
         } 
        }; 
        handler.postDelayed(runnable1, 6666); 
        // HANDLER END // 
        // HANDLER 
        Runnable runnable11 = new Runnable() { 
         public void run() { 
          // calculate result3 
          TextView theFact = (TextView) findViewById(R.id.txtCurrentSpeed); 
          String shareFact = theFact.getText().toString(); 
          TextView theFact1 = (TextView) findViewById(R.id.result3); 
          theFact1.setText(String.valueOf(shareFact)); 
          // calculate result3 
         } 
        }; 
        handler.postDelayed(runnable11, 9999); 
        // HANDLER END // 
        // warning 
        Runnable runnable111 = new Runnable() { 
         public void run() { 
          Toast.makeText(
            getBaseContext(), 
            "*you have 5 seconds left. get ready for the next sprint!*", 
            Toast.LENGTH_SHORT).show(); 
          mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
          mVibrator.vibrate(1000); 
         } 
        }; 
        handler.postDelayed(runnable111, 10000 + 60000 - 5000);// warning 
                      // after 
        // warning // 
       } 
      }, 5999, 10000 + 60000);// repeat after (+5.999s first run delay) 

     } else if (name2.equals("p1m_15")) { 
      final Handler handler = new Handler(); 
      Timer timer = new Timer(); 
      timer.schedule(new TimerTask() { 
       private Vibrator mVibrator; 

       public void run() { 
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
        mVibrator.vibrate(1000 * 15);// sprint time vibration 
        // HANDLER 
        Runnable runnable = new Runnable() { 
         public void run() { 
          // calculate result1 
          TextView theFact = (TextView) findViewById(R.id.txtCurrentSpeed); 
          String shareFact = theFact.getText().toString(); 
          TextView theFact1 = (TextView) findViewById(R.id.result1); 
          theFact1.setText(String.valueOf(shareFact)); 
          // calculate result1 
         } 
        }; 
        handler.postDelayed(runnable, 5000); 
        // HANDLER END // 
        // HANDLER 
        Runnable runnable1 = new Runnable() { 
         public void run() { 
          // calculate result2 
          TextView theFact = (TextView) findViewById(R.id.txtCurrentSpeed); 
          String shareFact = theFact.getText().toString(); 
          TextView theFact1 = (TextView) findViewById(R.id.result2); 
          theFact1.setText(String.valueOf(shareFact)); 
          // calculate result2 
         } 
        }; 
        handler.postDelayed(runnable1, 10000); 
        // HANDLER END // 
        // HANDLER 
        Runnable runnable11 = new Runnable() { 
         public void run() { 
          // calculate result3 
          TextView theFact = (TextView) findViewById(R.id.txtCurrentSpeed); 
          String shareFact = theFact.getText().toString(); 
          TextView theFact1 = (TextView) findViewById(R.id.result3); 
          theFact1.setText(String.valueOf(shareFact)); 
          // calculate result3 
         } 
        }; 
        handler.postDelayed(runnable11, 15000); 
        // HANDLER END // 
        // warning 
        Runnable runnable111 = new Runnable() { 
         public void run() { 
          Toast.makeText(
            getBaseContext(), 
            "*you have 5 seconds left. get ready for the next sprint!*", 
            Toast.LENGTH_SHORT).show(); 
          mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
          mVibrator.vibrate(1000); 
         } 
        }; 
        handler.postDelayed(runnable111, 15000 + 60000 - 5000);// warning 
                      // after 
        // warning // 
       } 
      }, 5999, 15000 + 60000);// repeat after (+5.999s first run delay) 

      // LOAD SHARED PREF P1m//////////////////////////////////////////// 
     } 
    } 

    public void finish() { 
     super.finish(); 
     System.exit(0); 
    } 

    private void updateSpeed(CLocation location) { 
     // TODO Auto-generated method stub 
     float nCurrentSpeed = 0; 

     if (location != null) { 
      location.setUseMetricunits(this.useMetricUnits()); 
      nCurrentSpeed = location.getSpeed(); 
     } 

     Formatter fmt = new Formatter(new StringBuilder()); 
     fmt.format(Locale.US, "%5.1f", nCurrentSpeed); 
     String strCurrentSpeed = fmt.toString(); 
     strCurrentSpeed = strCurrentSpeed.replace(' ', '0'); 

     String strUnits = "miles/hour"; 
     if (this.useMetricUnits()) { 
      strUnits = "meters/second"; 
     } 

     TextView txtCurrentSpeed = (TextView) this 
       .findViewById(R.id.txtCurrentSpeed); 
     txtCurrentSpeed.setText(strCurrentSpeed + " " + strUnits); 
    } 

    private boolean useMetricUnits() { 
     // TODO Auto-generated method stub 
     CheckBox chkUseMetricUnits = (CheckBox) this 
       .findViewById(R.id.chkMetricUnits); 
     return chkUseMetricUnits.isChecked(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     // TODO Auto-generated method stub 
     if (location != null) { 
      CLocation myLocation = new CLocation(location, 
        this.useMetricUnits()); 
      this.updateSpeed(myLocation); 
     } 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onProviderEnabled(String provider) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onGpsStatusChanged(int event) { 
     // TODO Auto-generated method stub 

    } 

} 

мои кнопки работают отлично, потому что всегда показывают Тост они назначены.

+0

В P1m вы создаете мгновенную переменную SharedPreferences каждый раз при создании кнопки. Создайте переменную SharedPreferences и Editor только один раз во время onCreate() и используйте их в методе onClick() для назначения пары ключ-значение. – adhithiyan

+0

@adhithiyan это не сработало – MaggotSauceYumYum

+0

вы будете удивлены, что я использую те же коды в других моих действиях (P15, S15), и он отлично работает, я просто копирую вставляемый код во всех них. его рабочий тон для p15, p20, p30, но не для p1m, p2m, p3m, p5m и p7m – MaggotSauceYumYum

ответ

0

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

public class Constants { 

    public static SharedPreferences prefs; 
    public static SharedPreferences.Editor editor; 

} 

Ваш P1m Класс

public class P1m extends Activity { 

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

public void ten(View view) { 
    Toast toast = Toast.makeText(this, "Plan saved!", Toast.LENGTH_SHORT); 
    toast.show(); 

    Constants.prefs = getActivity().getSharedPreferences("prefs", Context.MODE_PRIVATE); 
    Constants.editor = Constants.prefs.edit(); 

    Constants.editor.putString("train", "p1m_10"); 
    Constants.editor.commit(); 

    finish(); 
    Intent intent = new Intent(this, MainMenu.class); 
    startActivity(intent); 
} 

public void fifteen(View view) { 
    Toast toast = Toast.makeText(this, "Plan saved!", Toast.LENGTH_SHORT); 
    toast.show(); 

    Constants.editor.putString("train", "p1m_15"); 
    Constants.editor.commit(); 
    finish(); 
    Intent intent = new Intent(this, MainMenu.class); 
    startActivity(intent); 
    } 
} 

В классе S1m, получить значение как follwoing образом,

Constants.prefs = getActivity().getSharedPreferences("prefs", Context.MODE_PRIVATE); 
Constants.editor = Constants.prefs.edit(); 
String train = Constants.prefs.getString("train", "your default train"); 

После этого вы успешно получить свою ценность и получил улучшение в вашем коде.

+0

Здравствуйте, @Toxic Got решение или нет? –

+0

еще нет, пожалуйста, прочитайте мой комментарий ниже вопроса – MaggotSauceYumYum

+0

попробовал как мои ответы? –

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