Android Volley URL with parameters - android

I have written a code using a volley library (GET) and I have to fetch the data from the rest API in Django.
Actually the problem is i am getting a user id while i login , i just saved that id through shared preferences and i have to pass the id in the URL to get wallet details but i am getting error
BasicNetwork.performRequest: Unexpected response code 403
public class Wallet extends AppCompatActivity {
TextView all_tv1;
Button credit_bt, debit_bt;
SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
setContentView(R.layout.activity_wallet);
pref=getApplication().getSharedPreferences("Options", MODE_PRIVATE);
Integer Key_UserID=pref.getInt("UserId_Value", 0);
// String a = Key_UserID.toString();
/Json Request/
String uri = "http://staging.exol.in/wallet/wallet/api/wallet-detail/+Key_UserID";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, uri, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(getApplicationContext(),"stop",LENGTH_SHORT).show();
// String data = "";
try {
for(int i=0; i< response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
String tnx_id = obj.getString("tnx_id");
String transition_type = obj.getString("transition_type");
// String email = obj.getString("email");
// System.out.print("\nggtrgtg"+user+"\ngfg"+amount);
Toast.makeText(getApplicationContext(),tnx_id + transition_type ,LENGTH_SHORT).show();
// data = "" + id + "" + name + "" + email + "";
//txtDisplay.setText(txtDisplay.getText()+"\n" + id + "" + name + "\n" + email + "");
// Adds the data string to the TextView "results"
}
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),"Faled Misreably" ,LENGTH_SHORT).show();
}
});
//add request to queue
requestQueue.add(jsonArrayRequest);
setTitle("Wallet Window");
Toolbar toolbar1 = (Toolbar)findViewById(R.id.tool_bar);
setSupportActionBar(toolbar1);
all_tv1 = (TextView)findViewById(R.id.all_tv);
all_tv1.setMovementMethod(new ScrollingMovementMethod());
credit_bt = (Button)findViewById(R.id.credit_details1__bt);
debit_bt = (Button) findViewById(R.id.debit_details1__bt);
credit_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Credit Tab", LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Wallet_Credit.class);
startActivity(i);
finish();
}
});
debit_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Debit Tab", LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Wallet_Debit.class);
startActivity(i);
finish();
}
});
}
}

Your uri string is not set properly (notice the closing "). Instead of
String uri = "http://staging.exol.in/wallet/wallet/api/wallet-detail/+Key_UserID";
It should be
String uri = "http://staging.exol.in/wallet/wallet/api/wallet-detail/"+Key_UserID;

Related

How to send response of a volley POST request called from one activity to another in android

Requirement:
In Android app code, in MainActivity, I want to call a REST POST API through Volley and then pass the JSON response as it is in next Activity. But the response which gets passed is blank. The code is:
Please note that
System.out.println(globalOutput); //THIS DOESN'T PRINT ANYTHING
public class MainActivity extends AppCompatActivity {
public static final String LOGIN_RESULT = "com.example.awgpusers2.loginResult";
static String globalOutput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void login(View view) throws Exception {
EditText emailEditText = findViewById(R.id.editTextTextEmailAddress2);
EditText phoneEditText = findViewById(R.id.editTextPhone2);
EditText passwordEditText = findViewById(R.id.editTextTextPassword);
String emailAddress = emailEditText.getText().toString();
String phone = phoneEditText.getText().toString();
String password = passwordEditText.getText().toString();
makePostCall(emailAddress, phone, password, new VolleyCallback() {
#Override
public void onSuccess(String result) {
System.out.println("result " + result);
globalOutput = result;
System.out.println("globalOutput " + globalOutput);
}
});
System.out.println(globalOutput); //THIS DOESN'T PRINT ANYTHING
Intent intent = new Intent(this, LoginNextActivity.class);
intent.putExtra(LOGIN_RESULT, globalOutput);
startActivity(intent);
}
void makePostCall(String emailAddress, String phone, String password, final VolleyCallback callback) throws Exception {
//String globalOutput;
String postUrl = "http://18.188.180.148:8080/auth/login";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JSONObject postData = new JSONObject();
try {
postData.put("email", emailAddress);
postData.put("password", password);
postData.put("phoneNumber", phone);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, postUrl, postData, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
callback.onSuccess(response.toString());
}
}, new Response.ErrorListener() {
........................
});
requestQueue.add(jsonObjectRequest);
}
}
Please help
makePostCall() method is asynchronous function.
So you need to process in callback function.
public void login(View view) throws Exception {
EditText emailEditText = findViewById(R.id.editTextTextEmailAddress2);
EditText phoneEditText = findViewById(R.id.editTextPhone2);
EditText passwordEditText = findViewById(R.id.editTextTextPassword);
String emailAddress = emailEditText.getText().toString();
String phone = phoneEditText.getText().toString();
String password = passwordEditText.getText().toString();
makePostCall(emailAddress, phone, password, new VolleyCallback() {
#Override
public void onSuccess(String result) {
System.out.println("result " + result);
globalOutput = result;
System.out.println("globalOutput " + globalOutput);
System.out.println(globalOutput); //THIS DOESN'T PRINT ANYTHING
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, LoginNextActivity.class);
intent.putExtra(LOGIN_RESULT, globalOutput);
startActivity(intent);
}
});
}
});
}
Your System.out.println is executed before Volley returns the response. Volley's enqueue method is asynchronous, i.e. you can't tell exactly when it'll be executed.
Move
System.out.println(globalOutput); //THIS DOESN'T PRINT ANYTHING
Intent intent = new Intent(this, LoginNextActivity.class);
intent.putExtra(LOGIN_RESULT, globalOutput);
startActivity(intent);
Into the onSuccess method of the VolleyCallback

Volley no response from HTTP GET

I'm trying to retrieve the JSON from an API but I'm not getting anything.
The JSON :
{"coord":{"lon":90.41,"lat":23.71},"weather":[{"id":721,"main":"Haze","description":"haze","icon":"50n"}],"base":"stations","main":{"temp":25,"feels_like":28.6,"temp_min":25,"temp_max":25,"pressure":1011,"humidity":83},"visibility":3500,"wind":{"speed":1.5,"deg":90},"clouds":{"all":75},"dt":1588093825,"sys":{"type":1,"id":9145,"country":"BD","sunrise":1588029983,"sunset":1588076702},"timezone":21600,"id":1185241,"name":"Dhaka","cod":200}
I did add INTERNET permission :
<uses-permission android:name="android.permission.INTERNET" />
My code :
private void httpGet() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + CITY + "&units=metric&appid=" + API;
//https://api.openweathermap.org/data/2.5/weather?q=dhaka,bd&units=metric&appid=5694263c8d821570bfccff2a13246a73
Log.d("TEST", "Fonction lancee 1/2" + url);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TEST", "Fonction lancee 3/2" + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("TEST", "Erreur");
}
});
queue.add(jsonObjectRequest);
}
I also tested with StringRequest with the same result, no response.
EDIT
My entire classe to see the context :
public class MainActivity extends AppCompatActivity {
TextView tempTxt;
String CITY = "dhaka,bd";
String API = "5694263c8d821570bfccff2a13246a73";
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + CITY + "&units=metric&appid=" + API;
//https://api.openweathermap.org/data/2.5/weather?q=dhaka,bd&units=metric&appid=5694263c8d821570bfccff2a13246a73
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempTxt = findViewById(R.id.tempTxt);
httpGet();
//new weatherTask().execute();
Log.d("TEST", "TEST OUT CALL");
Button button2 = findViewById(R.id.definirp);
button2.setOnClickListener(new View.OnClickListener() {
//Passer a la seconde Activity
public void onClick(View v) {
Intent activity2 = new Intent(getApplicationContext(), Activity2.class);
startActivity(activity2);
finish();
}
});
//Affichage de l'heure
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView theure = (TextView) findViewById(R.id.date);
TextView tdate = (TextView) findViewById(R.id.heure);
long date = System.currentTimeMillis();
//Format de l'heure
SimpleDateFormat sdfTime = new SimpleDateFormat("hh:mm:ss");
SimpleDateFormat sdfDate = new SimpleDateFormat("MMM dd yyyy");
String timeString = sdfDate.format(date);
String dateString = sdfTime.format(date);
theure.setText(timeString);
tdate.setText(dateString);
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
}
private void httpGet() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://api.openweathermap.org/data/2.5/weather?q=" + CITY + "&units=metric&appid=" + API;
//https://api.openweathermap.org/data/2.5/weather?q=dhaka,bd&units=metric&appid=5694263c8d821570bfccff2a13246a73
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
tempTxt.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tempTxt.setText("That didn't work!");
}
});
queue.add(stringRequest);
}
You can test the page of my JSON, the address is in comment in my code, (there is a comma in the city), it works.

Why volley is not sending the values?

I'm new to android development. I'm trying to send some data to server using volley. But it is not sending parameters. Please help. The server is saying that the parameter is not set. I checked with the isset in php. When I tried sending data from a html form, it's working. But the volley is not sending the parameters.
public class MainActivity extends AppCompatActivity {
EditText uname;
EditText uotp;
RequestQueue myqueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText) findViewById(R.id.uname);
uotp = (EditText) findViewById(R.id.uotp);
myqueue = Volley.newRequestQueue(this);
}
public void sendotp(View v)
{
String unameval = uname.getText().toString();
if(unameval.matches(""))
{
Toast.makeText(getApplicationContext(), "Enter Phone Number", Toast.LENGTH_SHORT).show();
}
else
{
HashMap<String, String> params = new HashMap<>();
params.put("phone", unameval);
String myUrl = "http://privateurlhere";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, myUrl, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String dispname = response.getString("stat");
Toast.makeText(getApplicationContext(), dispname, Toast.LENGTH_SHORT).show();
}
catch(JSONException e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Resp err" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
myqueue.add(request);
}
}
}

posting data to mysql database using rest api which is done in magento 2 from my android app?

facing problem in posting data to mysql database using rest api which is done in magento 2 from my android app.
RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
private static final String URL_FOR_REGISTRATION = "https://xyz/restapi/registration";
ProgressDialog progressDialog;
private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputCnfPassword, signupInputAge;
private Button btnSignUp;
private Button btnLinkLogin;
private RadioGroup genderRadioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// Progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
signupInputCnfPassword = (EditText) findViewById(R.id.signup_input_passwords);
signupInputAge = (EditText) findViewById(R.id.signup_input_age);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitForm();
}
});
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
}
});
}
private void submitForm() {
registerUser(signupInputName.getText().toString(),
signupInputEmail.getText().toString(),
signupInputPassword.getText().toString(),
signupInputCnfPassword.getText().toString(),
signupInputAge.getText().toString());
}
private void registerUser(final String name, final String email, final String password, final String cnfpassword, final String dob) {
// Tag used to cancel the request
String cancel_req_tag = "register";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REGISTRATION, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String user = jObj.getJSONObject("user").getString("name");
Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("cust_username", name);
params.put("cust_firstname", email);
params.put("cust_pass", password);
params.put("cust_confirmpass", cnfpassword);
params.put("cust_phoneno", dob);
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
I am using Volley library for request.
I am getting this error
BasicNetwork.performRequest: Unexpected response code 503 for
https://xyz/restapi/registration.
My question is am I missing any thing or will there be constrain that should be checked in mysql to post the data.

Intent not receive data in second Activity in volley

Hey developers i am tried send the data through intent
i am sending data A activity to B activity data is send A Activity properly but B Activity is not receive but some data is receive but some data not receive
Code is A Activity
private void requestForSMS(final String mobile) {
StringRequest strReq = new StringRequest(Request.Method.POST,
config.Config.URL_REQUEST_SMS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
final String user = responseObj.getString("uid");
String message = responseObj.getString("msg");
Intent intent1 = new Intent(getApplicationContext(),HttpService.class);
intent1.putExtra("uid", user); // <---Sending data here this data not recive B Activity ------>
Log.d("user id going","====>"+user);
if(!user.equalsIgnoreCase("")){
pref.setIsWaitingForSms(true);
viewPager.setCurrentItem(1);
txtEditMobile.setText(pref.getMobileNumber());
layoutEditMobile.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"ErrorToast: " + message,
Toast.LENGTH_LONG).show();
}
// hiding the progress bar
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "ErrorResponce: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key","xxxxxxxxxxxxx");
params.put("mobile", mobile);
Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
int socketTimeout = 60000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(policy);
// Adding request to request queue
newapp.getInstance().addToRequestQueue(strReq);
}
private void verifyOtp() {
String otp = inputOtp.getText().toString().trim();
if (!otp.isEmpty()) {
Intent grapprIntent = new Intent(getApplicationContext(), HttpService.class);
// <---- sending data here also B Activity---->
grapprIntent.putExtra("key","xxxxxxxxxxxx");
grapprIntent.putExtra("mobileverify", otp);
startService(grapprIntent);
} else {
Toast.makeText(getApplicationContext(), "Please enter the OTP", Toast.LENGTH_SHORT).show();
}
}
private static boolean isValidPhoneNumber(String mobile) {
String regEx = "^[0-9]{10}$";
return mobile.matches(regEx);
}
B Activity
public class HttpService extends IntentService {
private static String TAG = HttpService.class.getSimpleName();
public HttpService() {
super(HttpService.class.getSimpleName());
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
String otp = intent.getStringExtra("mobileverify");
final String user1 = intent.getStringExtra("uid"); //<---- this is not recive value ---->
verifyOtp(otp,user1);
}
}
/**
* Posting the OTP to server and activating the user
*
* #param otp otp received in the SMS
*/
private void verifyOtp(final String otp, final String user1){
StringRequest strReq = new StringRequest(Request.Method.POST,
config.Config.URL_VERIFY_OTP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
// Parsing json object response
// response will be a json object
String message = responseObj.getString("msg");
if (message!="") {
// parsing the user profile information
JSONObject profileObj = responseObj.getJSONObject(response);
String mobile = profileObj.getString("mobile");
PrefManager pref = new PrefManager(getApplicationContext());
pref.createLogin(mobile);
Intent intent = new Intent(HttpService.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Toast.makeText(getApplicationContext(), "HTTPIF"+message, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "HTTPELSE"+message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "HTTPError: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key","xxxxxxxxxx");
params.put("mobileverify", otp);
params.put("uid",user1); // here its given error
Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);
}
Please Help me Thanks
Your grapprIntentdoesn't contain a value for "uid" key because you don't put it. You use some intent1 which is not used anywhere more. Instead you need to put "uid" into grapprIntent:
grapprIntent.putExtra("uid", user);
Maybe grapprIntent should be global variable for the class or find a way to pass it between methods.
Create A Global variable in your Application class and Use set and get Methods
like this
Application.class
private String user;
public String setuser(String usermy) {
this.user = usermy;
return null;
}
public String getuser()
{
return user;
}
where you want to send value set value like as your code
SMSActivity
MyApplication myUser = (MyApplication)getApplicationContext();
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
String user = responseObj.getString("uid");
String user1 = myUser.setuser(user);
And Get Value in your HttpService.class
Like this
MyApplication uidinfo = (MyApplication)getApplicationContext();
final String user = uidinfo.getuser();
and mention manifest.xml inside Application tag
<application
android:name=".MyApplication"
/>
happy coding

Categories

Resources