Inactive input connection - java

On running this app on an emulator it is performing as expected but when run on an actual android device it is not producing desired result and is showing the warning "getExtractedText on inactive InputConnection" in the logs. It's a chatbot application where i'm performing get request on an api with retrofit2 library.
package com.example.chatbot;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.inputmethodservice.Keyboard;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private RecyclerView chatBotRV;
private MessageAdapter messageAdapter;
private FloatingActionButton sendButton;
private EditText queryText;
private String USER_KEY = "USER";
private String BOT_KEY = "CHAT_BOT";
private Retrofit retrofit;
private APIservice apIservice;
private ArrayList<ChatModel> chatModelArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chatBotRV = findViewById(R.id.chat_bot_rv);
sendButton = findViewById(R.id.send_button);
queryText = findViewById(R.id.chat_ev);
chatModelArrayList = new ArrayList<>();
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!queryText.getText().toString().isEmpty()){
String message = queryText.getText().toString();
queryText.setText(null);
getMessage(message);
}else{
Toast.makeText(MainActivity.this, "Please enter your message :)", Toast.LENGTH_SHORT).show();
return;
}
}
});
messageAdapter = new MessageAdapter(chatModelArrayList, MainActivity.this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
chatBotRV.setLayoutManager(layoutManager);
chatBotRV.setAdapter(messageAdapter);
}
private void getMessage(String msg){
ChatModel chatModel_user = new ChatModel(msg, USER_KEY);
chatModelArrayList.add(chatModel_user);
messageAdapter.notifyDataSetChanged();
String url = "MY_API_URL"+msg;
String BASE_URL = "http://api.brainshop.ai/";
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
apIservice = retrofit.create(APIservice.class);
Call<MessageModel> call = apIservice.getMessage(url);
call.enqueue(new Callback<MessageModel>() {
#Override
public void onResponse(Call<MessageModel> call, Response<MessageModel> response) {
if(response.isSuccessful()){
MessageModel model = response.body();
chatModelArrayList.add(new ChatModel(model.getCnt(), BOT_KEY));
messageAdapter.notifyDataSetChanged();
}else{
Toast.makeText(MainActivity.this, "Some error on our side", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<MessageModel> call, Throwable t) {
chatModelArrayList.add(new ChatModel("Please revert your query", BOT_KEY));
messageAdapter.notifyDataSetChanged();
}
});
}
}

The InputConnection is overwhelmed by requests to clear the text. I tried modifying the code to check for text length before trying to clear it:
if (editText.length() > 0) {
editText.setText(null);
}
This helps mitigate the problem in that pressing the send button rapidly no longer causes the stream of InputConnectionWrapper warnings. However, this is still prone to problems when the user rapidly pressing the send button when the app is under sufficient load, etc.
There's another way to clear text: Editable.clear(). with this I don't get warnings at all:
(like getExtractedText on inactive InputConnection)
try this:
if (editText.length() > 0) {
editText.getText().clear();
}
Note that should you wish to clear all input state and not just the text (autotext, autocap, multitap, undo), you can use TextKeyListener.clear(Editable e).
if (editText.length() > 0) {
TextKeyListener.clear(editText.getText());
}

Related

Why does Firebase Auth work on emulator but not on real device

I have an app where the user can login using their mobile number. I used Firebase Auth for this. It works like a charm on the emulator.It runs fast and the app works well. But, when I try that on my Samsung M30s, it does not login. This is my code:
package com.sk.telegram.Activities.Login;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.firestore.FirebaseFirestore;
import com.sambhav2358.tinydb.TinyDB;
import com.sambhav2358.tinydb.TinyDBManager;
import com.sk.telegram.Activities.MainActivity;
import com.sk.telegram.Models.User;
import com.sk.telegram.Utils.KeyUtils;
import com.sk.telegram.Utils.PreferenceManager;
import com.sk.telegram.Utils.TextUtils;
import com.sk.telegram.databinding.ActivityLoginBinding;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class LoginActivity extends AppCompatActivity {
ActivityLoginBinding binding;
FirebaseAuth mAuth;
String mVerificationId;
PhoneAuthProvider.ForceResendingToken mResendToken;
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private String TAG = "LoginActivity";
boolean isLoggedIn = false;
Dialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityLoginBinding.inflate(getLayoutInflater());
FirebaseApp.initializeApp(this);
setContentView(binding.getRoot());
init();
binding.btnNext.setOnClickListener(v -> {
if (!isLoggedIn) {
isLoggedIn = true;
dialog = ProgressDialog.show(this,"","Please wait...");
startPhoneNumberVerification(getPhoneNumber());
}else {
dialog = ProgressDialog.show(this,"","Please wait...");
verifyPhoneNumberWithCode(mVerificationId,binding.otp.getText().toString());
}
});
}
private void init(){
binding.countryCodePicker.setAutoDetectedCountry(true);
// [START initialize_auth]
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
// [END initialize_auth]
// Initialize phone auth callbacks
// [START phone_auth_callbacks]
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
// This callback will be invoked in two situations:
// 1 - Instant verification. In some cases the phone number can be instantly
// verified without needing to send or enter a verification code.
// 2 - Auto-retrieval. On some devices Google Play services can automatically
// detect the incoming verification SMS and perform verification without
// user action.
Log.d(TAG, "onVerificationCompleted:" + credential);
signInWithPhoneAuthCredential(credential);
Toast.makeText(LoginActivity.this, "verified", Toast.LENGTH_SHORT).show();
}
#Override
public void onVerificationFailed(FirebaseException e) {
// This callback is invoked in an invalid request for verification is made,
// for instance if the the phone number format is not valid.
Log.w(TAG, "onVerificationFailed", e);
dialog.dismiss();
Toast.makeText(LoginActivity.this, "There was and error.", Toast.LENGTH_SHORT).show();
if (e instanceof FirebaseAuthInvalidCredentialsException) {
// Invalid request
} else if (e instanceof FirebaseTooManyRequestsException) {
// The SMS quota for the project has been exceeded
}
// Show a message and update the UI
}
#Override
public void onCodeSent(#NonNull String verificationId,
#NonNull PhoneAuthProvider.ForceResendingToken token) {
// The SMS verification code has been sent to the provided phone number, we
// now need to ask the user to enter the code and then construct a credential
// by combining the code with a verification ID.
Log.d("LoginActivity", "onCodeSent:" + verificationId);
//dismiss the dialog and update the UI
dialog.dismiss();
binding.phoneAuthLayout.setVisibility(GONE);
binding.otpLayout.setVisibility(VISIBLE);
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
}
};
// [END phone_auth_callbacks]
}
#Override
public void onStart() {
super.onStart();
}
private void startPhoneNumberVerification(String phoneNumber) {
// [START start_phone_auth]
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
// [END start_phone_auth]
}
private void verifyPhoneNumberWithCode(String verificationId, String code) {
// [START verify_with_code]
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithPhoneAuthCredential(credential);
// [END verify_with_code]
}
private void resendVerificationCode(String phoneNumber,
PhoneAuthProvider.ForceResendingToken token) {
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.setForceResendingToken(token) // ForceResendingToken from callbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
User mUser = new User("User" + new Random().nextInt(999999),task.getResult().getUser().getUid(),task.getResult().getUser().getPhoneNumber());
if (user != null){
FirebaseFirestore.getInstance().collection(KeyUtils.KEY_COLLECTION_USERS)
.document(task.getResult().getUser().getUid())
.set(mUser);
TinyDBManager tinyDB = TinyDB.getInstance(LoginActivity.this);
tinyDB.put("current_user",mUser);
new PreferenceManager(getApplicationContext()).putString("uid",mUser.getUserId());
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
} else {
// Sign in failed, display a message and update the UI
Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
Toast.makeText(LoginActivity.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
}
}
});
}
private String getPhoneNumber(){
return binding.countryCodePicker.getSelectedCountryCodeWithPlus() + " " + binding.number.getText().toString();
}
}
I also tried using test phone numbers but that doesn't work either

How to get JSON data from localhost in Android Studio (RESTful API)

So i've followed some tutorial on YT on how to get JSON object and JSON array of objects from website using URL and it worked. The code is below. Now, i've tried doing the exact same thing with URL of my localhost database, but it didn't work. I didn't get any errors or anything, and i have no idea what is the problem. I'm trying to do some RESTful API, in which the code in java is creating table with data in database, and it works perfectly, it's just that i cannot connect android app to it.
package com.example.motto_app;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
RadioGroup RG;
RadioButton bA, bB, bC, bD;
TextView tA, tB, tC, tD, tQ;
Button bN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//assigning variables to objects in layout
RG = findViewById(R.id.radioGroup);
bA = findViewById(R.id.answerAButton);
bB = findViewById(R.id.answerBButton);
bC = findViewById(R.id.answerCButton);
bD = findViewById(R.id.answerDButton);
tA = findViewById(R.id.answerAText);
tB = findViewById(R.id.answerBText);
tC = findViewById(R.id.answerCText);
tD = findViewById(R.id.answerDText);
tQ = findViewById(R.id.textQuestion);
bN = findViewById(R.id.NextButton);
//on-click listeners
bN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url ="http://localhost:8080/quiz";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
String question = "";
try {
JSONObject cityInfo = response.getJSONObject(0);
question = cityInfo.getString("question");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "Question: " + question, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Something wrong", Toast.LENGTH_SHORT).show();
}
});
queue.add(request);
}
});
bA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "AAA", Toast.LENGTH_SHORT).show();
}
});
bB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "BBB", Toast.LENGTH_SHORT).show();
}
});
bC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "CCC", Toast.LENGTH_SHORT).show();
}
});
bD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "DDD", Toast.LENGTH_SHORT).show();
}
});
}
}
Now i just want to add that the only thing that i've changed from the original code from YT is URL and variable names. The code worked perfectly with standard URL. Here is how my localhost looks: http://localhost:8080/quiz
By localhost do you mean the PC you're programming on, or the android device itself?
In the case you mean the Android device itself- you would never use a RESTful service here. You'd just make direct DB calls.
In the case you meant your PC- that isn't localhost. Not to the device. You need to use the actual IP of the device. Even if you're using an emulator, the emulator thinks its a separate machine and has its own IP address- localhost would only go to the emulator. And if its an actual device and not an emulator, you need to have your WIFI set up to allow traffic to that port (assuming your PC is on the same wifi network as your device. If not, its even more complicated).

Android Phone Number Verification in Firebase

I'm trying to create a login screen which will use Phone Number Authentication in Firebase. I wrote a code;
package com.example.logindeneme;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class PhoneLoginActivity extends AppCompatActivity {
private Button SendVerificationButton, VerifyButton;
private EditText InputPhoneNumber, InputVerificationCode;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks callbacks;
private FirebaseAuth mAuth;
private ProgressDialog loadingBar;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_login);
mAuth = FirebaseAuth.getInstance();;
SendVerificationButton = (Button) findViewById(R.id.send_ver_code_button);
VerifyButton = (Button)findViewById(R.id.verify_button);
InputPhoneNumber = (EditText) findViewById(R.id.phone_number_input);
InputVerificationCode = (EditText) findViewById(R.id.verification_code_input);
loadingBar = new ProgressDialog(this);
SendVerificationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String phoneNumber = InputPhoneNumber.getText().toString();
if(TextUtils.isEmpty(phoneNumber)){
Toast.makeText(PhoneLoginActivity.this, "Please enter your phone number first...", Toast.LENGTH_SHORT).show();
}
else{
loadingBar.setTitle("Phone Verification");
loadingBar.setMessage("please wait, while we are authenticating your phone...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
PhoneLoginActivity.this, // Activity (for callback binding)
callbacks); // OnVerificationStateChangedCallbacks
}
}
});
VerifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendVerificationButton.setVisibility(View.INVISIBLE);
InputPhoneNumber.setVisibility(View.INVISIBLE);
String verificationCode = InputVerificationCode.getText().toString();
if(TextUtils.isEmpty(verificationCode)){
Toast.makeText(PhoneLoginActivity.this, "Please write verification code first...", Toast.LENGTH_SHORT).show();
}
else{
loadingBar.setTitle("Verification Code");
loadingBar.setMessage("please wait, while we are verifying verification code...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, verificationCode);
signInWithPhoneAuthCredential(credential);
}
}
});
callbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
loadingBar.dismiss();
Toast.makeText(PhoneLoginActivity.this, "Invalid Phone Number, Please enter correct phone number with your country code...", Toast.LENGTH_SHORT).show();
SendVerificationButton.setVisibility(View.VISIBLE);
InputPhoneNumber.setVisibility(View.VISIBLE);
VerifyButton.setVisibility(View.INVISIBLE);
InputVerificationCode.setVisibility(View.INVISIBLE);
}
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
loadingBar.dismiss();
Toast.makeText(PhoneLoginActivity.this, "Code has been sent, please check and verify.", Toast.LENGTH_SHORT).show();
SendVerificationButton.setVisibility(View.INVISIBLE);
InputPhoneNumber.setVisibility(View.INVISIBLE);
VerifyButton.setVisibility(View.VISIBLE);
InputVerificationCode.setVisibility(View.VISIBLE);
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
loadingBar.dismiss();
Toast.makeText(PhoneLoginActivity.this, "Congratulations, you're logged in successfully...", Toast.LENGTH_SHORT).show();
SendUserToMainActivity();
}
else {
String message = task.getException().toString();
Toast.makeText(PhoneLoginActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(PhoneLoginActivity.this,MainActivity.class);
startActivity(mainIntent);
finish();
}
}
But when I try to enter my phone number and want a code, always says "Invalid phone number". However, if I enter my number and random verify code in Test Phone Numbers in Firebase, and if I enter in my app; it works.
My country uses "+90" phone code. So I tried +9053XXXXXXXX, +90 53X XXX XX XX, +90-53X-XXX-XX-XX and etc. but never works.
Where is my fault? Can you fix it ?
#Wicaledon
Go to your firebase console.
In Settings, enter your add your SHA-1 key.
This will definitely work.
To get SHA-1 key
https://developers.google.com/android/guides/client-auth

Getting Beacon Fence Using Awareness API it's take too much time and not accurate

This is my code for getting BeaconFence.It's take too much time and not provide accurate information i fetch two fence lost and found
//BeaconFenceActivity.java
import android.Manifest;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.azilen.awarenessapidemo.R;
import com.google.android.gms.awareness.Awareness;
import com.google.android.gms.awareness.fence.AwarenessFence;
import com.google.android.gms.awareness.fence.BeaconFence;
import com.google.android.gms.awareness.fence.FenceState;
import com.google.android.gms.awareness.fence.FenceUpdateRequest;
import com.google.android.gms.awareness.state.BeaconState;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.ResultCallbacks;
import com.google.android.gms.common.api.Status;
import java.util.Arrays;
import java.util.List;
public class BeaconFenceActivity extends AppCompatActivity {
private GoogleApiClient mGoogleApiClient;
private static final int PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 940;
private TextView txtBeacon;
private static final String BEACON_FENCE_KEY = "BEACON_FENCE_KEY";
private static final int BEACON_ZONE_IN = 2;
private static final int BEACON_ZONE_OUT = 1;
private PendingIntent mPendingIntent;
private BeaconFenceReceiver mBeaconFenceReceiver;
private ProgressDialog mProgress;
//Replace this with app's Google project name
private static final List<BeaconState.TypeFilter> BEACON_TYPE_FILTERS = Arrays.asList
(BeaconState.TypeFilter.with("awarenessapidemo-158205", "beacondemo"));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beacon_fence);
mProgress = new ProgressDialog(BeaconFenceActivity.this);
mProgress.setTitle("Geting Near Beacon");
mProgress.setMessage("Please wait..");
txtBeacon = (TextView) findViewById(R.id.txt_fence_beacon);
mGoogleApiClient = new GoogleApiClient.Builder(BeaconFenceActivity.this).addApi(Awareness.API).build();
mGoogleApiClient.connect();
mBeaconFenceReceiver = new BeaconFenceReceiver();
Intent intent = new Intent(BeaconFenceReceiver.BEACON_FENCE_RECEIVER_ACTION);
mPendingIntent = PendingIntent.getBroadcast(BeaconFenceActivity.this, 1, intent, 0);
}
#Override
protected void onStart() {
super.onStart();
getBeaconDetails();
registerReceiver(mBeaconFenceReceiver, new IntentFilter(BeaconFenceReceiver.BEACON_FENCE_RECEIVER_ACTION));
}
#Override
protected void onStop() {
super.onStop();
unregisterFences();
unregisterReceiver(mBeaconFenceReceiver);
}
private void getBeaconDetails() {
mProgress.show();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_ACCESS_FINE_LOCATION);
mProgress.hide();
} else {
AwarenessFence beaconFoundFence = BeaconFence.found(BEACON_TYPE_FILTERS);
AwarenessFence lostFence = BeaconFence.lost(BEACON_TYPE_FILTERS);
AwarenessFence orFence = AwarenessFence.or(lostFence, beaconFoundFence);
Awareness.FenceApi.updateFences(mGoogleApiClient,
new FenceUpdateRequest.Builder()
.addFence(BEACON_FENCE_KEY, orFence, mPendingIntent)
/* .addFence(BEACON_FENCE_KEY, beaconFoundFence, mPendingIntent)
.addFence(BEACON_FENCE_KEY, lostFence, mPendingIntent)
*/
.build()).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if (status.isSuccess()) {
Toast.makeText(BeaconFenceActivity.this, "Fence Registered", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(BeaconFenceActivity.this, "Fence Not Registered", Toast.LENGTH_SHORT).show();
}
}
});
mProgress.hide();
}
}
private void unregisterFences() {
Awareness.FenceApi.updateFences(
mGoogleApiClient,
new FenceUpdateRequest.Builder()
.removeFence(BEACON_FENCE_KEY)
.build()).setResultCallback(new ResultCallbacks<Status>() {
#Override
public void onSuccess(#NonNull Status status) {
Toast.makeText(BeaconFenceActivity.this, "Fence Removed", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(#NonNull Status status) {
Toast.makeText(BeaconFenceActivity.this, "Fence Not Removed", Toast.LENGTH_SHORT).show();
}
});
}
public void checkRestart(View view) {
getBeaconDetails();
registerReceiver(mBeaconFenceReceiver, new IntentFilter(BeaconFenceReceiver.BEACON_FENCE_RECEIVER_ACTION));
}
public class BeaconFenceReceiver extends BroadcastReceiver {
public static final String BEACON_FENCE_RECEIVER_ACTION = "com.azilen.awarenessapidemo.activities.fence.BeaconFenceReceiver.BEACON_FENCE_RECEIVER_ACTION";
#Override
public void onReceive(Context context, Intent intent) {
Log.e("Recived", "Received a Beacon Fence Broadcast");
FenceState fenceState = FenceState.extract(intent);
Log.e("FenceState Status:-", String.valueOf(fenceState.getFenceKey()));
if (TextUtils.equals(fenceState.getFenceKey(), BEACON_FENCE_KEY)) {
Log.e("FenceState:-", String.valueOf(fenceState.getCurrentState()));
switch (fenceState.getCurrentState()) {
case FenceState.TRUE: {
setBeaconState(BEACON_ZONE_IN);
Toast.makeText(BeaconFenceActivity.this, "You've entered the beacon zone!", Toast.LENGTH_SHORT).show();
Log.e("Beacon", "In Range");
break;
}
case FenceState.FALSE: {
setBeaconState(BEACON_ZONE_OUT);
Log.e("Beacon", "Out of Range");
Toast.makeText(BeaconFenceActivity.this, "You've Out of beacon Range!", Toast.LENGTH_SHORT).show();
break;
}
case FenceState.UNKNOWN: {
setBeaconState(FenceState.UNKNOWN);
Log.e("Beacon", "UNKNOWN");
Toast.makeText(BeaconFenceActivity.this, "Oops, Beacon status is unknown!", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
}
private void setBeaconState(int beaconState) {
if (beaconState == BEACON_ZONE_IN) {
txtBeacon.setText("You've entered the beacon zone!");
} else if (beaconState == BEACON_ZONE_OUT) {
txtBeacon.setText("You're not in the beacon zone..");
} else {
txtBeacon.setText("Oops, Beacon status is unknown!");
}
}
}
I Hope you can understand my question.
Thank you.
I can't tell you why it is taking to much time.
But in case of the accuracy you have to keep in mind,
that your position to the beacons is calculated from
the signal/signalstrength that beacons send and like every signal in
the microwave spectrum it gets reflected, blocked etc.
The environment in which you use your beacons could be
far from ideal to get the accuracy you want with the information
provided by the beacons.

how to implement post in retrofit

I have a login screen that take the username and password from user and validate it in the backend. Code i have written so far is below
package com.example.opinion;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;
public class Login extends Activity {
private Button login;
private Button reg;
private EditText uname;
private EditText pword;
public static final String BASE_URL = "http://192.168.0.105/";
public interface LoginApi{
#POST("login")
Call<HttpBinResponse> userLogin(#Body LoginData data);
}
static class HttpBinResponse {
String result;
}
public class LoginData {
String username;
String password;
public LoginData(String uname, String pword) {
this.username = uname;
this.password = pword;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login =(Button) findViewById(R.id.btnlogin);
reg =(Button) findViewById(R.id.btnregister);
uname = (EditText)findViewById(R.id.uname);
pword = (EditText)findViewById(R.id.pass);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = uname.getText().toString();
String pass = pword.getText().toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginData user = new LoginData(name, pass);
System.out.println(user.username+user.password);
LoginApi apiService = retrofit.create(LoginApi.class);
Call<HttpBinResponse> call = apiService.userLogin(user);
call.enqueue(new Callback<HttpBinResponse>() {
#Override
public void onResponse(Call<HttpBinResponse> call, Response<HttpBinResponse> response) {
int statusCode = response.code();
HttpBinResponse decodedResponse = response.body();
if (decodedResponse == null)
return;
// at this point the JSON body has been successfully parsed
System.out.println(decodedResponse.result);
}
#Override
public void onFailure(Call<HttpBinResponse> call, Throwable t) {
}
});
Intent it= new Intent(Login.this, Home.class);
startActivity(it);
}
});
reg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent it = new Intent(Login.this, Registration.class);
startActivity(it);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
}
In the above code LoginData class is used to attach the body for my post request.
HttpBinResponse class is for getting the response and store it in the result attribute. But i checked that my code is not returning any thing as the decodedResponse.result is null.
see this:
05-30 11:35:59.186 31176-31194/? I/OpenGLRenderer﹕ Initialized EGL,
version 1.4 05-30 11:36:08.783 31176-31176/com.example.opinion
I/System.out﹕ hkbffghjk 05-30 11:36:08.877
31176-31176/com.example.opinion I/System.out﹕ null
instead of null it should be a json object with key as result and its value.
Can anyone tell me how to get the proper response.
it seems like the url i'm creating is not created properly, either the body of the post request is not getting attached or some other problem.
i checked my sever logs and found that the request is reaching the server but nothing happens after that.

Categories