Firebase has no response regarding volley request - android

I am new to firebase. I tried to store user data in firebase database using volley. However, firebase has no response regarding my volley request and the database still is null. This is the tutorial I followed.
This is the volley request I used to connect firebase.
public void executeFirebase(){
StringRequest request = new StringRequest(Request.Method.GET, FIREBASE_REGISTER_URL, new Response.Listener<String>(){
#Override
public void onResponse(String s) {
Firebase reference = new Firebase("https://tradeal-930ad.firebaseio.com/users");
if(s.equals("null")) {
reference.child(name).child("password").setValue(password);
Toast.makeText(activity, "registration successful 1", Toast.LENGTH_LONG).show();
}
else {
try {
JSONObject obj = new JSONObject(s);
if (!obj.has(name)) {
reference.child(name).child("password").setValue(password);
Toast.makeText(activity, "registration successful 2", Toast.LENGTH_LONG).show();
Intent intent = new Intent(activity, MainPageActivity.class);
activity.startActivity(intent);
activity.finish();
loginUserActivity.finish();
} else {
Toast.makeText(activity, "username already exists", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
loading.dismiss();
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("" + volleyError );
loading.dismiss();
}
});
RequestQueue rQueue = Volley.newRequestQueue(activity);
rQueue.add(request);
}

change the rules of your database to public
{
"rules" :
{
".read" : true,
".write" : true
}
}
otherwise
{
"error" : "Permission denied"
}
this will be your response
to know more about rules you can visit security rules

Related

ReCaptcha V2 response error 12008 in Android

Below is my implementation of ReCaptcha V2 in my Android app.
When I run it, it returns: Error message: unknown status code: 12008
This means the following:
public static final int RECAPTCHA_INVALID_KEYTYPE Cannot start the
reCAPTCHA service because type of site key is not valid.
Please register new site key with the key type set to "reCAPTCHA
Android" via //g.co/recaptcha/androidsignup.
Constant Value: 12008
My site key is available on my ReCaptcha admin portal, so what do I need to do for it to be 'valid'?
The code example that I've implemented does include the following comments regarding the server url:
//it is google recaptcha siteverify server
//you can place your server url
Is this a requirement or a suggestion?
public void onCaptchaClick(View view) {
SafetyNet.getClient(this).verifyWithRecaptcha(SITE_KEY)
.addOnSuccessListener(this, new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
#Override
public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {
if (!response.getTokenResult().isEmpty()) {
handleSiteVerify(response.getTokenResult());
}
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
Log.d(TAG, "Error message: " +
CommonStatusCodes.getStatusCodeString(apiException.getStatusCode()));
} else {
Log.d(TAG, "Unknown type of error: " + e.getMessage());
}
}
});
}
protected void handleSiteVerify(final String responseToken){
//it is google recaptcha siteverify server
//you can place your server url
String url = "https://www.google.com/recaptcha/api/siteverify";
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.getBoolean("success")){
Toast.makeText(getApplicationContext(),String.valueOf(jsonObject.getBoolean("success")),Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),String.valueOf(jsonObject.getString("error-codes")),Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Log.d(TAG, "JSON exception: " + ex.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error message: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("secret", SECRET_KEY);
params.put("response", responseToken);
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
This error means that you are not using the right key.
Have you created an Android app key or a website key? I got this error when I tried to use the web key for the app, you need an Android app key.

java.io.EOFexception when running my application on real device

i am developing an application that request data from MYSQL
i used an API (json) to retrieve the data from database.
My problem is that my project works fine on android studio but when i am running it on real device (Samsung GT-I9082) i got an exception and i don't know why!
the exception is:
java.io.EOFexception
mycode:
private void getData(String leng) {
final String id="23119574";
try {
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this, "Please wait...", "Fetching...", false, false);
// String url = config.DATA_URL3+id;
String url = config.DATA_URL4 + id;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response, id);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Handler_Barcode.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
stringRequest.setRetryPolicy((new DefaultRetryPolicy(
20000,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)));
requestQueue.add(stringRequest);
}catch(Exception e){
e.printStackTrace();
}
}
note: i am using volley
and my device android version is 4.2.2
thank you!

how to pass header in retrofit 1.9 API

Requirement->
To get list of Objects Using GET Request:
passing Request headers:
X-ACCESS-TOKEN = Token received after successful sign in
X-USER-EMAIL = Email used in login.
I am using this code to login->
private void normalLoginToServer() {
final ProgressDialog progressDialog = GeneralUtil.createProgressDialog(this, "Logging into app..");
progressDialog.show();
Instead of using JSONObject, i need to pass Request Headers.
in a below Astrike code. how to pass Headers.? please help me.
***JSONObject outer_body = new JSONObject();
JSONObject body = new JSONObject();
try {
body.put(Constants.USER_EMAIL, _emailText.getText().toString().trim());
body.put(Constants.USER_PWD, _passwordText.getText().toString().trim());
outer_body.put(Constants.USER, body);***
try {
TypedInput typedInput = new TypedByteArray("text/plain", outer_body.toString().getBytes("UTF-8"));
apiService.loginToServer(typedInput, new Callback<UserInfo>() {
#Override
public void success(UserInfo response, Response response2) {
int status = response2.getStatus();
switch (status) {
case 200:
if (progressDialog.isShowing())
progressDialog.dismiss();
if (response == null)
return;
String status1 = response.getStatus();
if (status1.equalsIgnoreCase("success")) {
Toast.makeText(context, "Successful login", Toast.LENGTH_SHORT).show();
Data data = response.getData();
User user = data.getUser();
String token = user.getAccess_token();
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra(Constants.ACCESS_TOKEN, token);
startActivity(intent);
finish();
} else if (status1.contains("failure")) {
Toast.makeText(context, "Username not found", Toast.LENGTH_SHORT).show();
}
break;
case 500:
Toast.makeText(context, getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void failure(RetrofitError retrofitError) {
if (progressDialog.isShowing())
progressDialog.dismiss();
if (retrofitError != null) {
if (retrofitError.getKind() != null) {
if (retrofitError.getKind().equals(RetrofitError.Kind.NETWORK)) {
Toast.makeText(context, "Check your network connection and try again later",
Toast.LENGTH_SHORT).show();
}
} else if (retrofitError.getResponse() != null) {
if (retrofitError.getResponse().getStatus() == 500) {
Toast.makeText(context, getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
}
}
}
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in Advenced.!!
You can use #Header in your retrofit api interface. For example, something like:
void loginToServer(#Header("your_header") String yourHeaderValue, Callback<UserInfo> callback);
Assuming you want to pass static headers(those who won't change for a individual requests).
for example this code adds cache control header to /tasks request
public interface UserService {
#Headers("Cache-Control: max-age=640000")
#GET("/tasks")
List<Task> getTasks();
}
and if you need to pass dynamic headers (those changing on individual requests)
public interface UserService {
#GET("/tasks")
List<Task> getTasks(#Header("Content-Range") String contentRange);
}
More on Retrofit Add Custom Request Header

Volley onErrorResponse doesn't work when no internet access

I have a function getTeacherData()
and it returns a json object,The problem is when i disable my internet connection on my phone the app crashes(android doesn't show the error in android monitor,it just crashes without showing the bug),
When i run the same app on my emulator it works fine and if i disconnect my internet the onErrorResponse is also working ,but it crashes when i run it on other phones
private void getTeacherData() {
if (username.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
String url = DATA_URL+username;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(cardview.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
try {
JSONObject jsonObject =new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config.JSON_ARRAY);
for(int x=0;x<result.length();x++) {
JSONObject collegeData = result.getJSONObject(x);
albumList.add(new Album(collegeData.getString(config.course_name),collegeData.getString(config.semester)
,collegeData.getString(config.section),collegeData.getString(config.total_classes)
,collegeData.getString(config.subject),collegeData.getString(config.classes_taken),collegeData.getString(config.subject_code)));
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
things i have tried :
Removed showJSON(); method inside onResponse().
Surrounded the string request with try catch.
Surrounded whole getTeacherData() with try catch.
It seems like onErrorResponse responds differently on few devices
onErrorResponse returned null on few devices (that was the reason for the crash)
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error.getMessage==NULL){
Toast.makeText(cardview.this, "Failed to retrieve data", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(cardview.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});

NoConnectionError in android volley

The following is my code. I get com.android.volley.NoConnectionError: java.io.InterruptedIOException for the first time and for the second time it works fine. There server response is also fine, No error in server side.
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest request = new JsonObjectRequest(URL, null,
new Listener<JSONObject>() {
#Override
public void onResponse(JSONObject responseJsonObject) {
try {
if (responseJsonObject.has("user")
&& !responseJsonObject
.isNull("user")) {
user.jsonParser(responseJsonObject
.getJSONObject("user"));
}
} catch (JSONException exception) {
Toast.makeText(context, "Error Occured",
Toast.LENGTH_SHORT).show();
}
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
progressDialog.dismiss();
Log.d("Volley Error", volleyError.toString());
Toast.makeText(context, "Connectivity Error",
Toast.LENGTH_SHORT).show();
}
});
queue.add(request);
progressDialog.show();
queue.start();
I had the same problem and I solved it by removing the following line
queue.start()
I was having the same issue. The question Vamsi referenced has a workaround using OkHttp that you works if you use OkHttp as the stack in volley (see also the comments in that question on how to use OkHttp in volley).
However, here is another hacky workaround that doesn't involve using another library:
final RequestQueue requestQueue = getRequestQueue();
final class ErrorFirstTimeHack {
boolean first_time = true;
MyVolleyJsonObjectRequest request = null;
}
final ErrorFirstTimeHack errorFirstTimeHack = new ErrorFirstTimeHack();
final MyVolleyJsonObjectRequest request = buildRequestObject(
Request.Method.GET,
url,
new Response.Listener() {
#Override
public void onResponse(Object response) {
// normal success processing
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof com.android.volley.NoConnectionError) {
if (errorFirstTimeHack.first_time) {
errorFirstTimeHack.first_time = false;
requestQueue.add(errorFirstTimeHack.request);
return;
}
}
// normal error processing
}
}
);
errorFirstTimeHack.request = request;
requestQueue.add(request);

Categories

Resources