Android Volley php mysql - android

I read this tutorial. But I have problem when press login or register Button doesn't display message from StringRequest.
StringRequest stringRequest = new StringRequest(Request.Method.POST, login_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
if(code.equals("login_failed")){
builder.setTitle("Login Error");
displayAlert(jsonObject.getString("message"));
}
else {
//Intent intent = new Intent(MainActivity.this, LoginSuccess.class);
Bundle bundle = new Bundle();
bundle.putString("name", jsonObject.getString("name"));
bundle.putString("email", jsonObject.getString("email"));
startActivity(new Intent(MainActivity.this, LoginSuccess.class).putExtras(bundle));
//intent.putExtras(bundle);
//startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}
);

try this:
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = "login_url";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
if(code.equals("login_failed")){
builder.setTitle("Login Error");
displayAlert(jsonObject.getString("message"));
}
else {
//Intent intent = new Intent(MainActivity.this, LoginSuccess.class);
Bundle bundle = new Bundle();
bundle.putString("name", jsonObject.getString("name"));
bundle.putString("email", jsonObject.getString("email"));
startActivity(new Intent(MainActivity.this, LoginSuccess.class).putExtras(bundle));
//intent.putExtras(bundle);
//startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
String userName = edtUserName.getText().toString();
String password = edtPassword.getText().toString();
if (userName.length() > 0 && password.length() > 0) {
MyData.put("username", userName);
MyData.put("password", password);
}
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);

Related

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.

doinBackground cannot save field values

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);
}
}

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.

how to retrieve mobilenumber from Mysql using Json in Android

I am Using JSON to retrieve details(fname,email,bikeno,mobileno) from MySQL database when user login. All details are retreiving except mobile number.
My Code is :
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("Logging You in");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, login_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject jsonObject1= jsonArray.getJSONObject(0);
String code = jsonObject.getString("code");
if (code.equals("login_failed")) {
builder.setTitle("Login Error");
displayAlert(jsonObject.getString("message"));
} else {
Intent intent = new Intent(MainActivity.this, Home.class);
Bundle bundle = new Bundle();
bundle.putString("email1", jsonObject.getString("email"));
bundle.putString("bikeno1", jsonObject.getString("bikeno"));
bundle.putString("fname", jsonObject.getString("fname"));
bundle.putString("mobileno", jsonObject.getString("mobileno"));
intent.putExtras(bundle);
startActivity(intent);
finish();
}
} catch(Exception e){
}
}
}
});
My Question is how to get mobile number and how to send that value to another activity?
Check this out:
php:
<?php
$sql = "SELECT * FROM tablename";
require_once('connectionphp.php');
$r = mysqli_query($conn,$sql);
$result1 = array();
while($row = mysqli_fetch_array($r)){
array_push($result1,array(
'mobilenum'=>$row['mobilenum']
));
}
echo json_encode($result1);
and try to retrive it in your java like this:
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(Activity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Activity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String , String>();
params.put(KEY_MOBILE, mobilenum);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
and get the bundle like this in next Activity:
Bundle extras = getIntent().getExtras();
if(extras != null){
mob= extras.getString("mobileno");
}

Categories

Resources