Why volley is not sending the values? - android

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

Related

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.

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.

In my code, only one link is parse, but I have four different links. How can I parse all of them

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn;
TextView price;
String url = "https://koinim.com/ticker/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn_get_information);
price = (TextView)findViewById(R.id.price);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v){
if (v.getId() == R.id.btn_get_information){
JsonObjectRequest jsonObjectRequest = new
JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
price.setText("BTC: " +
response.getString("sell")+ " " + "₺" );
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText((getApplicationContext()),"Error",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getmInstance(getApplicationContext()).
addToRequestQue(jsonObjectRequest);
}
}
}
I am a new developer in android.
I looked at the sources and made the parse from one link. But I have four links. How do I parse the four links?
Instead of having a String url, create an ArrayList of Strings that holds all your URLs.
In the method onClick() loop through the URLs.
Note that the ArrayList is filled in onCreate. I also added a try/catch clause in onClick, so if something goes wrong with one URL, the others will be parsed anyways.
Handling different URLs:
For parsing the Koinim ticker, you needed the key "sell", for Paribu you will need "last".
In the loop I am checking if the URL contains either Koinim or Paribu and adjust they key accordingly.
ArrayList<String> urls = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn_get_information);
price = (TextView) findViewById(R.id.price);
urls.add("https://koinim.com/ticker/");
urls.add("url2");
urls.add("url3");
urls.add("url4");
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_get_information) {
for (String url : urls) {
try {
JsonObjectRequest request = null;
if(url.contains("koinim"))
{
request = getSellPrice("sell");
}
else if(url.contains("paribu"))
{
request = getSellPrice("last");
}
if(request != null)
{
MySingleton.getmInstance(getApplicationContext()).
addToRequestQue(jsonObjectRequest);
}
} catch (Exception ex) {
// something went wrong, handle exception here
}
}
}
}
private JsonObjectRequest getSellPrice(String key)
{
JsonObjectRequest jsonObjectRequest = new
JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
price.setText("BTC: " +
response.getString(key) + " " + "₺");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText((getApplicationContext()), "Error", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
return jsonObjectRequest;
}

Unable to POST data to server in android using WebServices API

I want to POST data to server but i get
Volley: [1726] BasicNetwork.performRequest: Unexpected response code 415 for http://192.158.20.43:8080/Api/employee/create" error.
public class RegisterTextActivity extends AppCompatActivity {
EditText emailBox, passwordBox,firstName,lastName;
Button registerButton;
TextView loginLink;
String URL = "http://192.158.20.43:8080/Api/employee/create";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_text);
firstName=(EditText)findViewById(R.id.firstname);
lastName=(EditText)findViewById(R.id.lastname);
emailBox = (EditText)findViewById(R.id.emailBox);
passwordBox = (EditText)findViewById(R.id.passwordBox);
registerButton = (Button)findViewById(R.id.registerButton);
loginLink = (TextView)findViewById(R.id.loginLink);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>(){
#Override
public void onResponse(String s) {
if(s.equals("true")){
Toast.makeText(RegisterTextActivity.this, "Registration Successful", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(RegisterTextActivity.this, "Can't Register", Toast.LENGTH_LONG).show();
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
Toast.makeText(RegisterTextActivity.this, "Some error occurred -> "+volleyError, Toast.LENGTH_LONG).show();
}
}) {
#Override
public String getBodyContentType() {
return "application/json;charset=utf-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("firstname",firstName.getText().toString().trim());
parameters.put("lastname",lastName.getText().toString().trim());
parameters.put("email", emailBox.getText().toString().trim());
parameters.put("phone", passwordBox.getText().toString().trim());
return parameters;
}
};
RequestQueue rQueue = Volley.newRequestQueue(RegisterTextActivity.this);
/
rQueue.add(request);
}
});
loginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterTextActivity.this, LoginTestActivity.class));
}
});
}
}
API work fine in POSTMAN but not work properly here.
try changing your Content-Type
application/json;charset=utf-8
to
application/json

Why is Volley's onResponse not called

I am fetching json data through Volley. The problem I am having
is that Volley's onResponse is never called, and hence the data are not parsed and displayed.
Sample JSON data
{
"title": "This is a sample text title title",
"cat": {
"origin" : "United states",
"target" : "Asia",
},
"content": "Lorem ipsum ipsum trxt hag jlak jshss jsyts pjqgq uuqtyq usiuqjo uwywh",
}
NewsActivity
public class NewsDetails extends AppCompatActivity {
private final String TAG = "NewsDetails";
private ProgressDialog mProgresscircle;
TextView newsTitle, newsOrigin, newsContent;
//private int news_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_details);
newsTitle = (TextView) findViewById(R.id.dnews_title);
newsOrigin = (TextView) findViewById(R.id.dnews_origin);
newsContent = (TextView) findViewById(R.id.dnews_content);
if (NetworkCheck.isAvailableAndConnected(this)) {
//Calling method to load newss
loadNews();
} else {
final Context context;
context = this;
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(R.string.alert_titl);
alertDialog.setCancelable(false);
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setMessage(R.string.failed_news);
alertDialog.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(context)) {
alertDialog.show();
} else {
loadNews();
}
}
});
alertDialog.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
}
}
private void loadNews() {
Log.d(TAG, "loadNews called");
mProgresscircle = new ProgressDialog(NewsDetails.this);
mProgresscircle.setCancelable(false);
mProgresscircle.setMessage(null);
mProgresscircle.show();
int news_id = getIntent().getIntExtra("NewsId", -1);
Toast.makeText(NewsDetails.this, "News id is" + news_id, Toast.LENGTH_SHORT).show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DetailConfig.GET_DURL + news_id,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called NewsDetails");
//Dismissing progressbar;
if (mProgresscircle != null) {
mProgresscircle.dismiss();
}
//Calling method to parse json array
parseNews(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to queue
requestQueue.add(djsonArrayRequest);
}
//This method will parse json data of news
private void parseNews(JSONArray jsonArray) {
Log.d(TAG, "Parsing news array");
for (int i = 0; i<jsonArray.length(); i++) {
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString(DetailConfig.TAG_DPOST_TITLE);
newsTitle.setText(title);
JSONObject pOrigin = jsonObject.getJSONObject("cat");
String origin = pOrigin.getString("origin");
newsOrigin.setText(origin);
String content = jsonObject.getString(DetailConfig.TAG_DPOST_CONTENT);
newsContent.setText(content);
} catch (JSONException w) {
w.printStackTrace();
}
}
}
}
The things I know
In logcat, loadNews method is called.
I'm logging Volley, and from logcat volley is not complaining in anyway
I can't see "onResponse called NewsDetails" in logcat, meaning that for some reason not known to me, it's not called
So, my question is why is onResponse not called and how should I fix it?
You should use JsonObjectRequest instead of JsonArrayRequest because you are getting jsonobject in the response.
For getting more knowledge you may go through Volley tutorial
/* you are getting json in response but your response listener method is get Json Array replace your code with below code and also add an debug point in your error listener method */
private void loadNews() {
Log.d(TAG, "loadNews called");
mProgresscircle = new ProgressDialog(NewsDetails.this);
mProgresscircle.setCancelable(false);
mProgresscircle.setMessage(null);
mProgresscircle.show();
int news_id = getIntent().getIntExtra("NewsId", -1);
Toast.makeText(NewsDetails.this, "News id is" + news_id, Toast.LENGTH_SHORT).show();
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
DetailConfig.GET_DURL, requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Debug", response.toString());
//TODO parsing code
parseNews(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to queue
requestQueue.add(djsonArrayRequest);
}
// or replace this code into your into your loadNews method
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
DetailConfig.GET_DURL, requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Debug", response.toString());
//TODO parsing code
parseNews(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
**
You can also refer below link for complete tutorial http://www.hackpundit.com/android-turorial-json-parse-volley/
**

Categories

Resources