i have a registration form for my app and the volley sends the request to the php file on the server and i see the user registered on the database, but the response listener does not receive the response which allows it to go back to homepage
this is my android code
if (rdPassword.equals(rdPassword2)) {
if(rdEmail.matches(emailPattern)||rdEmail.matches(emailPattern2)){
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
System.out.println(response);
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
pd.dismiss();
Intent bktohome = new Intent(driver_registration.this, home.class);
bktohome.putExtra("company", rdCompany);
startActivity(bktohome);
finish();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(driver_registration.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DriverRegistration registerRequest = new DriverRegistration(rdUsername, rdPassword, rdName, rdEmail,
rdMobile, rdCompany, rdAddress, rdSSN, rdDLN,rdImage_encoded, responseListener);
RequestQueue queue = Volley.newRequestQueue(driver_registration.this);
queue.add(registerRequest);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(driver_registration.this);
builder.setMessage("Wrong Email Format...")
.setNegativeButton("Retry",null)
.create()
.show();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(driver_registration.this);
builder.setMessage(" Passwords do not match")
.setNegativeButton("Retry", null)
.create()
.show();
}
DriverRegistration class
public class DriverRegistration extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://trackitfinal.hostei.com/registerDriver.php";
private Map<String , String> params;
public DriverRegistration(String username , String password , String name , String email , int mobile , String company , String address ,
int SSN , int DLN,String rdImage_encoded, Response.Listener<String> listener)
{
super(Method.POST,REGISTER_REQUEST_URL,listener,null);
params=new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("name",name);
params.put("email",email);
params.put("mobile",mobile+"");
params.put("company",company);
params.put("address",address);
params.put("SSN",SSN+"");
params.put("DLN",DLN+"");
params.put("image",rdImage_encoded);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
check if your Api is working and sending proper response when User hit it or it may be just updating DB.and is there Api for getting user detail you can check it by hitting it or check it in the postman.
Related
I want to make an app that the user enter information and it upload it to a google sheet file. I have a google app script which works (I runed it with values) and a code in Java for the app which don't work.. I will be very please if someone can help me understand what I do wrong
Thanks, Ido
Google app script
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1jCxPiqvHOwVJrWdzY_Ccy49i-rtOD8AeFrf53KwN3OQ/edit#gid=0")
var sheet = ss.getSheetByName('Users');
function doPost(e){
var action = e.parameter.action;
if(action == 'addUser'){
return addItem(e);
}
}
function addItem(e){
var name = e.paramete.vName;
var phone = e.parameter.vPhone;
var area = e.parameter.vArea;
sheet.appendRow([name, phone, area]);
return ContentService.createTextOutput("Success").setMimeType(ContentService.MimeType.TEXT);
}
Java Code
public void addUserData(){
String name = fullName.toString();
String phone = phoneNumber.toString();
String area = place;
StringRequest stringRequest = new StringRequest(Request.Method.POST, "URL", new Response.Listener<String>(){
#Override
public void onResponse(String response) {
Intent intent = new Intent(getApplicationContext(), CorrectActivity.class);
startActivity(intent);
progressDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Intent intent = new Intent(getApplicationContext(), FailedActivity.class);
startActivity(intent);
progressDialog.hide();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put("action", "addUser");
params.put("vName", name);
params.put("vPhone", phone);
params.put("vArea", area);
return params;
}
};
int socketTimeOut = 50000;
RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeOut,0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
devs hope all are fine and shine I am stuck into a problem of hitting the URL of my API from onclick method. I want to send the JWT token in the header and the value of my id on the click of the layout. API accept header and id argument. I am unable to do this as I am very new to the programming world any help from you people must be most appreciated thanks:
Below my function code :
profile.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String str = taginput.getText().toString();
tag_id = taginput.getText().toString();
session = new SessionManager(getApplicationContext());
//I want to send these two things to the next activity JWT to haders and id to hit api
token = session.getStringData("jwtToken");
id = session.getStringData("mtagid");
if(!str.isEmpty()) {
session = new SessionManager(getApplicationContext());
token = session.getStringData("jwtToken");
tag_id = session.getStringData("tagid");
Intent intent = new Intent(getApplicationContext(), CInfo.class);
startActivity(intent);
}
else {
Toast.makeText(getApplicationContext(),
"Please Enter CNIC first!", Toast.LENGTH_LONG)
.show();
}
}
});
The class where API call and all the functionality is written is given below :
public class CInfo extends AppCompatActivity {
private String TAG = CInfo.class.getSimpleName();
private ProgressDialog pDialog;
private static final int MY_SOCKET_TIMEOUT_MS = 50000;
ListView listView;
List<ConstantClass> constantClassList;
ProgressBar progressBar;
private RequestQueue mRequestQueue;
private SessionManager session;
String token;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c_info);
Bundle extras = getIntent().getExtras();
listView=(ListView)findViewById(R.id.listView);
progressBar=(ProgressBar)findViewById(R.id.progress);
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
constantClassList=new ArrayList<>();
sendAndRequestResponse();
session = new SessionManager(getApplicationContext());
token = session.getStringData("jwtToken");
}
private void sendAndRequestResponse() {
mRequestQueue= Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest ( Request.Method.POST, AppConfig.URL_CARS_INFO+DemoClass.tag_id, null, new Response.Listener<JSONObject> () {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray ( "result" );
for (int i = 0; i < jsonArray.length (); i++) {
JSONObject jsonObject = jsonArray.getJSONObject ( i );
String ownername = jsonObject.getString ( "ownername" );
String tokenno = jsonObject.getString ( "tokenno" );
String registration = jsonObject.getString ( "registration" );
String cnic = jsonObject.getString("cnic");
String balance = jsonObject.getString("balance");
String veh_type = jsonObject.getString("veh_type");
ConstantClass constantClass=new ConstantClass(ownername,tokenno,registration,cnic,balance,veh_type);
constantClassList.add(constantClass);
}
CustomAdapter customAdapter=new CustomAdapter(CInfo.this,constantClassList);
listView.setAdapter(customAdapter);
} catch (JSONException e) {
e.printStackTrace ();
}
}
}, new Response.ErrorListener () {
#Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
// Show timeout error message
Toast.makeText(CInfo.this,
"Oops. Timeout error!",
Toast.LENGTH_LONG).show();
}
}
}
}
)
{
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tagid", DemoClass.mtag_id);
//params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", token);
Log.d(TAG,"Tokkenn0"+token);
return params;
}
};
mRequestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<String>() {
#Override
public void onRequestFinished(Request<String> request) {
progressBar.setVisibility(View.GONE);
}
});
mRequestQueue.add (jsonObjectRequest);
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//mRequestQueue = Volley.newRequestQueue ( CInfo.this );
}
}
I think your problem is here:
sendAndRequestResponse();
session = new SessionManager(getApplicationContext());
token = session.getStringData("jwtToken");
It should be:
session = new SessionManager(getApplicationContext());
token = session.getStringData("jwtToken");
sendAndRequestResponse();
Or else you will only set the token which is needed in sendAndRequestResponse() after calling the method which is then too late.
Also ensure you have this permission declared in your manifest:
<uses-permission android:name="android.permission.INTERNET" />
I have a php script for handling very basic registration. its in a folder in my localhost; http://(ipaddress/localhost):3306/testing/Register.php. Android studio points to this URL but i get no error output when i run the emulator. When i open the PHP script in the browser, everything looks good.
Here is the registerrequest java script:
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://(ipaddress/localhost):3306/testing/Register.php";
private Map<String, String> params;
public RegisterRequest(String username, String password,String isAdmin, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL,listener,null);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("isAdmin",isAdmin+"");
}
public Map<String, String> getparams() {
return params;
}
}
here is my createuser script
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);
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
queue.add(registerRequest);
}
});
}
finally, here is my PHP script, Register; m
$db_host = 'localhost:3306';
$db_user = 'root';
$db_pass = '';
$db_name = 'test';
$con = mysqli_connect($db_host,'user',$db_pass,$db_name);
if($con){
echo "connection successful";
}else{
echo "connection failed";
}
$age = $_POST["isAdmin"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO cresidentials (username,password,isAdmin) VALUES (?, ?, ?)");
if(!$statement) { printf("Prepare failed: %s\n", mysqli_error($con)); }
if(!$statement) { return json_encode(['status'=>'failed','message'=>mysqli_error($con)]); }
mysqli_stmt_bind_param($statement, "ssi",$username,$password,$isAdmin);
mysqli_stmt_execute($statement);
if(mysqli_error($statement)) { return json_encode(['status'=>'failed','message'=>mysqli_error($con)]); }
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
Im using xampp (apache and mysql turned on) and my Register is in a folder in Htdocs.
Thank you in advance for any help!
You could modify constructor of RegisterRequest:
public RegisterRequest(String username, String password,String isAdmin,
Response.Listener<String> listener,
Response.ErrorListener() errListener){ //add error listener
super(Method.POST, REGISTER_REQUEST_URL,listener,errListener);
......
}
And in CreateUser class file, add below:
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, String.valueOf(error), Toast.LENGTH_SHORT).show();
}
}
Then:
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,
responseListener,errorListener);
Now, run again and when error occured, you could see it in error listener.
I am trying to save my data to server. can any one help me?
when i am trying to save data through browser it is working fine but when i try it through this code doesn'n give any response??
public class Register extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "dRegister";
EditText etName, etEmail, etMobile, etPassword, /*etRePassword*/
etCity;
Button register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = (EditText) findViewById(R.id.name);
etEmail = (EditText) findViewById(R.id.email);
etMobile = (EditText) findViewById(R.id.mobile);
etCity = (EditText) findViewById(R.id.etCity);
etPassword = (EditText) findViewById(R.id.password);
//etRePassword = (EditText) findViewById(R.id.rePassword);
register = (Button) findViewById(R.id.bRegister);
register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String email = etEmail.getText().toString();
final String password = etPassword.getText().toString();
final String city = etCity.getText().toString();
final String phoneno = etMobile.getText().toString();
StringRequest registerRequest = new StringRequest(Request.Method.POST,RegisterRequest.REGISTER_REQUEST_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response + " Response");
if(response.equals("SUCCESS")){
startActivity(new Intent(Register.this,MainActivity.class));
}
else{
Toast.makeText(Register.this, "You have not Registered!", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error " + error.toString());
if(error.networkResponse == null){
if(error.getClass().equals(TimeoutError.class));
Toast.makeText(Register.this, "oops Time out error!", Toast.LENGTH_SHORT).show();
}
}
}){
#Override
public Map<String, String> getHeaders()throws AuthFailureError{
Map<String, String> headers = new HashMap<>();
headers.put("name",name);
headers.put("email",email);
headers.put("password",password);
headers.put("city",city);
headers.put("phoneno",phoneno);
return headers;
}
};
registerRequest.setRetryPolicy(new DefaultRetryPolicy(1000 * 15,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
/*Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response + "");
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(Register.this, MainActivity.class);
startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setMessage("Registration failed").setNegativeButton("Retry", null)
.create().show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, email, city, phoneno, password, responseListener){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//super.getHeaders();
Map<String,String> headers = new HashMap<>();
String credential = "raju#gmail.com:123";
String auth = "Basic "+ Base64.encodeToString(credential.getBytes(),Base64.NO_WRAP);
//headers.put("Content-Type");
headers.put("Authorization",auth);
//
return headers;
}
};*/
RequestQueue queue = Volley.newRequestQueue(Register.this);
registerRequest.setShouldCache(false);
queue.add(registerRequest);
}
}
Here Is my server code....
#RequestMapping(value = "/savemobileUser", method = RequestMethod.POST)
public #ResponseBody String saveUser(#RequestBody MobileUserModel mobileUser) {
MobileUserModel user = new MobileUserModel();
user.setActivationKey(mobileUser.getActivationKey());
user.setCity(mobileUser.getCity());
user.setEmail(mobileUser.getEmail());
user.setImeino(mobileUser.getImeino());
user.setName(mobileUser.getName());
user.setPassword(mobileUser.getPassword());
user.setPhoneno(mobileUser.getPhoneno());
userrepository.save(user);
System.out.println("Saved");
// return "User has been saved Successfully";
return "SUCCESS";
}
Put following inside your onClick method:
switch (v.getId()) {
case R.id.bRegister:
// add your registration process code here
break;
}
Make Sure you have given Internet permissions in your manifest.
<uses-permission android:name="android.permission.INTERNET" />
Please provide your json response format and also the parameter type that you are sending. It may occur due to different reasons, for example, there is an json array in response and you are mapping it just in simple object or the attributes (variable) that you are mapping into it, names are not exactly similar to json response filed or there can be different multiple reasons.
The problem is definitely from this code.
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etuserame.getText().toString();
final String email = etemail.getText().toString();
final String password = etpassword.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(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username, email, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
when the user clicks register, it does not open the new activity and I get nothing in my database. I just get a cancelling event due to no window focus and too many processes running.
This is my RegisterRequest class.
private Map<String, String> params;
public RegisterRequest(String username, String email, String password, Response.Listener<String> listener){
/*
NExt line means we are going to pass some information into the register.php
*/
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
/*
This is how we pass in the information from the register to the thing, we are using a hashmap
*/
params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
}
/*
Volley needs to get the data so we do a get params
Which gives us this method
*/
#Override
public Map<String, String> getParams() {
return params;
}
}