android Volley does not response when request again - android

all.
I am using volley to make a http request to my website server. And it works fine and response when click the commit button to add a request to request queue. But click the button again does not response. It still shows the progressdialog and response nothing. Is there something wrong ?
Here's code example below:
public class MainActivity extends ActionBarActivity {
private static final String URL = "http://www.google.com";
public RequestQueue mQueue = null;
public StringRequest request = null;
private Button mScanButton = null;
private TextView mDisplay = null;
private ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScanButton = (Button) findViewById(R.id.button_scan);
mDisplay = (TextView) findViewById(R.id.display);
request = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response retrieved");
mDisplay.setText(response);
dialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mDisplay.setText("That didn't work.");
dialog.dismiss();
}
});
request.setShouldCache(false);
mScanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "Mapping data", "please wait..");
mQueue = Volley.newRequestQueue(MainActivity.this);
mQueue.add(request);
System.out.println("Add to queue..");
}
});
}

try this May this guide you here is the complete source which helps you understand easily.
looking at this line
if (ServerConfig.isNetworkOnline(SplashScreen.this)) {
StringRequest strReq = new StringRequest(Request.Method.POST, "your server link", serverResponse, errorListener) {
};
AppController.getInstance().getRequestQueue().add(strReq);
} else {
Toast.makeText(getApplicationContext(), "Please check your network connection", Toast.LENGTH_SHORT).show();
finish();
}
you can remove those above code leaving with below code.
StringRequest strReq = new StringRequest(Request.Method.POST, "your server link", serverResponse, errorListener) {
};
AppController.getInstance().getRequestQueue().add(strReq);

I try to move the area of request declaration to on-click method and it works fine. But I still don't understand how it works.
public class MainActivity extends ActionBarActivity {
private static final String URL = "http://www.google.com";
public RequestQueue mQueue = null;
public StringRequest request = null;
private Button mScanButton = null;
private TextView mDisplay = null;
private ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScanButton = (Button) findViewById(R.id.button_scan);
mDisplay = (TextView) findViewById(R.id.display);
mScanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "Mapping data", "please wait..");
request = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response retrieved");
mDisplay.setText(response);
dialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mDisplay.setText("That didn't work.");
dialog.dismiss();
}
});
mQueue = Volley.newRequestQueue(MainActivity.this);
mQueue.add(request);
System.out.println("Add to queue..");
}
});
}

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.

Volley give me only: onErrorResponse

I start to work with volley and when i try to make a post request it give me only errore.
Can you guys tell me when im wrong?
Im working on the Android side of the project with VolleyLibrary.
public class MainActivity extends AppCompatActivity {
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Login();
}
});
}
private void Login(){
String url = "http://myapies.youcantwatch.it/loginuser_module";
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(!response.trim().equals("errors")){
Intent intent = new Intent(MainActivity.this, LoggedActivity.class);
startActivity(intent);
} else {
Toast.makeText(MainActivity.this, "Login Fallito", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "La chiamata non รจ andata a buon fine", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("firstName","adkdmadm");
params.put("password","asdasdjn");
params.put("secretKey","dlwdmkemd3d455");
params.put("username", etUsername.getText().toString().trim());
params.put("passwordasdad", etPassword.getText().toString().trim());
return super.getParams();
}
};
requestQueue.add(stringRequest);
}
}
Replace StringRequest->JSONObjectRequest and check.
Pass request parameters in JSONObject, not in the header,
only pass Content-Type->application/json in header.
change volley to another libs like retrofit volley long time not updated

Send data to laravel with Android volley

I want to send the user-id data I received with android to laravel.
codes for android;
public class MainActivity extends AppCompatActivity {
public String userId;
Button send;
private static final String KEY_USERNAME ="userId" ;
String insertUrl ="http://127.0.0.1:8000/registerDevices";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userId= "12345";
send=(Button) findViewById(R.id.buttonPush);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(), userId, Toast.LENGTH_LONG).show();
registerUser();
}
});
}
public void registerUser(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, insertUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), userId, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERNAME,userId);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
My route in laravel;
Route::post('/registerDevices', 'RegisterController#registerdevices');
public function registerdevices(Request $request)
{
\Log::info('api call from andriod');
$jsonPostedData = Input::get('userId');
return $this->service->registerdevices($jsonPostedData);
}
my code does not work and the error it gives;
java.net.ConnectException:Connection Refused
Can you help me?

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.

HTTP Post Request using Volley

I code to send some message and email using HTTP post using Volley.
when i run the emulator using Genymotion.Everything luking fine but i click the click button it show HTTP has been stopped. I am giving logcat picture Please click this Logcat picture to see Please help me what is wrong and how to resolve this problem
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String URL_CLICK = "http://www.careoservice.goyalsoftwares.com/feedback/add.php";
public static final String KEY_MESSAGE = "message";
public static final String KEY_EMAIL = "email";
private EditText editTextMessages;
private EditText editTextEmail;
private Button buttonSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextEmail = (EditText) findViewById(R.id.editmsg);
editTextEmail = (EditText) findViewById(R.id.editmail);
buttonSend = (Button) findViewById(R.id.btnclk);
buttonSend.setOnClickListener(this);
}
public void sendView() throws JSONException {
final String message = editTextMessages.getText().toString().trim();
final String email = editTextEmail.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_CLICK, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Toast.makeText(MainActivity.this,s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_MESSAGE, message);
params.put(KEY_EMAIL, email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View v) {
if (v == buttonSend) {
try {
sendView();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
You are not initialazing the "editTextMessages", this is your null pointer exception.

Categories

Resources