Android studio says volley.NoConnectionError: java.io.EOFException, what is this? - java

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

Related

SignUp rest service is not working when rest call is made from Android Application

I create project in android studio and use Volley for signup and login
I can login in my android app with email and password that i insert in database with phpMyadmin But signup in android doesn't insert email and password to database!
this is my LoginDialog.java code :
public class LoginDialog extends DialogFragment {
EditText edtEmail, edtPass;
Button btnSignup, btnLogin;
OnSignupClicked onSignupClicked;
View view;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
view = LayoutInflater.from(getContext()).inflate(R.layout.login_dialog, null);
setupViews();
builder.setView(view);
return builder.create();
}
private void setupViews() {
btnSignup = (Button) view.findViewById(R.id.btn_loginDialog_signup);
edtEmail = (EditText) view.findViewById(R.id.edt_loginDialog_email);
edtPass = (EditText) view.findViewById(R.id.edt_loginDialog_pass);
btnLogin = (Button) view.findViewById(R.id.btn_loginDialog_login);
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = edtEmail.getText().toString();
String pass = edtPass.getText().toString();
userSignup(email, pass);
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login(edtEmail.getText().toString(), edtPass.getText().toString());
}
});
}
private void login(final String myEmail, final String pass) {
String url = "http://192.168.1.101/login.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("not found")) {
Toast.makeText(getContext(), "پست الکترونیک یا رمز عبور اشتباه است", Toast.LENGTH_SHORT).show();
} else {
onSignupClicked.onClicked(response);
dismiss();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("LOG", "onErrorResponse: " + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", myEmail);
params.put("pass", pass);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
public void setOnSignupClicked(OnSignupClicked onSignupClicked) {
this.onSignupClicked = onSignupClicked;
}
private void userSignup(final String email, final String pass) {
String url = "http://192.168.1.101/signup.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG", "onResponse: "+response);
onSignupClicked.onClicked(response);
dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("LOG", "onErrorResponse: " + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("pass", pass);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
public interface OnSignupClicked {
void onClicked(String email);
}
}
And this my signup.php code :
<?php
include "connect.php";
$email = $_POST["email"];
$pass = $_POST["pass"];
$query = "INSERT INTO user(email,pass)VALUES (:email,:pass)";
$res=$connect->prepare($query);
$res->bindParam(":email",$email);
$res->bindParam(":pass",$pass);
$res->execute();
if($res){
echo $email;
}else{
echo "error";
}
Please guide me how can i fix signup to connect with database :X
Your server side code had bugs. I fixed it
<?php
$connection = mysqli_connect('localhost','root','password','user') or die('connecition err');
$email = $_POST['email'];
$pass = $_POST['pass'];
$sql = "INSERT INTO `user` (`email`,`pass`) VALUES ('$email','$pass')";
$query = mysqli_query($connection,$sql);
if($query){
echo $email;
}else{
echo "no";
}
?>

Show function data without blinking with Volley in Android Studio

Recently I am working on Android project with Volley for registration and for further operation, I can make function for insertion and other one is for retrieval data. When insert button click 'Insert' function called and data has been inserted to database through volley, and at the same time retrieval function also called. But when USER clicked the button and function called then data showed(database inserted data) with blinking effect, look like loading.
I want to get rid of that effect. I want to show data smoothly without any blinking effect. I do searching but can not find any solution. Please suggest me solution I'am newbie so kindly short and efficient required.
package com.darkcoderz.parsejson;
public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;
//private CoordinatorLayout mCLayout;
private TextView mTextView;
private String mJSONURLString = "http://192.168.10.4/volley/api.php";
String url = "http://192.168.10.4/volley/register.php";
private EditText sms;
private Button sendsms;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the application context
//mContext = getApplicationContext();
//mActivity = MainActivity.this;
// Get the widget reference from XML layout
//mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
mTextView = (TextView) findViewById(R.id.tv);
sms = (EditText) findViewById(R.id.sms);
sendsms = (Button) findViewById(R.id.sendsms);
final Handler firesms = new Handler();
firesms.post(new Runnable() {
#Override
public void run() {
getdata();
firesms.postDelayed(this, 100);
}
});
sendsms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reg();
}
});
getdata();
}
// insert
public void reg()
{
final String msg = sms.getText().toString();
StringRequest stringreq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success"))
{
Toast.makeText(MainActivity.this, "Registration Successfull!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Username Already Exist!", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Great Error "+error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("sms",msg);
return params;
}
};
RequestQueue reqest = Volley.newRequestQueue(MainActivity.this);
reqest.add(stringreq);
}
private void getdata() {
// Empty the TextView
mTextView.setText("");
// Initialize a new RequestQueue instance
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Do something with response
//mTextView.setText(response.toString());
// Process the JSON
try{
// Loop through the array elements
for(int i=0;i<response.length();i++){
// Get current json object
JSONObject student = response.getJSONObject(i);
// Get the current student (json object) data
// String firstName = student.getString("fname");
// String lastName = student.getString("lname");
String age = student.getString("email");
// Display the formatted json data in text view
mTextView.append("SMS : " + age);
mTextView.append("\n\n");
}
}catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
}
}
private void getdata() {
// Empty the TextView
mTextView.setText("");
// Initialize a new RequestQueue instance
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//before parsing check your response is in JSONArray Format or JSONObject format
// Process the JSON
try{
}catch (JSONException e){
e.printStackTrace();
//print here to know JSONException if exists
Toast.makeText(mContext, "Exception"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
}

How to get response from server?

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.

What would be the simplest way of posting data using Volley?

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

Unable to get a response from the backend as to my query. How can I fix this issue?

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

Categories

Resources