Not Getting Resposne when making Request using volley - java

I'm trying to make a request to server using volley and check the returned value contains specific value or not. It works when I use separate class and call from Mainactivity using intent in onCreate.
But I would like to make a call manually when button is clicked from fragment but when button is clicked nothing happens.
Here is my code:
mCeload = (FloatingActionButton) view.findViewById(R.id.Update);
mCeload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "https://cmprc.edu.np/batch/update.json";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response != null ) {
boolean resp = response.contains("1");
if (!resp) {
Toast.makeText(getActivity(), "Contacts are Updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "No Updates Availaible", Toast.LENGTH_SHORT).show();
}
}
}
}, new com.android.volley.Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
Toast.makeText(getActivity(), "You clicked the Button", Toast.LENGTH_SHORT).show();
}
});
I"m positive that button is clicked since I"m getting last toast message but before that nothing happens and I"m not getting any Toast of whether response was positive or negative.
Also How do i get the response as string and store in local database such that I could compare the saved value with new one when user check for updates and if both value matches then show Toast of no updates available and if not then show updates available.
Thanks in advance.

Add your request on the RequestQueue like this way:
final RequestQueue requestQueue = Volley.newRequestQueue(getActivity);
String url = "https://cmprc.edu.np/batch/update.json";
// Initialize a new StringRequest
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response != null ) {
boolean resp = response.contains("1");
if (!resp) {
Toast.makeText(getActivity(), "Contacts are Updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "No Updates
Availaible", Toast.LENGTH_SHORT).show();
} }
},
new Response.ErrorListener() {
#Override
public void
onErrorResponse(VolleyError error) {
volleyError.printStackTrace();
}
}
);
// Add StringRequest to the RequestQueue
requestQueue.add(stringRequest);

Related

How to return or reuse response value of Volley library in android studio?

public class MainActivity extends AppCompatActivity {
private static final String url = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=1";
private static String data ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
data=data + response.substring(0);
Log.d("CODE1",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,"Something went wrong",Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
TextView text = (TextView) findViewById(R.id.text_view);
text.setText(data);
}
}
I am trying to use the "response" value of onResponse function at the end of the onCreate function. As you can see data is assigned to TEXTVIEW but it is not displayed. How can we use the data in response to pass to other data structure and then use for other work?
use like this:
data=data + response.substring(0);
Log.d("CODE1",response);
text.setText(data);
Because, this line(setText) runs before you send request. You displayed empty data.
Move the setText method into onResponse
Your code will be like this:
TextView text = (TextView) findViewById(R.id.text_view);
final StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("CODE1",response);
text.setText(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,"Something went wrong",Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);

Not Getting Response of USSD Code in Android

I want to dial and get the dialed USSD code response. Here is my code. but when I run it doesn't show any response on the toast.
private void ussdResponse(String completeCode) {
TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE}, requestCode);
ActivityCompat.requestPermissions(MainActivity.this , new String[]{Manifest.permission.READ_PHONE_STATE},requestCode);
return;
}
manager.sendUssdRequest(completeCode, new TelephonyManager.UssdResponseCallback() {
#Override
public void onReceiveUssdResponse(TelephonyManager telephonyManager, String request, CharSequence response) {
super.onReceiveUssdResponse(telephonyManager, request, response);
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "USSD Result"+response.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onReceiveUssdResponseFailed(TelephonyManager telephonyManager, String request, int failureCode) {
super.onReceiveUssdResponseFailed(telephonyManager, request, failureCode);
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "USSD Response Failed.", Toast.LENGTH_SHORT).show();
}
}, new Handler());
}
compleCode contains the USSD Code. But the Toast shows Nothing.
can any one please find me the solution.? Or is there any other way to get the dialed USSD response in my app?
I found the answer myself. I Used this Api to resolve the problem.
https://github.com/romellfudi/VoIpUSSD
Here is my code:
HashMap map = new HashMap<>();
map.put("KEY_LOGIN",new HashSet<>(Arrays.asList("espere", "waiting", "loading", "esperando")));
map.put("KEY_ERROR",new HashSet<>(Arrays.asList("problema", "problem", "error", "null")));
final USSDApi ussdApi = USSDController.getInstance(MainActivity.this);
ussdApi.callUSSDInvoke("*786#", map, new USSDController.CallbackInvoke() {
#Override
public void responseInvoke(String message) {
// message has the response string data
String dataToSend = "data";// <- send "data" into USSD's input text
ussdApi.send(dataToSend,new USSDController.CallbackMessage(){
#Override
public void responseMessage(String message) {
// message has the response string data from USSD
Log.d("message", message);
}
});
}
#Override
public void over(String message) {
// message has the response string data from USSD or error
// response no have input text, NOT SEND ANY DATA
}
});

Login to Firebase using phone returns null pointer

I'm trying to follow the tutorial from Firebase to allow users to login using their phone number. I've watched a tutorial video. All my code looks correct, but when I try it on my test device I receive a null pointer error.
at com.google.android.gms.common.internal.Preconditions.checkNotNull(Unknown Source)
at com.google.firebase.auth.PhoneAuthProvider.verifyPhoneNumber(Unknown Source)
at studios.p9p.chatomatic.chat_o_matic.PhoneLogin.CheckPhoneNumber(PhoneLogin.java:92)
at studios.p9p.chatomatic.chat_o_matic.PhoneLogin.access$000(PhoneLogin.java:29)
at studios.p9p.chatomatic.chat_o_matic.PhoneLogin$1.onClick(PhoneLogin.java:52)
My code for the phone login is as follows:
private EditText et_check_phone_number;
private EditText et_verify_code;
private Button btn_phone;
private Button btn_verify;
private String getPhoneNumber, getVerifactionCode;
private String mVerificationId = "";
private FirebaseAuth mAuth;
private FirebaseDatabase db;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mcallBacks;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private ProgressDialog mloading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_login);
mAuth = FirebaseAuth.getInstance();
initVariables();
btn_phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckPhoneNumber();
}
});
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VerifyPhoneNumber();
}
});
}
private void initVariables() {
et_check_phone_number = findViewById(R.id.et_phonenumber);
et_verify_code = findViewById(R.id.etvarifaction);
btn_phone = findViewById(R.id.btn_phone_login);
btn_verify = findViewById(R.id.btn_phone_verify);
mloading = new ProgressDialog(this);
}
private void CheckPhoneNumber() {
getPhoneNumber = et_check_phone_number.getText().toString();
if (TextUtils.isEmpty(getPhoneNumber))
{
Toast.makeText(this, "Phone Number Field Cant Be Empty...", Toast.LENGTH_SHORT).show();
} else{
mloading.setTitle("Checking Your Phone Number");
mloading.setMessage("It Gonna Take A Second...");
mloading.setCanceledOnTouchOutside(false);
mloading.setIcon(R.mipmap.ic_launcher);
mloading.show();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
getPhoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mcallBacks);
}
}
mcallBacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(PhoneLogin.this, "Wrong Or Invalid Phone Number...", Toast.LENGTH_SHORT).show();
btn_phone.setVisibility(View.VISIBLE);
et_check_phone_number.setVisibility(View.VISIBLE);
et_verify_code.setVisibility(View.INVISIBLE);
btn_verify.setVisibility(View.INVISIBLE);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(getBaseContext(), "Invalid Request " + e.toString(), Toast.LENGTH_SHORT).show();
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(getBaseContext(), "The SMS quota for the project has been exceeded " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
Toast.makeText(PhoneLogin.this, "Code Sent Please Check Your SMS...", Toast.LENGTH_SHORT).show();
btn_phone.setVisibility(View.INVISIBLE);
et_check_phone_number.setVisibility(View.INVISIBLE);
et_verify_code.setVisibility(View.VISIBLE);
btn_verify.setVisibility(View.VISIBLE);
}
};
}
private void VerifyPhoneNumber() {
getVerifactionCode = et_verify_code.getText().toString();
if (TextUtils.isEmpty(getVerifactionCode)){
Toast.makeText(this, "Please Enter The Code Sent To Your SMS...", Toast.LENGTH_SHORT).show();
}else{
mloading.setTitle("Checking Your Verification code ");
mloading.setMessage("Ill Be Back In A Jiffy...");
mloading.setCanceledOnTouchOutside(false);
mloading.setIcon(R.mipmap.ic_launcher);
mloading.show();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, getVerifactionCode);
signInWithPhoneAuthCredential(credential);
}
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
mloading.dismiss();
Toast.makeText(PhoneLogin.this, "Login Successful...", Toast.LENGTH_SHORT).show();
Intent phoneloginIntent =new Intent (getBaseContext(),Home_Screen.class);
phoneloginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(phoneloginIntent);
finish();
} else {
String mesage = task.getException().toString();
Toast.makeText(PhoneLogin.this, "Error: " + mesage, Toast.LENGTH_SHORT).show();
}
}
});
}
The "+44" I added trying to see if I was entering the wrong phone number. I tried it by adding the +44 manually into the edit text of the app first and that gave the same error.
Edit
So I've removed the line inside the Auth provider that asked if the number was larger than 9 digits as it wasn't working. Also I ran a log to see if it capturing the phone number correctly.
Log.i("Verify_Phone_Number",getPhoneNumber);
2019-07-16 14:15:30.585 32055-32055/studios.p9p.chatomatic.chat_o_matic I/Verify_Phone_Number: +447******100 and it returns correctly
Edit 2
So on further testing if I click btn_phone before entering the phone number it works correctly, but if I simply add the phone number to the edit test first then press thebtn_phone it crashes with the above message in logcat.
As per Firebase Docs you have to pass the Number with Country Code :
E.g.
phone number = +919090909090
See Following Picture :
As you can see even testing number needs country code with them.
When your app crashes it means Firebase PhoneAuthProvider.getInstance().verifyPhoneNumber() not getting the number with country code.
You can try this following code before passing to if condition :
if (et_check_phone_number.getText().toString().startsWith("+44"){
getPhoneNumber = et_check_phone_number.getText().toString();
}else{
getPhoneNumber = "+44"+et_check_phone_number.getText().toString();
}
Above Code will check whether user put prefix of your country code or not.
Ok so the way i solved this problem was to move the mcallbacks to the on create section of code. as shown below
setContentView(R.layout.activity_phone__login);
mAuth = FirebaseAuth.getInstance();
InitVariables();
AddPhoneNumberButtons();
mcallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(getBaseContext(), "Wrong Or Invalid Phone Number...", Toast.LENGTH_SHORT).show();
AddPhoneNumberButtons();
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(getBaseContext(), "Invalid Request " + e.toString(), Toast.LENGTH_SHORT).show();
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(getBaseContext(), "The SMS quota for the project has been exceeded " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
// Save verification ID and resending token so we can use them later
verificationid = verificationId;
mresendtoken = token;
Toast.makeText(getBaseContext(), "Code Sent Please Check Your SMS...", Toast.LENGTH_SHORT).show();
AddVerifyButtons();
}
};

I want to call logout method on Android application when application is uninstalled

I want to call logout method on Android application when application is uninstalled.
private void setlogout() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, logout,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Toast.makeText(getApplicationContext(), "logout successfully", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}

intent to next activity, toast, progress bar not working

I am trying to make a login page where if user enters a correct mobile and pwd it should go in ProfileActivity.java
my code
public class LoginActivity extends AppCompatActivity {
EditText editTextUsername, editTextPassword;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (SharedPrefManager.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, ProfileActivity.class));
}
progressBar = (ProgressBar) findViewById(R.id.progressBar);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
//if user presses on login
//calling the method login
Button login = (Button)findViewById(R.id.buttonLogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userLogin();
}
});
//if user presses on not registered
findViewById(R.id.textViewRegister).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//open register screen
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
}
private void userLogin() {
//first getting the values
final String mobile = editTextUsername.getText().toString();
final String password = editTextPassword.getText().toString();
//validating inputs
if (TextUtils.isEmpty(mobile)) {
editTextUsername.setError("Please enter your username");
editTextUsername.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
editTextPassword.setError("Please enter your password");
editTextPassword.requestFocus();
return;
}
//if everything is fine
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getInt("id"),
userJson.getString("mobile"),
userJson.getString("password")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("mobile", mobile);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
}
In this code neither a toast, progressbar, nor the intent to redirect to next activity is working. I have also extended ProfileActivity with Activity. I have registerd profileactivity.java in manifest file.
What am i doing wrong here? thank you for your suggestions
finish() method should be put a end, because it will ignore all next lines.
Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
You are using "id" field as an integer and it's an String ,Secondly from where you are getting
User user = new User(
userJson.getString("id"),
"", // please add mobile and password in JSON
""
);
I solved it. In the line ,
JSONObject userJson = obj.getJSONObject("user");
I named the object as user. But in PHP I named it as result As soon as I changed it, it started working.
Although, Thanks for your support community :).

Categories