Excute Google App Script to add data to sheet from Android App - java

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

Related

Can't insert data in google sheets from android app (Java)

I'm trying to insert a data on google sheet api by calling this method on my code. but it's not working, what is wrong with my code?
public void addItemToSheet() {
//final ProgressDialog loading = ProgressDialog.show(this,"Adding Item","Please wait");
String code = "insert test";
StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://script.google.com/macros/s/AKfycbwvCuLeJpsH6iQ6UojH5tR4rLQW98JFjVa0DqOujqb1Krox_mhbdrb9DRljMMOrsoGk/exec",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// loading.dismiss();
Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> parmas = new HashMap<>();
//here we pass params
parmas.put("Code",code);
return parmas;
}
};
int socketTimeOut = 5000;// u can change this .. here it is 5 seconds
RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
}
I deployed the sheet using this script :
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/DFJEKLE3LGsvate8vgAW72eDJQ_U/edit#gid=0");
var sheet = ss.getSheetByName('Items'); // My sheet is named Items
function doPost(e){
var action = e.parameter.action;
if(action == 'addItem'){
return addItem(e);
}
}
function addItem(e){
var code = e.parameter.Code;
sheet.appendRow([code]);
return ContentService.createTextOutput("Success").setMimeType(ContentService.MimeType.TEXT);
}

Response.Listener not working

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.

when i try to register by my app i didn't get any respnse

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.

How can I fix too many things happening Android Studio

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

Handling response from database and passing it to new activity

I am currently building a login system for a simple game application. What I am trying to achieve is the following: When a user logs in I want to display the top 5 highscores in the activity the user comes to after logging in.
The response I am getting from the database is a JSON encoded string looking like this:
{"success":true,"toplist":
[{"username":"Tom","score":"4200"},
{"username":"John","score":"2303"},
{"username":"Benjamin","score":"700"},
{"username":"Michael","score":"648"},
{"username":"Daniel","score":"500"}]
}
From here I would like to "handle" and pass the top 5 information to the userAreaActivity and then show the top 5 in a table.
Here is what I have so far in order to handle the response:
bSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.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 userAreaIntent = new Intent(LoginActivity.this, UserAreaActivity.class);
LoginActivity.this.startActivity(userAreaIntent);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login failed!")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
If it is of any use this is what my UserAreaActivity.Java looks like:
public class UserAreaActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final TableLayout tlHighscores = (TableLayout) findViewById(R.id.tlHighscores);
Intent intent = getIntent();
}
}
Would be thrilled if someone would give me some guidance as to how I would do this in the most convenient way.
You can simply do this
Intent userAreaIntent = new Intent(LoginActivity.this, UserAreaActivity.class);
userAreaIntent.putString("data", jsonResponse.toString());
LoginActivity.this.startActivity(userAreaIntent);
And in UserAreaActivity
JSONObject jsonObj = new JSONObject(getIntent().getStringExtra("data"));
Once you get the jsonObj you can parse it and use it anyway you want.
This is what the Intent object is for - to provide an intent along with associated information. You can simply do:
Intent intent = new Intent(this, UserAreaActivity.class);
intent.putString("key", "value");
startActivity(intent);
Now, you can do intent.getStringExtra("key") in your receiving Acitivity to extract the values. You can pass your entire JSON string and retrieve information this way.

Categories