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");
}
Related
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.
MY function content to make jsonArrayRequest is:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,
FilesUsed.url_display_thought, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jsonObject1 = response.getJSONObject(0);
JSONObject jsonObject2 = response.getJSONObject(1);
if (jsonObject1.getBoolean("error")) {
ArrayList<String> list = new ArrayList<>();
list.add(jsonObject2.getString("message"));
displayThought(list);
} else {
int count = 0;
ArrayList<String> list = new ArrayList<>();
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
String thought = jsonObject.getString("post");
list.add(thought);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
displayThought(list);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", "sainiakshay04");
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(jsonArrayRequest);
The content of the php it is using is:
require_once '../app/display_personal_account.php';
$response=array();
if(isset($_POST['email'])){
$db = new display_personal_account($_POST['email']);
$res=$db->get_info_added("shared_content");
if($res==1){
$response=$db->display_shared_content();}
else{
$response[]['error']=true;
$response[]['message']="No Content To Display ";}
}
else{
$response[]['error']=true;
$response[]['message']="ERROR: INVALID REQUEST";
}
echo json_encode($response);
?>
but the output it is displaying is ERROR:INVALID REQUEST, although I'm binding email using getParams, isset of php is not working and going to else part.
HELP!
You're checking isset($_POST['email']) but you send null parameter in the JsonArrayRequest.
For now, JsonArrayRequest only supports the JsonArray parameter.
There are two things that you need to do :
Send the email in the JsonArray parameter
JSONObject request = new JSONObject();
request.put("email", userEmail);
JSONArray arrayParam = new JSONArray();
arrayParam.put(request);
....
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,
FilesUsed.url_display_thought, arrayParam, ...
Get the email in the PHP
require_once '../app/display_personal_account.php';
$response=array();
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
if(isset($input[0]['email'])){
$db = new display_personal_account($input[0]['email']);
....
After that, you should just work fine :)
final ProgressDialog loading = ProgressDialog.show(Login.this, "Verifying", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
loading.dismiss();
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(Login.this, Success.class);
Bundle bundle = new Bundle();
bundle.putString("name", jsonObject.getString("name"));
bundle.putString("email", jsonObject.getString("email"));
intent.putExtras(bundle);
startActivity(intent);
}
}
change Response.Listner<String> to JSONArray like below code
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
loading.dismiss();
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(Login.this,Success.class);
Bundle bundle=new Bundle();
bundle.putString("name",jsonObject.getString("name"));
bundle.putString("email",jsonObject.getString("email"));
intent.putExtras(bundle);
startActivity(intent);
}
because you are trying to parse String data into JSONArray.
here
JSONArray jsonArray=new JSONArray(response);
change this to
JSONObject jsonObject =new JSONObject(response);
I guess the value in the variable response holds some other value other than array.
try using json object and print/debug the value.
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
loading.dismiss();
JSONObject jsonObj = new JSONObject(response);
}
}
}
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.
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);