【问题标题】:Storing using shared preferences使用共享首选项存储
【发布时间】:2016-03-09 18:10:33
【问题描述】:

我正在制作一个速度计,并希望有一个最高速度的文本视图,以查看手机的行驶速度,我尝试使用共享首选项,但它在启动时崩溃。我已将共享首选项放入可运行文件中,以便它快速更新并检查当前速度是否高于最高速度,是否将其存储并显示在文本视图中。谢谢本。

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 E/AndroidRuntime(23288): java.lang.RuntimeException: 无法实例化活动 ComponentInfo{com.example/com.example.MainActivity}: java.lang.NullPointerException: 尝试调用虚拟方法' android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' 在空对象引用上

【问题讨论】:

  • 能否请您发布日志猫..
  • SharedPreferences 对象的内容会在您编辑时动态更新。保存后不要重新加载它 - 实际上 - 尽量不要重新加载它。

标签: android sharedpreferences


【解决方案1】:

如果您要立即读取存储的首选项,请不要使用apply()。请改用commit()。这个调用在主线程上运行,而不是像apply() 这样的背景,但如果你只是存储一小段数据,你应该不会注意到任何区别。这是有关它的更多信息。 SharedPreferences.Editor

【讨论】:

    【解决方案2】:

    在 Activity 上调用构造函数之前,您不能运行这两行代码:

    SharedPreferences prefs = this.getSharedPreferences("values", Context.MODE_PRIVATE);
    String topspeed = prefs.getString("topspeed", "0");
    

    例如,您可以通过在此处定义变量来修复它,但在 onCreate() 方法中设置它们。

    【讨论】:

    • 您好,我按照您所说的那样更改了代码,现在它在开始时停止了崩溃,并且文本视图中显示“0”,但是当 GPS 信号连接时,它现在崩溃了。
    • 如果您自己没有弄清楚,我建议为此发布一个单独的问题。
    猜你喜欢
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    相关资源
    最近更新 更多