I am trying to use Volley to send 3 strings to a php script that sends it to a localhost server. I have this so far;
RegisterRequest;
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://192.168.*.*:80/phptesting/Register.php";
private Map<String, String> params;
public RegisterRequest(String username, String password,String isAdmin,
Response.Listener<String> listener,
Response.ErrorListener errListener){
super(Method.POST, REGISTER_REQUEST_URL,listener,errListener);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("isAdmin",isAdmin+"");
}
public Map<String, String> getparams() {
return params;
}
}
This is CreateUser;
public class CreateUser extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
this.setTitle("Create User");
final EditText username1 = findViewById(R.id.Createusername);
final EditText password1 = findViewById(R.id.CreatePassword);
final Switch isAdmin = findViewById(R.id.isadmin);
final Button createuser = findViewById(R.id.createuserbtn);
if (getIntent().hasExtra("com.example.northlandcaps.crisis_response")){
isAdmin.setVisibility(View.GONE);
}
createuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = username1.getText().toString();
final String password = password1.getText().toString();
final String isadmin = isAdmin.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response Value: ", response);
if (response.equals("success")){
Intent intent = new Intent(CreateUser.this, MainActivity.class);
CreateUser.this.startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
}
};Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), String.valueOf(error), Toast.LENGTH_SHORT).show();
}
};
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener,errorListener);
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
queue.add(registerRequest);
}
});
}
Now, the only error im getting is an Undefined index. And thats because Volley isnt sending data to the php script. The php script does work properly when data is sent to it, so my question is this; what changes do i have to make to my script for it to send the 3 strings over?
Never mess with code or else it will be confusing for you to handle things properly.
So just make another class and use it in your activity.
Have a look at this class I have written, you can use it anywhere and for any type of data request.
public class SendData {
private Context context;
private String url;
private HashMap<String, String> data;
private OnDataSent onDataSent;
public void setOnDataSent(OnDataSent onDataSent) {
this.onDataSent = onDataSent;
}
public SendData(Context context, String url, HashMap<String, String> data) {
this.context = context;
this.url = url;
this.data = data;
}
public void send(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(onDataSent != null){
onDataSent.onSuccess(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(onDataSent != null){
onDataSent.onFailed(error.toString());
}
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.putAll(data);
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, 0, 0));
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
public interface OnDataSent{
void onSuccess(String response);
void onFailed(String error);
}
}
And now you can easily use it from any activity. Just give data in the constructor and use the interface to track the events this way
HashMap<String, String> data = new HashMap<>();
data.put("username", "");//define the value
data.put("password", "");//define the value
data.put("is_admin", "");//define the value
SendData sendData = new SendData(this, "", data); //defie the context and url properly
sendData.setOnDataSent(new SendData.OnDataSent() {
#Override
public void onSuccess(String response) {
//parse the response
}
#Override
public void onFailed(String error) {
//something went wrong check the error
}
});
sendData.send();
Related
I'm writing a class with requests to rest API (Yandex disk). I use volley, but I do have some problems with getting a response from it. You can check the rest API here.
I use volley and I can get a response in the debugger, but not in my Activity.
Here is my Requests class
class Requests {
private String response_of_server, token;
private String url = "https://cloud-api.yandex.net/v1/disk";
private Context context;
Requests (String token, Context context) {
this.token = token;
this.context = context;
}
private void set_response_of_server(String response) {
this.response_of_server = response;
}
String get_response() {
return response_of_server;
}
void get_metadata_of_user() {
try {
/*Request*/
RequestQueue queue = Volley.newRequestQueue(this.context);
Response.ErrorListener error_listener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
Response.Listener<String> response_listener = new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
set_response_of_server(response);
}
};
StringRequest getRequest = new StringRequest(Request.Method.GET, url+"?fields=user", response_listener, error_listener) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Host", "cloud-api.yandex.net");
params.put("Authorization", token);
return params;
}
};
queue.add(getRequest);
/*Request end*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the MainActivity where I want my response.
public class MainActivity extends AppCompatActivity {
private final String ID_OF_APP = "Your token of app";
private final String URL_FOR_CODE_QUERY = "https://oauth.yandex.com/authorize?response_type=token&client_id=" + ID_OF_APP;
private String SAVED_TOKEN = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_get_code = findViewById(R.id.btn_get_code); // send to get code page (yandex)
btn_get_code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(URL_FOR_CODE_QUERY));
startActivity(i);
}
});
Button btn_sign_in = findViewById(R.id.btn_sign_in);
btn_sign_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText code_field = findViewById(R.id.code_field);
String token = code_field.getText().toString();
save_token(token);
try {
if(check_token()) {
//Toast.makeText(MainActivity.this, "You are successfully signed in", Toast.LENGTH_SHORT).show();
// TODO change activity
}
else {}
} catch (InterruptedException e) {
e.printStackTrace();
}
//Toast.makeText(MainActivity.this, "Something went wrong. Please, check your connection and try again later", Toast.LENGTH_SHORT).show();
}
});
}
private void save_token(String token) {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(SAVED_TOKEN, token);
ed.apply();
}
private String load_token() {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
return sPref.getString(SAVED_TOKEN, "");
}
private boolean check_token() throws InterruptedException {
String token = load_token();
String result;
Requests request = new Requests(token, this);
request.get_metadata_of_user();
result = request.get_response();
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
return !(result.equals("-1"));
}
}
check_token() function at the moment should just make a toast with a response of the server. However, I cannot get the Toast or any response coming back from the server.
You have a Requests class which has the function to call the server API which is Asynchronous. Hence, you will not get the result immediately after calling the request.get_metadata_of_user(); in your check_token() function.
Hence I would like to suggest you modify your Request class like the following.
public class Requests {
private String response_of_server, token;
private String url = "https://cloud-api.yandex.net/v1/disk";
private Context context;
private HttpListener listener; // Add a listener to get the callback functionality
Requests (String token, Context context, HttpListener listener) {
this.token = token;
this.context = context;
this.listener = listener; // initialize the listener here
}
private void set_response_of_server(String response) {
this.response_of_server = response;
listener.onResponseReceived(response); // Send the response back to the calling class
}
String get_response() {
return response_of_server;
}
void get_metadata_of_user() {
try {
RequestQueue queue = Volley.newRequestQueue(this.context);
Response.ErrorListener error_listener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
Response.Listener<String> response_listener = new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
set_response_of_server(response);
}
};
StringRequest getRequest = new StringRequest(Request.Method.GET, url+"?fields=user", response_listener, error_listener) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Host", "cloud-api.yandex.net");
params.put("Authorization", token);
return params;
}
};
queue.add(getRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now the HttpListener class might look like the following. Create HttpListener.java and add the following code to create this as an interface.
public interface HttpListener {
public void onResponseReceived();
}
Hence you need to implement this interface in your MainActivity like the following.
public class MainActivity extends AppCompatActivity implements HttpListener {
private final String ID_OF_APP = "Your token of app";
// I fixed this part too. Please change if that is not useful
private final String URL_FOR_CODE_QUERY = "https://oauth.yandex.com/authorize?response_type=" + SAVED_TOKEN + "&client_id=" + ID_OF_APP;
private String SAVED_TOKEN = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ... I omitted some code
Button btn_sign_in = findViewById(R.id.btn_sign_in);
btn_sign_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText code_field = findViewById(R.id.code_field);
String token = code_field.getText().toString();
save_token(token);
try {
// if(check_token()) {
// The check_token function call is Async. This will not return immediately. Hence you might consider removing this if part. Simply just call the function and listen to the callback function when the response is received
// }
check_token(); // Simply call the function here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
private void save_token(String token) {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(SAVED_TOKEN, token);
ed.apply();
}
private String load_token() {
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
return sPref.getString(SAVED_TOKEN, "");
}
// I changed the return type as this is not returning anything.
private void check_token() throws InterruptedException {
String token = load_token();
String result;
Requests request = new Requests(token, this);
request.get_metadata_of_user();
// You will not get the response immediately here. So omit these codes.
// result = request.get_response();
// Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
// return !(result.equals("-1"));
}
#Override
public void onResponseReceived(String response) {
// Here is your response. Now you can use your response
// and can perform the next action here.
}
}
Please note that, the code is not tested. Please modify as per your requirement. I hope that helps you to understand the problem.
I have a super basic register script in android studio. Im trying to get it to connect to a php file located in the Localhost of XAMMP. My question is unique because i directing my script to a specific localhost url, not searching on the internet. The URL is accurate too, unless it has to be changed BACK to being localhost(not ip). The error code is
E/Create User: com.android.volley.NoConnectionError:
java.io.EOFException
here is the register request;
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://(ip address):3306/testing/Register.php";
private Map<String, String> params;
public RegisterRequest(String username, String password,String isAdmin,
Response.Listener<String> listener,
Response.ErrorListener errListener){
super(Method.POST, REGISTER_REQUEST_URL,listener,errListener);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("isAdmin",isAdmin+"");
}
public Map<String, String> getparams() {
return params;
}
}
here is the CreateUser class;
public class CreateUser extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
this.setTitle("Create User");
final EditText username1 = findViewById(R.id.Createusername);
final EditText password1 = findViewById(R.id.CreatePassword);
final Switch isAdmin = findViewById(R.id.isadmin);
final Button createuser = findViewById(R.id.createuserbtn);
if (getIntent().hasExtra("com.example.northlandcaps.crisis_response")){
isAdmin.setVisibility(View.GONE);
}
createuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = username1.getText().toString();
final String password = password1.getText().toString();
final String isadmin = isAdmin.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Intent intent = new Intent(CreateUser.this, MainActivity.class);
startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener,errorListener);
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
queue.add(registerRequest);
}
});
}
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), String.valueOf(error), Toast.LENGTH_SHORT).show();
Log.e("Create User", error+"");
}
};
The php file, like i said, is inside htdocs inside of XAMMP. both apache and mysql are running, however, someone said i may not have my php script invoked by apache. Or that php even enabled on my Apache server.
try this
int socketTimeout = 500000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
// Creating RequestQueue.
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
// Adding the StringRequest object into requestQueue.
queue.add(registerRequest);
I am trying to create a register activity which uses volley and PHP to connect to mySQL. I have attached some of the code. The code works perfectly fine till i try to get the response back from the Database. While using StringRequest, the control is not entering this section of the code. How can i fix this problem? Please Help.
public class RegisterActivity extends AppCompatActivity {
String rurl = "http://102.160.2.104/register.php";
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etName = (EditText) findViewById(R.id.etName);
....
final EditText weig = (EditText) findViewById(R.id.weight);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
...
if(!(conpassword.equals(password))){
etPassword.setText("");
etconpas.setText("");
Toast.makeText(getApplicationContext(),"Passwords don't match",Toast.LENGTH_LONG).show();
}
//The problem arises over here as it does not enter the onResponse() method.
StringRequest stringRequest = new StringRequest(Request.Method.POST, rurl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
message = jsonObject.getString("message");
fin();
} catch (JSONException e) {
System.out.println("hhellooo");
e.printStackTrace();
}
}
private void fin() {
System.out.println(message);
if(message.equals("User already exists")){
etName.setText("");
etPassword.setText("");
contact.setText("");
etUsername.setText("");
age.setText("");
heig.setText("");
weig.setText("");
Toast.makeText(getApplicationContext(),"User already Exists",Toast.LENGTH_LONG).show();
}
else
{
Intent intent = new Intent(RegisterActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("name",name);
params.put("username",username);
params.put("password",password);
params.put("value", finalValue);
params.put("phone", String.valueOf(phone));
params.put("years", String.valueOf(years));
params.put("height", String.valueOf(height));
params.put("weight", String.valueOf(weight));
return params;
}
};
MySingleton.getInstance(RegisterActivity.this).addtoRQ(stringRequest);
}
});
}
The MySingleton class file to add the request into the queue.
class MySingleton {
private static MySingleton mInstance;
private static RequestQueue requestQueue;
private Context context;
private MySingleton(Context ctx) {
context = ctx;
requestQueue = getRequestQueue();
}
private RequestQueue getRequestQueue() {
if(requestQueue==null)
{
requestQueue = Volley.newRequestQueue(context.getApplicationContext());
}
return requestQueue;
}
static synchronized MySingleton getInstance(Context con){
if(mInstance==null)
{
mInstance = new MySingleton(con);
}
return mInstance;
}
<T>void addtoRQ(Request<T> request) {
requestQueue.add(request);
}
I think your request is not being sent because you haven't added it to a request queue.
RequestQueue mRequestQueue;
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
<Your request setup>
// Add the request to the RequestQueue.
mRequestQueue.add(stringRequest);
From: Android Developer
I want to move GET method inside (if) that located inside onResponse of POST request without calling URL again because once the user post edittext php file will echo json result that will show up inside listview in activity so if call URL again in other method nothing will show up, how can I do that please?
public class supportActivity extends AppCompatActivity implements View.OnClickListener{
private EditText ticketsupport;
private Button button;
private List<supportContent> con = new ArrayList<supportContent>();
private ListView supportlist;
private supportAdapter adapter;
private String ticketinput;
private String url = "http://10.0.3.2/aalm/getticket.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_support);
ticketsupport = (EditText)findViewById(R.id.insertticketnumber);
supportlist = (ListView)findViewById(R.id.supportlistview);
adapter = new supportAdapter(this, con);
supportlist.setAdapter(adapter);
button = (Button)findViewById(R.id.buttonsupprt);
button.setOnClickListener(this);
}
private void inquiry() {
ticketinput = ticketsupport.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("responseticket")) {
showTicket();
} else {
Toast.makeText(supportActivity.this, "Check the number please", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(supportActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticknumber", ticketinput);
return map;
}
};
RequestQueue requestQueue1 = Volley.newRequestQueue(getApplicationContext());
requestQueue1.add(stringRequest1);
}
private void showTicket(){
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("responseticket");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject ticket = jsonArray.getJSONObject(i);
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
con.add(support);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "Volley");
}
}
);
requestQueue2.add(jsonObjectRequest);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View view){
inquiry();
}
}
I am trying send post request in Json using StringRequest.I desing Jersey Servlet in java and I created android project in android studio.
I can send json object with Poster Plugin in Chrome but I cant android client.
Please help me.
Jersey Servlet:
#Path("/register")
public class RegisterServlet {
#POST
#Path("/add")
#Consumes(MediaType.APPLICATION_JSON)
public Response addUser(UserDTO user){
if((user.getUsername()=="") || (user.getEmail()=="") || (user.getPassword()=="")){
Logger.getLogger(RegisterServlet.class).info("Name or Email or Password is empty");
return Response.status(200).entity("empty").build();
}
if(Service.getInstance().addUser(user)){
Logger.getLogger(RegisterServlet.class).info("Added User --> username: "+user.getUsername()+"email: "+user.getEmail());
return Response.status(200).entity("add").build();
}else{
Logger.getLogger(RegisterServlet.class).info("Error Add User");
return Response.status(200).entity("error").build();
}
}
}
Android Code ;
private void postUser(final String username,final String email,
final String password,final String dep_name){
String tag_string_req = "req_register";
StringRequest strReq = new StringRequest(Method.POST,
"http://192.168.56.1:8080/ServerApp/register/add", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
} catch (Exception 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() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", username);
params.put("email", email);
params.put("password", password);
params.put("dep_name", dep_name);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
AppController in Android;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}