Retrieve a String property from a class instance - java

I have class A and B.
"A" makes an instance of "B" and call a method that modify a String property. However, after the calling the property checked in "A" is null.
Can anyone help me?
Class B
private String Retro;
....
public boolean Login(final String user, final String pass){
stringRequest = new StringRequest(Request.Method.POST, Url + strLogin,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Retro = "Done";
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
**Retro = error.getMessage();**
Toast.makeText(context, "Error de acceso: "+Retro, Toast.LENGTH_LONG).show(); //error.getMessage()
}
}) {
#Override
protected Map<String, String> getParams(){
Map<String, String> parameters = new HashMap<>();
parameters.put("identifier", user);
parameters.put("password", pass);
return parameters;
}
};
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
return Retro == "Done";
}
Class A
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
accessDB = new StrapiDBAccess(this);
signIn();
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
...
if (acct != null) {
....
boolean result = accessDB.Login(parcelAccess.personEmail, "*******");
tvAuth.setText(tvAuth.getText()+" "+**accessDB.getRetro()**); //
}
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
parcelAccess.signedIn = false;
parcelAccess.personName = "Anónimo";
Toast.makeText(this, "Error de autenticación con Google. Chequee que tiene internet e inténtelo de nuevo.", Toast.LENGTH_SHORT).show();
}
}

I found the answer to my doubt. It is impossible to do by a field, or getter or any direct way. It is neccesary to implement an interface for success or error. It would be this way:
Class B
public void Login(final String user, final String pass, final VolleyCallback callback){
Retro = "";
stringRequest = new StringRequest(Request.Method.POST, Url + strLogin,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
***callback.onSuccess("Done");***
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Retro = Retro + String.copyValueOf(error.getMessage().toCharArray());
***callback.onError(Retro);***
//error.getMessage()
}
}) {
#Override
protected Map<String, String> getParams(){
Map<String, String> parameters = new HashMap<>();
parameters.put("identifier", user);
parameters.put("password", pass);
return parameters;
}
};
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
Toast.makeText(context, "Error de acceso: "+ErrorCode, Toast.LENGTH_LONG).show();
}
Class A
accessDB.Login(parcelAccess.personEmail, "************", new StrapiDBAccess.VolleyCallback(){
#Override
public void onSuccess(String result) {
}
#Override
public void onError(String error)
//no pudo ingresar
}
}
});
Well, I hope to help anyone who has this kind of trouble

Related

com.android.volley.clientError Android Studio Error

When I press on the register button this error occurs.
I have installed the volley 1.1.1
this is my code:
public class MainActivity extends AppCompatActivity {
private EditText etEmail, etPassword;
private String email, password;
private String URL = "http://10.0.2.2/login/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email = password = "";
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPassword);
}
public void login(View view) {
email = etEmail.getText().toString().trim();
password = etPassword.getText().toString().trim();
if(!email.equals("")&&!password.equals("")){
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success")) {
Intent intent = new Intent(MainActivity.this, Success.class);
startActivity(intent);
finish();
} else if (response.equals("failure")) {
Toast.makeText(MainActivity.this, "Invalid Login Id/Password", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
protected Map<String, String> getParms() throws AuthFailureError {
Map<String, String> parms = new HashMap<>();
parms.put("email",email);
parms.put("password", password);
return parms;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}else{
Toast.makeText(this, "Fields can not be empty!", Toast.LENGTH_SHORT).show();
}
}

method int return wrong value [duplicate]

This question already has answers here:
How do i use a variable outside the onResponse in Android?
(4 answers)
Closed 4 years ago.
Greeting all, I am having the hard time to set int value for a variable in ValueEventListener and get that value outside ValueEventListener for the method to checking is value == 1, the method will return 1, else return 0
I have tried many way like save the value via SharedPreferences, set value to Textview and call from textview, but still, the method always return 0 as it cannot read the value that have been set in ValueEventListener. Any help are much appreciate. Thank you
Here my code
int status = 0;
protected void onCreate(Bundle savedInstanceState) {
...
btnSync_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getCustomerList() == 1) {
msg = msg + "Get customer success \n";
} else {
msg = msg + "Get customer unsuccessful \n";
}
AlertDialog.Builder statusDialog = new AlertDialog.Builder(SyncActivity.this);
statusDialog.setPositiveButton("OK", null);
statusDialog.setTitle("Status");
statusDialog.setMessage(msg);
statusDialog.show();
msg = "";
}
});
}
The method that will return the int
private int getCustomerList() {
urlRef = myRef.child("...");
urlRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
...
StringRequest stringRequest = new StringRequest(Request.Method.GET, customerURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
status = 1; //here my problem, value assign here is success
try {
...
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
...
status = 0; // here if unsuccessful
}
});
RequestQueue requestQueue = Volley.newRequestQueue(SyncActivity.this);
requestQueue.add(stringRequest);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
...
}
});
if (status == 1) {
return 1;
} else {
return 0;
}
}
Even better way why dont't you display your AlertDialog inside getCustomerList() method
Call your getCustomerList() like this
btnSync_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCustomerList();
}
});
Then add your AlertDialog inside getCustomerList() like this
SAMPLE CODE
private void getCustomerList() {
AlertDialog.Builder statusDialog = new AlertDialog.Builder(SyncActivity.this);
statusDialog.setPositiveButton("OK", null);
statusDialog.setTitle("Status");
urlRef = myRef.child("...");
urlRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
...
StringRequest stringRequest = new StringRequest(Request.Method.GET, customerURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
msg = msg + "Get customer success \n";
statusDialog.setMessage(msg);
statusDialog.show();
msg = "";
try {
...
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
...
msg = msg + "Get customer unsuccessful \n";
statusDialog.setMessage(msg);
statusDialog.show();
msg = "";
}
});
RequestQueue requestQueue = Volley.newRequestQueue(SyncActivity.this);
requestQueue.add(stringRequest);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
...
}
});
}

Autoclick saveButton in every change of string in editText

Receive SMS then set EditText to msgBody
public class SmsBroadcastReceiver extends BroadcastReceiver {
//.....
((EditText)MainActivity.mThis.findViewById(R.id.editTextName)).setText(msgBody);}
The error is this in View cannot be applied to android.view.View.Onclicklistiner
//onCreate
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
buttonSave.performClick(this);
}
});
the message will automatically save to SQLite and sync to Mysql when buttonSave is click
private void saveNameToServer() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Saving Name...");
progressDialog.show();
final String name = editTextName.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_SAVE_NAME,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
//if there is a success
//storing the name to sqlite with status synced
saveNameToLocalStorage(name, NAME_SYNCED_WITH_SERVER);
} else {
//if there is some error
//saving the name to sqlite with status unsynced
saveNameToLocalStorage(name, NAME_NOT_SYNCED_WITH_SERVER);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
//on error storing the name to sqlite with status unsynced
saveNameToLocalStorage(name, NAME_NOT_SYNCED_WITH_SERVER);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", name);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
#Override
public void onClick(View view) {
saveNameToServer();
}
Are there other ways to auto click button when EditText value changes?
Instead of invoking the click buttonSave.performClick(this); just simply invoke saveNameToServer(); method to save your data.
buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//buttonSave.performClick(this); // remove, not required
saveNameToServer(); // save your data
}
});

How to debug "json parsing error: Value true at error of type java.lang.Boolean cannot be converted to JSONObject"

I am making android app with gcm integration for group chatting and messages broadcasting. But when I'm executing it, application showing an error:
json parsing error: Value true at error of type java.lang.Boolean cannot be converted to JSONObject
LoginActivity.java:
public class LoginActivity extends AppCompatActivity {
private String TAG = LoginActivity.class.getSimpleName();
private EditText inputName, inputEmail;
private TextInputLayout inputLayoutName, inputLayoutEmail;
private Button btnEnter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Check for login session. It user is already logged in
* redirect him to main activity
* */
if (MyApplication.getInstance().getPrefManager().getUser() != null) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_name);
inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_email);
inputName = (EditText) findViewById(R.id.input_name);
inputEmail = (EditText) findViewById(R.id.input_email);
btnEnter = (Button) findViewById(R.id.btn_enter);
inputName.addTextChangedListener(new MyTextWatcher(inputName));
inputEmail.addTextChangedListener(new MyTextWatcher(inputEmail));
btnEnter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}
});
}
/**
* logging in user. Will make http post request with name, email
* as parameters
*/
private void login() {
if (!validateName()) {
return;
}
if (!validateEmail()) {
return;
}
final String name = inputName.getText().toString();
final String email = inputEmail.getText().toString();
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error flag
if (obj.getBoolean("error") == false) {
// user successfully logged in
JSONObject userObj = obj.getJSONObject("user");
User user = new User(userObj.getString("user_id"),
userObj.getString("name"),
userObj.getString("email"));
// storing user in shared preferences
MyApplication.getInstance().getPrefManager().storeUser(user);
// start main activity
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
// login error - simply toast the message
Toast.makeText(getApplicationContext(), "" + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("email", email);
Log.e(TAG, "params: " + params.toString());
return params;
}
};
//Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
// Validating name
private boolean validateName() {
if (inputName.getText().toString().trim().isEmpty()) {
inputLayoutName.setError(getString(R.string.err_msg_name));
requestFocus(inputName);
return false;
} else {
inputLayoutName.setErrorEnabled(false);
}
return true;
}
// Validating email
private boolean validateEmail() {
String email = inputEmail.getText().toString().trim();
if (email.isEmpty() || !isValidEmail(email)) {
inputLayoutEmail.setError(getString(R.string.err_msg_email));
requestFocus(inputEmail);
return false;
} else {
inputLayoutEmail.setErrorEnabled(false);
}
return true;
}
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.input_name:
validateName();
break;
case R.id.input_email:
validateEmail();
break;
}
}
}
}
Because the response you are getting it not properly formatted for Json conversion.
JSONObject obj = new JSONObject(response);
Its returning boolean which you are trying to convert into JSONObject.
Edit 1: It might also occur that there is problem while fetching boolean.
Try to fetch it like this:
jsonObject.optBoolean("error");

Why is my JsonObjectRequest not working?

I have been fiddling with this for a few days now. Couldn't get it right. Android studio won't let me compile it with this error. So, I have this application where I have two tabs and two fragments. One fragment is called new, and that fragment fetches json. But I couldn't get to do it properly. I have uploaded a picture of how the error looks like, and the class files. Can you please help me out?
Error: "Cannot resolve constructor JsonObjectRequest(int, java.lang.String, null.......)
new_fragment.java
public class new_fragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
private RequestQueue requestQueue;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() !=null){
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
volleySingleton = VolleySingleton.getsInstance();
requestQueue = volleySingleton.getRequestQueue();
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,"http://10.0.8.152/json/new.json",null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedIntanceState) {
setHasOptionsMenu(true);
View layout = inflater.inflate(R.layout.new_fragment, container, false);
return layout;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.ref_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.refreshico:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
VolleySingleton
public class VolleySingleton {
private static VolleySingleton sInstance = null;
private ImageLoader mImageLoader;
private RequestQueue mRequestQueue;
private VolleySingleton(){
mRequestQueue = Volley.newRequestQueue(appClass.getAppContext());
mImageLoader = new ImageLoader(mRequestQueue,new ImageLoader.ImageCache() {
private LruCache<String, Bitmap> cache = new LruCache<>((int)(Runtime.getRuntime().maxMemory()/1024)/8);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static VolleySingleton getsInstance(){
if(sInstance==null){
sInstance = new VolleySingleton();
}
return sInstance;
}
public RequestQueue getRequestQueue(){
return mRequestQueue;
}
public ImageLoader getImageLoader(){
return mImageLoader;
}
}
cast (String)null.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,"http://10.0.8.152/json/new.json",(String)null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
new JsonObjectRequest takes 3rd Parameter as String requestBody
cast null to String
or you can make a null string like String rBody = null; and then pass rBody as 3rd Parameter
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
"http://10.0.8.152/json/new.json", (String) null, // here
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
For everyone trying to implement this right now: Google changed the jsonObjectRequest constructor: now you don't suppy the request type anymore, instead you supply firstly the url and then null as second parameter if you want a get request. e.g.:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("http://www.aaa.com/getJSON/dummyMeldung.json", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("meldung");
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject meldung = jsonArray.getJSONObject(i);
String comment = meldung.getString("comment");
Log.d("ausgabe", comment);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Well, i see the situation, and it happends because as your error say, the constructor doesnt exists.
If you are using the JsonObjectRequest as default, and you want to consume an Get method, you dont have to send the null parameter, you just should send of this way:
Change this:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,"http://10.0.8.152/json/new.json",null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
For this:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,"http://10.0.8.152/json/new.json",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
As you can see, i just remove the parameter for the JsonObject, because the method is Get, and there is an constructor thats accept that you dont send JsonObject.
Another solution is to make your own JsonObjectRequest, and custom it to accept that kind of values.
Regards.
There is a ambiguous Constructor, for solve this, use this code:
JSONObject jsonObject = null;
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET, "Your url", jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
The problem as to do with the version of volley.
On your build.gradle app file you should have
dependencies {
......
compile 'com.mcxiaoke.volley:library:1.0.0'
.....
}

Categories