doinBackground cannot save field values - android

I'm trying to figure out reason doInBackground() cannot save field values. Even return value changes back to initial after return statement. I have initialed AsyncTask onCreate() in the main class. Everything works fine until onPostExecute().
Thanks in advance
private class UserRegisterTask extends AsyncTask<Void, Void, Boolean> {
JSONObject jsonObj;
String uuid;
String ok;
String errorMessage;
Boolean noErrors = false;
public UserRegisterTask() {
}
Here is doInBack...
#Override
protected Boolean doInBackground(Void... params) {
final String url = "https://webaddress/register.php";
final Context context = getContext();
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonObj = new JSONObject(response);
String error = jsonObj.getString("error");
if (error.equals("false")) {
uuid = jsonObj.getString("unique_id");
noErrors = true;
Log.e("####¤%", String.valueOf(noErrors.booleanValue()));
mEmail = jsonObj.getString("email");
ok = jsonObj.getString("ok");
} else {
errorMessage = jsonObj.getString("error_msg");
Log.d("XXXXXXXXXXXXX", errorMessage);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//mTextView.setText("That didn't work!");
Log.e("ERROR", error.getMessage());
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("password", mpassword);
params.put("email", mEmail);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest);
return noErrors;
}
And here is onPostExecute()
#Override
protected void onPostExecute(Boolean success) {
urt = null;
if (success.booleanValue()) {
Toast toast = Toast.makeText(getApplicationContext(), ok, Toast.LENGTH_LONG);
toast.show();
new Thread(new Runnable() {
public void run() {
new SendEmail(mEmail, sb.toString(), uuid);
}
}).start();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
intent.putExtra("email", mEmail);
startActivity(intent);
// finish();
} else {
Toast toast = Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_SHORT);
toast.show();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
}
}

Related

Android - Intent data after AsyncTask

Server connection is working on background (AsyncTask), and server response JSON.
I want to send data from server to other Activity, but it is not working.
I have tried to solve this but nothing work. How I can solve this?
My code is below:
public class LoginRequest extends AsyncTask<Void, Void, String> {
String errorMsg = LOGIN_ERROR;
String builder;
#Override
protected String doInBackground(Void... voids) {
JSONObject requestJsonObject = new JSONObject();
try {
requestJsonObject.put("email", userEmail);
requestJsonObject.put("password", userPassword);
} catch (JSONException e) {
e.printStackTrace();
}
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.POST,
BASE_URL,
requestJsonObject,
response -> {
errorMsg = LOGIN_SUCCESS;
Log.d(TAG, "response = " + response);
builder = response.toString();
},
error -> errorMsg = LOGIN_ERROR
);
requestQueue.add(request);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (errorMsg.equals(LOGIN_ERROR)) {
textViewError.setText(R.string.login_failure);
} else {
Toast.makeText(getApplicationContext(), "Login Success", Toast.LENGTH_SHORT).show();
// Send data from server to UserMainActivity
Intent intent = new Intent(LoginActivity.this, UserMainActivity.class);
intent.putExtra("serverMessage", builder);
startActivity(intent);
}
}
}
You should pass your activity context to your asyncTask and start Activity from that context
Your AsyncTask should look like this
private class LoginRequest extends AsyncTask<Void, Void, String> {
Context context;
LoginRequest(Context context)
{
this.context=context;
}
String builder;
#Override
protected String doInBackground(Void... voids) {
//your code here
return null;
}
#Override
protected void onPostExecute(String s) {
//your code here
Intent intent = new Intent(context, NewActivity.class);
intent.putExtra("serverMessage", builder);
context.startActivity(intent);
}
}
Call this asyncTask like this
LoginRequest asyncTaskForceUpdate=new LoginRequest(this);
asyncTaskForceUpdate.execute();
Try to change your code as below:
public class LoginRequest extends AsyncTask<Void, Void, String> {
String errorMsg = "ERROR";
String builder = "";
#Override
protected String doInBackground(Void... voids) {
JSONObject requestJsonObject = new JSONObject();
try {
requestJsonObject.put("email", userEmail);
requestJsonObject.put("password", userPassword);
} catch (JSONException e) {
e.printStackTrace();
}
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.POST,
BASE_URL,
requestJsonObject,
response -> {
errorMsg = "SUCCESS";
Log.d(TAG, "response = " + response);
builder = response.toString();
},
error -> errorMsg = "ERROR"
);
requestQueue.add(request);
return errorMsg;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s.equals("ERROR")) {
textViewError.setText(R.string.login_failure);
} else {
Toast.makeText(getApplicationContext(), "Login Success", Toast.LENGTH_SHORT).show();
// Send data from server to UserMainActivity
Intent intent = new Intent(LoginActivity.this, UserMainActivity.class);
intent.putExtra("serverMessage", builder);
startActivity(intent);
}
}
}
I changed the return value to errorMsg for doInBackground. As it is more common practice. Tell me if this does or doesn't work.

How Can I use Post Method in Volley?

I want to know how can I POST Request Object in volley
class Request {
int restId;
List<Item> items;
}
class Item{
int itemId;
int count;
}
OnCreate():
RequestQueue requestQueue = Volley.newRequestQueue(this);
Example Post Method:
StringRequest postRequest = new StringRequest(Request.Method.POST, url1,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
System.out.println("response: " + response);
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
System.out.println("success: " + success);
// success-e gore usere info gosterilir
if (success.equals("true"))
{
Toast.makeText(SignUpActivity.this, R.string.register_success, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SignUpActivity.this, SignInActivity.class);
startActivity(intent);
}
else
{
String errorMessage = jsonObject.getString("message");
Toast.makeText(SignUpActivity.this, R.string.register_failed, Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(SignUpActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
)
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
params.put("name", nameText);
params.put("login", userNameText);
params.put("email", emailText);
params.put("password", passwordText);
if (!dateText.equals(""))
params.put("birthday", dateText);
return params;
}
};
requestQueue.add(postRequest);

Return response of Volley of Android [duplicate]

This question already has answers here:
Can I do a synchronous request with volley?
(8 answers)
Closed 4 years ago.
I have written a function that makes an HTTP request and the response stores in a Bundle to subsequently initialize an activity.
public static void communicate(final Context context, String url, final String typeResponse, final Intent intent) {
RequestQueue queue = Volley.newRequestQueue(context);
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest stringRequest = new StringRequest(Request.Method.POST, BASE_URL + url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
switch (typeResponse) {
case "text":
bundle.putString("response", response);
break;
case "json":
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray names = jsonObject.names();
for (int i = 0; i < names.length(); i++) {
//Toast.makeText(context, names.getString(i), Toast.LENGTH_SHORT).show();
bundle.putString(names.getString(i), jsonObject.getString(names.getString(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
intent.putExtras(bundle);
context.startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("test", "hi!!");
return params;
}
};
queue.add(stringRequest);
}
But I want return the Bundle object for use that function like this:
Bundle myBundle = communicate('httl://qwe.asd', 'json')
How can I to modifier my function?
Thanks.
Volley request are asynchronous, so i recommend you put inner your onResponse other function to be process your bundle.
As well, you can create an interface to send your response in other place. Something like this
interface
public interface onResponseCallback {
void onResponse(Bundle bundle);
}
activity
public MyActivity extends AppCompatActivity implements onResponseCallback{
public void onCreate(Bundle....){
MyRequest myrequest = new MyRequest(this);
..}
public void onResponse(Bundle bundle){
//bundle argument is your response from request,
// do some with your response
Intent intent = new Intent....
intent.putExtras(bundle);
startActivity(intent);
}
}
Request class
public class MyRequest{
OnResponseCallback onResponseCallback= null;
public MyRequest(onResponseCallback onResponseCallback)
this.onResponseCallback = onResponseCallback;
}
public void communicate(final Context context, String url, final String typeResponse, final Intent intent) {
RequestQueue queue = Volley.newRequestQueue(context);
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest stringRequest = new StringRequest(Request.Method.POST, BASE_URL + url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
switch (typeResponse) {
case "text":
bundle.putString("response", response);
break;
case "json":
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray names = jsonObject.names();
for (int i = 0; i < names.length(); i++) {
//Toast.makeText(context, names.getString(i), Toast.LENGTH_SHORT).show();
bundle.putString(names.getString(i), jsonObject.getString(names.getString(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
onResponseCallback.onResponse(bundle);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("test", "hi!!");
return params;
}
};
queue.add(stringRequest);
}
}
and if you dont like nothing of this, maybe you can use constants or put in sharedpreferences to save your bundle object.
I hope that helps you.

How to update textview text(server data) with time interval?

I want to update data in Textview text with 5 second interval. The data should comes for server. I call the "handler" with 15000 ms interval.
Problem is few times app crass due to call handler. Please tell me is there any other process to update data with time interval. I am sending the following code which I have used.
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if(dataFromLogin.trim().equals("yes"))
{
checkUrlToFetchData(personLoginName);
}
else
{
checkUrlForExtraVideo(latestVideoID);
checkUrlToFetchDataCreaterLogin(personLoginName);
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 15000);
=============================
void checkUrlToFetchData(final String useridt)
{
RequestQueue queue = Volley.newRequestQueue(AllItemScreen.this);
String url = "http://liveapp.99emailmarketing.com/notifications/index";
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v( "response:",response);
try {
JSONObject jsonObj = new JSONObject(response);
boolean success = jsonObj.getBoolean("success");
if(success == true)
{
JSONArray notifications = jsonObj.getJSONArray("notifications");
if(notifications.length()>0)
{
JSONObject jo= notifications.getJSONObject(0);
createNotification(jo.getString("message"));
}
}
else
{
String error = jsonObj.getString("error");
Toast.makeText(AllItemScreen.this, error, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.v( "try:",e.toString());
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(AllItemScreen.this, "That didn't work!", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_id",userIdfromLogin);
return params;
}
};
queue.add(stringRequest);
}
void checkUrlToFetchDataCreaterLogin(final String useridt)
{
//Toast.makeText(this, "Validation Successfull", Toast.LENGTH_LONG).show();
RequestQueue queue = Volley.newRequestQueue(AllItemScreen.this);
String url = "http://liveapp.99emailmarketing.com/LiveNotifications/index";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the response string.
//progressDialog.dismiss();
//Toast.makeText(AllItemScreen.this, "response:"+response, Toast.LENGTH_SHORT).show();
Log.v( "response:",response);
try {
//Log.v( "try:","1");
JSONObject jsonObj = new JSONObject(response);
boolean success = jsonObj.getBoolean("success");
String profileimages="",profileimages1="",profileimages2="",profileimages3="",profileimages4="",profileimages5="";
if(success == true)
{
JSONArray notifications = jsonObj.getJSONArray("LiveNotifications");
if(notifications.length()>0)
{
JSONObject jo= notifications.getJSONObject(0);
createNotification(jo.getString("message"));
}
}
else
{
String error = jsonObj.getString("error");
Toast.makeText(AllItemScreen.this, error, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.v( "try:",e.toString());
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//progressDialog.dismiss();
Toast.makeText(AllItemScreen.this, "That didn't work!", Toast.LENGTH_SHORT).show();
}
}) {
//adding parameters to the request
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_id",userIdfromLogin);
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
void checkUrlForExtraVideo(final String checkUrlForExtraVideo)
{
RequestQueue queue = Volley.newRequestQueue(AllItemScreen.this);
String url = "http://liveapp.99emailmarketing.com/user-videos/newvideo";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the response string.
//progressDialog.dismiss();
//Toast.makeText(AllItemScreen.this, "response:"+response, Toast.LENGTH_SHORT).show();
Log.v( "response:",response);
try {
//Log.v( "try:","1");
JSONObject jsonObj = new JSONObject(response);
boolean success = jsonObj.getBoolean("success");
if(success == true)
{
int newVideo = jsonObj.getInt("newVideo");
if(newVideo>0)
{
getResourceUriRecyclerViewtruenew(swipeRefreshLayout);
}
}
else
{
String error = jsonObj.getString("error");
Toast.makeText(AllItemScreen.this, error, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.v( "try:",e.toString());
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//progressDialog.dismiss();
Toast.makeText(AllItemScreen.this, "That didn't work!", Toast.LENGTH_SHORT).show();
}
}) {
//adding parameters to the request
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("video_id",latestVideoID);
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
If you want to do some task for every 5 seconds , You can use
Handler handler = new Handler();
new Runnable()
{
#Override
public void run() {
//do your task
handler.postDelayed(this, 5000);
}
}.run();
You can try this for the 5-second timer
private Handler mCountdownHandler;
private final static int INTERVAL = 5 * 1000;
private Runnable mTimer = new Runnable() {
#Override
public void run() {
// Do something
...
...
// Reschedule the timer to execute after 5 seconds
mCountdownHandler.postDelayed(this, INTERVAL);
}
};
private void startTimer() {
stopTimer();
mCountdownHandler = new Handler(getMainLooper());
mCountdownHandler.post(mTimer);
}
private void stopTimer() {
if (mCountdownHandler != null) {
mCountdownHandler.removeCallbacks(mTimer);
mCountdownHandler = null;
}
}
Don't forget to free the handler when you destroy the activity
#Override
protected void onDestroy() {
super.onDestroy();
stopTimer();
}

Multiple request at android volley

I get an error when I make multiple volley requests.
First, I am requesting login and it works fine. After the login process, the main activity opens in the application. When I make a new request here, the request is added to the queue. But the request is not executed. what is the reason of this?
This code is login function:
private void LoginUser(final String email, final String password) {
String tag_string_req = "request_register";
pDialog.setMessage("Giriş Yapılıyor ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONObject user = jObj.getJSONObject("user");
int userId = user.getInt("UserId");
int uId = user.getInt("UId");
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("UserId", userId);
intent.putExtra("UId", uId);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("message");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
hideDialog();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
strReq.setShouldCache(false);
LoginApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
This code is get datas about user at after login function:
public void Sync(final Context context, final int uId)
{
String tag_string_req = "request_syncUser";
db1 = new Database(context);
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//gelen tüm verileri local db ye at
try {
SQLiteDatabase db = db1.getWritableDatabase();
JSONObject jObj = new JSONObject(response);
JSONArray responseUser = jObj.getJSONArray("user");
boolean error = jObj.getBoolean("error");
String message = jObj.getString("message");
if(!error) {
for(int i=0; i<responseUser.length(); i++)
{
JSONObject user = responseUser.getJSONObject(i);
String u_name = user.getString("Name");
String u_surname = user.getString("Surname");
String u_email = user.getString("Email");
String u_password = user.getString("Password");
String u_isLogin = user.getString("isLogin");
String u_isSync = user.getString("isSync");
int u_uId = user.getInt("UId");
ContentValues cv = new ContentValues();
cv.put("Name", u_name);
cv.put("Surname", u_surname);
cv.put("Email", u_email);
cv.put("Password", u_password);
cv.put("isLogin", u_isLogin);
cv.put("isSync", u_isSync);
cv.put("UId", u_uId);
db.insertOrThrow("user", null, cv);
Toast.makeText(context, message ,Toast.LENGTH_LONG).show();
Toast.makeText(context, u_name + u_surname,Toast.LENGTH_LONG).show();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("uId", String.valueOf(uId));
return params;
}
};
strReq.setShouldCache(false);
LoginApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
Well we need to see your code?
That said my guess is you are not creating / accessing your queue in a singleton pattern. Complete guess. Always always always post code.

Categories

Resources