我正在开发定期更新用户位置的应用程序。我提供服务并且有效,我通过广播发送结果
Intent i = new Intent("location_update");
i.putExtra("lat",location.getLatitude());
i.putExtra("lang",location.getLongitude());
sendBroadcast(i);
我也在这里成功收到了结果:
latData=String.valueOf(intent.getExtras().get("lat"));
langData=String.valueOf(intent.getExtras().get("lang"));
直到现在一切正常但是当我尝试通过这样的改造更新数据库lat& lang
user.lang= Float.parseFloat(langData);
它给我空指针异常,那是因为user.lang接收空值!此外,我确信100%我成功地从服务中接收数据,并确保我将数据传递到文本视图,并且它会定期工作和更改。无论如何,这是我的完整连接代码
<?php
include 'DB.php';
$data = file_get_contents("php://input");
$obj = json_decode($data);
$db = DB::getInstance();
header('Content-Type: application/json');
if(!isset($obj->{'lang'})){
print "{\"status\":0,\"message\":\"lang is Missing !\"}" ;
}else if(!isset($obj->{'lat'})){
print "{\"status\":0,\"message\":\"lat is Missing !\"}" ;
}else if(!isset($obj->{'username'})){
print "{\"status\":0,\"message\":\"username is Missing !\"}" ;
}else{
$lang = $obj->{'lang'};
$lat = $obj->{'lat'};
$username= $obj->{'username'};
$update = $db->update('users',
[
'lang' => $lang,
'lat' => $lat,
])->where('user_name','=',$username)->exec();
if($update){
print "{\"status\":1,\"message\":\"\"}" ;
} else {
print "{\"status\":0,\"message\":\"Error while updating\"}" ;
}
}
用户
public class User extends RealmObject{
@SerializedName("username")
public String username;
@SerializedName("password")
public String password;
@SerializedName("email")
public String email;
@SerializedName("lang")
public float lang;
@SerializedName("lat")
public float lat;
@SerializedName("id")
public int id;
public boolean isAdmin;}
主要活动
public class MainActivity2 extends AppCompatActivity {
private Button btn_start, btn_stop;
private TextView langLoc, latLoc,idupdate;
private BroadcastReceiver broadcastReceiver;
User user = new User();
String latData , langData;
@Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context,Intent intent) {
latData=String.valueOf(intent.getExtras().get("lat"));
langData=String.valueOf(intent.getExtras().get("lang"));
//langLoc.setText(langData);
//latLoc.setText(latData);
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
user.username= "mohamed";
//user.lang= Float.parseFloat(langData);
//user.lat= (float) 15.15;
/*IncomingData
User user = Session.getInstance().getUser();
if (user !=null){
tv_email.setText(user.username);
}*/
Webservice.getInstance().getApi().UpdateuserLocation(user).enqueue(new Callback<MainResponse>() {
@Override
public void onResponse(Call<MainResponse> call, Response<MainResponse> response) {
}
@Override
public void onFailure(Call<MainResponse> call, Throwable t) {
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if(broadcastReceiver != null){
unregisterReceiver(broadcastReceiver);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main22);
btn_start = (Button) findViewById(R.id.button);
btn_stop = (Button) findViewById(R.id.button2);
latLoc = (TextView) findViewById(R.id.lat);
langLoc = (TextView) findViewById(R.id.lang);
if(!runtime_permissions())
enable_buttons();
}
private void enable_buttons() {
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Service Start
Intent i =new Intent(getApplicationContext(),GPS_Service.class);
startService(i);
}
});
btn_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),GPS_Service.class);
stopService(i);
}
});
}
private boolean runtime_permissions() {
if(Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},100);
return true;
}
return false;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 100){
if( grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
enable_buttons();
}else {
runtime_permissions();
}
}
}
}
最后一件事,当我像那样制作用户静态数据时
user.username= "mohamed";
user.lang= (float) 15.155;
应用程序将数据发送到服务器并成功更新数据库。
答案 0 :(得分:0)
问题是您的字符串langData
在您的Receiver的onReceive
回调中初始化之前为空。您需要将parseFloat
调用移动到该调用中,以便初始化变量。然后,一旦变量被初始化,您将更新您的用户,然后激活该请求。
像这样:
@Override
public void onReceive(Context context,Intent intent) {
latData=String.valueOf(intent.getExtras().get("lat"));
langData=String.valueOf(intent.getExtras().get("lang"));
user.lang= Float.parseFloat(langData);
user.lat= Float.parseFloat(latData);
Webservice.getInstance().getApi().UpdateuserLocation(user).enqueue(new Callback<MainResponse>() {
@Override
public void onResponse(Call<MainResponse> call, Response<MainResponse> response) {
}
@Override
public void onFailure(Call<MainResponse> call, Throwable t) {
}
});
}