Я делаю спидометр и хочу иметь текстовое представление с высокой скоростью, чтобы узнать, как быстро он путешествовал, я попытался использовать общие настройки, но он сработает при запуске. Я поместил общие настройки в runnable, чтобы он быстро обновлялся и проверял, является ли текущая скорость выше максимальной, а если она хранится и отображается в текстовом представлении. Спасибо, Бен.Хранение с использованием общих настроек
import android.app.*;
import android.os.*;
import android.location.*;
import android.content.*;
import android.widget.*;
import java.text.*;
import android.graphics.*;
import android.graphics.drawable.*;
import android.view.*;
public class MainActivity extends Activity implements LocationListener
{
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
SharedPreferences prefs;
String topspeed;
@Override
protected void onCreate(Bundle savedInstanceestate)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged(null);
SharedPreferences prefs = this.getSharedPreferences("values", Context.MODE_PRIVATE);
String topspeed = prefs.getString("topspeed", "0");
TextView tv3 = (TextView) this.findViewById(R.id.tv3);
tv3.setText(topspeed);
}
@Override
public void onLocationChanged(Location p1)
{
TextView tv1 = (TextView) this.findViewById(R.id.mainTextView1);
if(p1 == null){
tv1.setText("-.- mp/h");
}
else{
float currentspeed = p1.getSpeed();
double mph_conversion = currentspeed * 2.2369362920544;
DecimalFormat precision = new DecimalFormat("0.0");
tv1.setText(precision.format(mph_conversion) + " mp/h");
double topspeed1 = Double.parseDouble(topspeed);
if(topspeed1 > mph_conversion){
SharedPreferences prefs = this.getSharedPreferences("values", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("topspeed", Double.toString(mph_conversion));
editor.apply();
}
else{
TextView tv3 = (TextView) this.findViewById(R.id.tv3);
SharedPreferences prefs = this.getSharedPreferences("values", Context.MODE_PRIVATE);
String topspeed = prefs.getString("topspeed", "0");
tv3.setText(topspeed);
}
}
}
@Override
public void onStatusChanged(String p1, int p2, Bundle p3)
{
// TODO: Implement this method
}
@Override
public void onProviderEnabled(String p1)
{
// TODO: Implement this method
}
@Override
public void onProviderDisabled(String p1)
{
TextView tv1 = (TextView) this.findViewById(R.id.mainTextView1);
tv1.setText("Turn on high GPS accuracy");
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime/1000);
int mins = secs/60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
}
};
public void bgcolour (View view){
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
}
public void tv2click (View v){
//start timer
timerValue = (TextView) findViewById(R.id.timerValue);
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
@Override
public void onBackPressed() {
android.os.Process.killProcess(android.os.Process.myPid());
// This above line close correctly
}
}
ошибка Logcat 03-09 20: 57: 29,690 Е/AndroidRuntime (23288): java.lang.RuntimeException: Невозможно создать экземпляр активности ComponentInfo {com.example/com.example.MainActivity}: Java. lang.NullPointerException: Попытка вызвать виртуальный метод «android.content.SharedPreferences android.content.Context.getSharedPreferences (java.lang.String, целый)» на нулевой ссылке на объект
Не могли бы вы разместить logcat .. – Lal
Содержимое объекта SharedPreferences автоматически обновляется при его редактировании. Не перезагружайте его после сохранения - на самом деле - старайтесь не перезагружать его вообще. – nekavally