How can I use the data of an activity in another activity? - java

I want to send an SMS with location to the contact that the user has been saved. But I don't know how to do it. I am totally new to Android Studio, so I donĀ“t know how to write my code that it will work the way I want it.
Please, can you help me to do that?
This is the code of sending SMS:
Button sendBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}
protected void sendSMSMessage() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
// fixme: show explanation
// before requesting the permission again
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
} else {
sendSmsImpl();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
sendSmsImpl();
} else {
// fixme: explain that it can't send SMS without the permission
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
// !!! NOTE: you still need break inside switch/case
// even with curly braces
break;
}
}
}
private void sendSmsImpl() {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("+212xxx", null, "Je suis en danger, voici ma localisation : https://www.google.com/maps/search/?api=1&query=<lat>,<lng>", null, null);
//todo: use sentIntent argument of sendTextMessage to detect success/error
Toast.makeText(getApplicationContext(),
"SMS sent.", Toast.LENGTH_LONG).show();
}
And this the code of saving contact:
private int id;
private String phoneNo;
private String name;
// constructor
public ContactModel(int id, String name, String phoneNo) {
this.id = id;
this.phoneNo = validate(phoneNo);
this.name = name;
}
// validate the phone number, and reformat is necessary
private String validate(String phone) {
// creating StringBuilder for both the cases
StringBuilder case1 = new StringBuilder("+212");
StringBuilder case2 = new StringBuilder("");
// check if the string already has a "+"
if (phone.charAt(0) != '+') {
for (int i = 0; i < phone.length(); i++) {
// remove any spaces or "-"
if (phone.charAt(i) != '-' && phone.charAt(i) != ' ') {
case1.append(phone.charAt(i));
}
}
return case1.toString();
} else {
for (int i = 0; i < phone.length(); i++) {
// remove any spaces or "-"
if (phone.charAt(i) != '-' || phone.charAt(i) != ' ') {
case2.append(phone.charAt(i));
}
}
return case2.toString();
}
}
public String getPhoneNo() {
return phoneNo;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Related

Android send me twice the same message

I am working on a project for school and trying to send SMS to the user phone. The message is sent twice instead of once. How do I fix that problem?
Here is my code:
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =1 ;
EditText textphone;
String message;
String phoneNo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_r_e_g_i_s_t_e_r);
textphone=findViewById(R.id.phone);
c = findViewById(R.id.create1);
c.setOnClickListener(this);
c.setEnabled(false);
if(!checkPermission(Manifest.permission.SEND_SMS)){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}else{
c.setEnabled(true);
}
}
public void onClick(View v) {
if (v == c) {
sendmessage();}
now the method:
private void sendmessage() {
if(checkPermission(Manifest.permission.SEND_SMS))
{
message="Hello "+ username2.getText().toString()+",welcome to Chatime. Hope you enjoy from our app.";
phoneNo=textphone.getText().toString();
if(phoneNo.length()==0){
return;
}
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo,null,message,null,null);
Toast.makeText(getApplicationContext(), "Message Sent", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
public boolean checkPermission(String permission){
int check=ContextCompat.checkSelfPermission(this,permission);
return (check==PackageManager.PERMISSION_GRANTED);
}

How to initiate Agora client using push notification so video call can start between two users?

FCM with agora Implementation
I have down agora part but have to implement firebase console.
I have configured cm. Previously I was using sinch to have called between two apps but now want to change to calling with agoro but with the same concept. In that, we were sending a token to the server and according to that sinch use to handle the call.
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQ_ID = 22;
private static final String[] REQUESTED_PERMISSIONS = {
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private static final String TAG="Agora ";
private RtcEngine mRtcEmgine;
private FrameLayout mLocalContainer;
private RelativeLayout mRemoteContainer;
private SurfaceView mLocalView;
private SurfaceView mremoteView;
private ImageView mCallBtn;
private ImageView mMuteBtn;
private ImageView mSwitchCameraBtn;
private boolean mCallEnd;
private boolean mMuted;
private final IRtcEngineEventHandler mRtcHandler= new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel,final int uid, int elapsed) {
super.onJoinChannelSuccess(channel, uid, elapsed);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("agora","Join channel success, uid "+(uid &0xFFFFFFFFL));
}
});
}
#Override
public void onUserOffline(final int uid, int reason) {
super.onUserOffline(uid, reason);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("agora","User Offline, uid "+(uid &0xFFFFFFFFL));
removeRemoteVideo();
}
});
}
#Override
public void onRemoteVideoStateChanged(final int uid, int state, int reason, int elapsed) {
super.onRemoteVideoStateChanged(uid, state, reason, elapsed);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("agora","First reomte video decoded, uid "+(uid &0xFFFFFFFFL));
setupRemoteVideo(uid);
}
});
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initUI();
mLocalContainer=findViewById(R.id.local_video_view_container);
mRemoteContainer=findViewById(R.id.remote_video_view_container);
mCallBtn=findViewById(R.id.btn_call);
mCallBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallEnd){
startCall();
mCallEnd=false;
mCallBtn.setImageResource(R.drawable.btn_endcall);
}
else {
endCall();
mCallEnd=true;
mCallBtn.setImageResource(R.drawable.btn_startcall);
}
showButton(!mCallEnd);
}
});
mMuteBtn=findViewById(R.id.btn_mute);
mMuteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mMuted = !mMuted;
mRtcEmgine.muteLocalAudioStream(mMuted);
int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_unmute;
mMuteBtn.setImageResource(res);
}
});
mSwitchCameraBtn=findViewById(R.id.btn_switch_camera);
mSwitchCameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRtcEmgine.switchCamera();
}
});
if (checkSelfpermission(REQUESTED_PERMISSIONS[0]) &&
checkSelfpermission(REQUESTED_PERMISSIONS[1]) &&
checkSelfpermission(REQUESTED_PERMISSIONS[2]))
{
Log.e(TAG," true ");
initEngineAndJoinChannel();
}
else {
Log.e(TAG," false ");
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQ_ID) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED ||
grantResults[1] != PackageManager.PERMISSION_GRANTED ||
grantResults[2] != PackageManager.PERMISSION_GRANTED) {
Log.e(TAG,"Need permissions " + Manifest.permission.RECORD_AUDIO +
"/" + Manifest.permission.CAMERA + "/" + Manifest.permission.WRITE_EXTERNAL_STORAGE);
finish();
return;
}
initEngineAndJoinChannel();
}
}
#Override
protected void onDestroy(){
super.onDestroy();
if (!mCallEnd){
leaveChannel();
}
RtcEngine.destroy();
}
private void initUI() {
Log.e(TAG," UI ");
mLocalContainer=findViewById(R.id.local_video_view_container);
mRemoteContainer=findViewById(R.id.remote_video_view_container);
mCallBtn=findViewById(R.id.btn_call);
mMuteBtn=findViewById(R.id.btn_mute);
mSwitchCameraBtn=findViewById(R.id.btn_switch_camera);
}
private void initEngineAndJoinChannel() {
initializeEngine();
setupVideoConfig();
setupLocalVideo();
joinChannel();
}
private void setupVideoConfig() {
Log.e(TAG,"running 2");
mRtcEmgine.enableVideo();
mRtcEmgine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(
VideoEncoderConfiguration.VD_640x360,
VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
VideoEncoderConfiguration.STANDARD_BITRATE,
VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT
));
}
private void setupLocalVideo() {
Log.e(TAG,"running 3");
mRtcEmgine.enableVideo();
mLocalView=RtcEngine.CreateRendererView(getBaseContext());
mLocalView.setZOrderMediaOverlay(true);
mLocalContainer.addView(mLocalView);
VideoCanvas localVideoCanvas = new VideoCanvas(mLocalView, VideoCanvas.RENDER_MODE_HIDDEN,0);
mRtcEmgine.setupLocalVideo(localVideoCanvas);
}
private void setupRemoteVideo(int uid) {
int count = mRemoteContainer.getChildCount();
View view = null;
for(int i = 0; i < count; i++) {
View v= mRemoteContainer.getChildAt(i);
if (v.getTag() instanceof Integer && ((int)v.getTag()) == uid) {
view = v;
}
}
if (view != null) {
return;
}
mremoteView = RtcEngine.CreateRendererView(getBaseContext());
mRemoteContainer.addView(mremoteView);
mRtcEmgine.setupRemoteVideo(new VideoCanvas(mremoteView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
mremoteView.setTag(uid);
}
private void initializeEngine() {
Log.e(TAG,"running 1");
try {
mRtcEmgine=RtcEngine.create(getBaseContext(),getString(R.string.agora_app_id),mRtcHandler);
}
catch (Exception e) {
Log.e(TAG,Log.getStackTraceString(e));
throw new RuntimeException("NEED TO check rtc sdk fatal error \n"+Log.getStackTraceString(e));
}
}
private void removeRemoteVideo() {
if (mremoteView != null) {
mRemoteContainer.removeView(mremoteView);
}
mremoteView = null;
}
private void joinChannel() {
Log.e(TAG,"running 4");
String token = getString(R.string.agora_access_token);
if (TextUtils.isEmpty(token)) {
token = null;
}
mRtcEmgine.joinChannel(token,"demochannel", "", 0);
}
private void leaveChannel() {
mRtcEmgine.leaveChannel();
}
/* public void onLocalAudioMuteClicked(View view) {
mMuted = !mMuted;
mRtcEmgine.muteLocalAudioStream(mMuted);
int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_unmute;
mMuteBtn.setImageResource(res);
}*/
/* public void onSwitchClicked(View view) {
mRtcEmgine.switchCamera();
}*/
/* public void onCallClicked(View view) {
if (mCallEnd){
startCall();
mCallEnd = false;
mCallBtn.setImageResource(R.drawable.btn_endcall);
}
else {
endCall();
mCallEnd = true;
mCallBtn.setImageResource(R.drawable.btn_startcall);
}
showButton(!mCallEnd);
}*/
private void startCall() {
setupLocalVideo();
joinChannel();
}
private void endCall() {
removeLocalVideo();
removeRemoteVideo();
leaveChannel();
}
private void removeLocalVideo() {
if (mLocalView != null) {
mLocalContainer.removeView(mLocalView);
}
mLocalView = null;
}
private void showButton(boolean show) {
int visibilty = show ? View.VISIBLE : View.GONE;
mMuteBtn.setVisibility(visibilty);
mSwitchCameraBtn.setVisibility(visibilty);
}
private Boolean checkSelfpermission(String permission) {
if (ContextCompat.checkSelfPermission(this,permission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, MainActivity.PERMISSION_REQ_ID);
return false;
}
return true;
}
}

How to determine why my Android application keeps stopping?

I'm having a problem with my application. The application is supposed to send a message using volume key buttons on the phone. The problem is that it keeps stopping and I do not know if it works. Here is the code, I also added some wake lock in order for my app to stay active even when phone is locked.
public class MainActivity extends Activity {
private final static int SEND_SMS_PERMISSION_REQUEST_CODE = 111;
private Button sendMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
setContentView(R.layout.activity_main);
sendMessage = findViewById(R.id.send_message);
final EditText phone = findViewById(R.id.phone_no);
final EditText message = findViewById(R.id.message);
sendMessage.setEnabled(false);
if (checkPermission(Manifest.permission.SEND_SMS)) {
sendMessage.setEnabled(true);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE);
}
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
sendMessage.setEnabled(true);
return true;
} else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)) {
sendMessage.setEnabled(true);
return true;
} else
return super.onKeyDown(keyCode, event);
}
private boolean checkPermission(String permission) {
int checkPermission = ContextCompat.checkSelfPermission(this, permission);
return checkPermission == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case SEND_SMS_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
sendMessage.setEnabled(true);
}
break;
}
}
}
Right now your code is not sending any messages when you press the volume key nor when you release it. You need to add this to your code:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
...
}
Also, you're missing n opening bracket on the final else of your onKeyDown()

checking for an explicit permission?

in my code the permission log will be display but the phone number is not visible in toast
how to get simcard number in the toast message with the use of explicit permission
public class MainActivity extends AppCompatActivity {
String TAG = "PhoneActivityTAG";
Activity activity = MainActivity.this;
String wantPermission = Manifest.permission.READ_PHONE_STATE;
private static final int PERMISSION_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!checkPermission(wantPermission)) {
requestPermission(wantPermission);
} else {
Log.d(TAG, "Phone number: " + getPhone());
}
}
private String getPhone() {
TelephonyManager phoneMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(activity, wantPermission) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "my phone no is:-" + phoneMgr,Toast.LENGTH_LONG).show();
}
return phoneMgr.getLine1Number();
}
private void requestPermission(String permission){
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)){
Toast.makeText(activity, "Phone state permission allows us to get phone number. Please allow it for additional functionality.", Toast.LENGTH_LONG).show();
}
ActivityCompat.requestPermissions(activity, new String[]{permission},PERMISSION_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Phone number: " + getPhone());
} else {
Toast.makeText(activity,"Permission Denied. We can't get phone number.", Toast.LENGTH_LONG).show();
}
break;
}
}
private boolean checkPermission(String permission){
if (Build.VERSION.SDK_INT >= 23) {
int result = ContextCompat.checkSelfPermission(activity, permission);
return result == PackageManager.PERMISSION_GRANTED;
} else {
return true;
}
}
}
please help me
how can i get phone number in the display toast?
checkout the answer written here.
some correction in code
private String getPhone() {
TelephonyManager phoneMgr = (TelephonyManager) Context.getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(activity, wantPermission) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "my phone no is:-" + phoneMgr,Toast.LENGTH_LONG).show();
}
return phoneMgr.getLine1Number();
}

Can't update location periodcally to server

I am developing application which update user's location periodically. I make the service and it worked, I send results by broadcast
Intent i = new Intent("location_update");
i.putExtra("lat",location.getLatitude());
i.putExtra("lang",location.getLongitude());
sendBroadcast(i);
I am also received result successfully here:
latData=String.valueOf(intent.getExtras().get("lat"));
langData=String.valueOf(intent.getExtras().get("lang"));
till now everything worked fine but when iam try to update database lat&lang by retrofit like that
user.lang= Float.parseFloat(langData);
it gives me null pointer exception and that's because user.lang receive null value! Also I am sure 100% I receive data from the service successfully and to get certain I pass the data to text view and it worked and changed periodically. Whatever, this is my full code for connection
<?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\"}" ;
}
}
User
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;}
Main Activity
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();
}
}
}
}
Last thing, when I make the data of user static like that
user.username= "mohamed";
user.lang= (float) 15.155;
the app send the data to server and database updated successfully.
The problem is that your string langData is null until initialized in the onReceive callback of your Receiver. You need to move your parseFloat call into that so that the variable has been initialized. Then, once the variables are initialized, you would update your user and then fire off the request.
Like so:
#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) {
}
});
}

Categories