Can't insert data in google sheets from android app (Java) - 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);
}

Related

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

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

Reading the Echo of a POST Request for Android

Please i really need your help blocked from yesterday :'(
// MY X VAR
int x ;
// im executing the check_referrer() function into my the button click listner
signupJoinBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = signupUsername.getText().toString();
referrercode = signupReferrer.getText().toString();
x =check_referrer(username,referrercode);
// Check_ Referrer is supposed Reading "1" or "0" from my PHP file ( i tested my php file and his working )
public int check_referrer( String referral, String referrer ) {
String awr = Config.Base_Url + "get/checkref.php";
final String v1 = "1"; // OK
final String v0 = "0"; // The referrer is not existing
StringRequest stringRequest = new StringRequest(Request.Method.POST,awr,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals(v1) ) {
x= 1;
}
else if (response.equals(v0) ) {
x= 0;
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
// user is the variable my php file will receive
params.put("user",username);
// user is the variable my php file will receive
params.put("ref", referrercode);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
return x;
}
You have to declare
JSONObject jObj = new JSONObject(response);
in your onResponse method. Then you can pull Json values from php file using
String var1 = jObj.getString("var1");
Can you show us your php file?

passing one param to server and get array using JsonArrayRequest with volley android studio

I'm trying to make an app . I struggling to get some data of one of my table in my database . I know how to get everything from my table , but now i need only few lines of this table. So I have to pass an ID .
The problem is that i cant add any param in JsonArrayRequest.
You can see my php file and my class where I'm calling JsonArrayRequest:
php
<?php
include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user_id = $_POST["user_id"]; // this is what Im trying to fix
$sql = "SELECT * FROM plans WHERE user_id=?"; // and pass the information in ?
$result = $conn->query($sql);
if ($result->num_rows >0) {
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "0 results";
}
echo $json;
$conn->close();
?>
java class:
public class PlansActivity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
String GET_JSON_DATA_HTTP_URL = "http://travelb.000webhostapp.com/jsonData.php";
String JSON_ID = "user_id";
String JSON_NAME = "destination";
String JSON_SUBJECT = "date";
String JSON_PHONE_NUMBER = "plan_id";
Button button;
PostJsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plans);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
button = (Button)findViewById(R.id.button) ;
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
final Intent intent = getIntent();
final int id = intent.getIntExtra("user_id", -1);
/* button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
}
});*/
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setId(json.getInt(JSON_ID));
GetDataAdapter2.setName(json.getString(JSON_NAME));
GetDataAdapter2.setSubject(json.getString(JSON_SUBJECT));
GetDataAdapter2.setPhone_number(json.getString(JSON_PHONE_NUMBER));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
I read lot of thing but all different . Im new on androidstudio and php .
I hope someone can help me , because Im tryin to do that for 2weeks now .
You should extends JsonArrayRequest in your custom Request like this:
public class MyJsonArrayRequest extends JsonArrayRequest {
private Map<String, String> mPostParams;
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return mPostParams;
}
public MyJsonArrayRequest(String url, Map<String, String> postParams, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
super(url, listener, errorListener);
this.mPostParams = postParams;
}
}
with getParams() method you will able to pass POST parameters.
Map<String, String> params = new HashMap<>();
params.put("ID", id);
params.put("USER_ID", userId);
MyJsonArrayRequest jsonArrayRequest = new MyJsonArrayRequest(GET_JSON_DATA_HTTP_URL, params,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Another way is to pass parameters via GET request in URL.
You can send parameters with jsonArrayRequest like this by overriding getParam method
JsonArrayRequest request = new JsonArrayRequest(method, url, null, responseListener, errorListener) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
try {
params.put("paramOne", "hello");
} catch (JSONException e) {
e.printStackTrace();
}
return params;
}
};
addToRequestQueue(request);
#mcatta
I want to do something like I did in my others acticity :
ProfileRequest profilRequest = new ProfileRequest(id, responseListener);
RequestQueue queue = Volley.newRequestQueue(UserAreaActivity.this);
queue.add(profilRequest);
and
public class ProfileRequest extends StringRequest {
private static final String PROFIL_REQUEST_URL = "http://travelb.000webhostapp.com/Profil.php ";
private Map<String, String> params;
public ProfileRequest(int user_id, Response.Listener<String> listener){
super(Request.Method.POST, PROFIL_REQUEST_URL, listener, null);
params= new HashMap<>();
params.put("user_id", user_id+"");
}
#Override
public Map<String, String> getParams() {
return params;
}
}
so the id in profilerequest is a final int variable.
this one was easy to do .
Im still confused with jsonarrayrequest
Its been a long time but,
someone can find it useful
and the following code works .
public class Activity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
String GET_JSON_DATA_HTTP_URL = "API here";
//String JSON_ID = "id";
//we have intilize here with json names and database column name also should be kept here
String JSON_FNAME = "contact_fname";
String JSON_LNAME = "contact_lname";
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
//json web call from web
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
String uid ="value"//Or you can use your value to pass
StringRequest strrequest = new StringRequest(Request.Method.POST,GET_JSON_DATA_HTTP_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
try {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
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("userid", uid);//userid to send to php
return params;
}
};
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(strrequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(String array) throws JSONException {
JSONArray jarr = new JSONArray(array);
for(int i = 0; i<jarr.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();//adapter class
//JSONObject json;
try {
JSONObject json = jarr.getJSONObject(i);
// JSONObject json = (JSONObject) array.get(String.valueOf(i));
//set and get methods should declare here with database colmun names and json names
GetDataAdapter2.setcontact_fname(json.getString(JSON_FNAME));
GetDataAdapter2.setcontact_lname(json.getString(JSON_LNAME));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}

public List<Model> loadInBackground() method in android does not get data from jSon Array

I am developing an application using android and i'm trying to get the jSon Array displayed in Listfragment using the loadInBackground() method below in my DataListLoader class:
class DataListLoader extends AsyncTaskLoader<List<Model>> {
List<Model> mModels;
String jsonString;
String name = "Daniel Nyerere", phone = "0652400670";
public DataListLoader(Context context) {
super(context);
loadInBackground();
}
public List<Model> loadInBackground() {
// You should perform the heavy task of getting data from
// Internet or database or other source
// Here, we are generating some Sample data
// Create corresponding array of entries and load with data.
final List<Model> entries = new ArrayList<Model>(50);
StringRequest stringRequest = new StringRequest(
Request.Method.GET, "http://10.0.2.2/webapp/json_get_data.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().contains("server_response")) {
jsonString = response.toString();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
name = jo.getString("name");
phone = jo.getString("user_phone");
entries.add(new Model(name, phone));
System.out.println("DATA FROM JSON ARRAY: " + name + " " + phone);
count++;
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
requestQueue.add(stringRequest);
entries.add(new Model(name, phone));
return entries;
}
But when i try to run it the data from System.out.println("DATA ENTRIES: "+entries); comes as null list ,so no data get displayed in the fragment activity . Anyone who can help me to fix it so that i get data from json because it consume me a lot of time
//You can call it in UI thread
final List<Model> entries = new ArrayList<Model>(5);
StringRequest stringRequest = new StringRequest(
Request.Method.GET, "http://10.0.2.2/webapp/json_get_data.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//you need to update the `ListView` content here
//If you need you can create new thread here too e.g. using AsyncTask
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
requestQueue.add(stringRequest);

POST json array to Mysql database using JsonArrayRequest using volley in android?

This is my code for JsonArrayRequest I think either it is incomplete or incorrect. The problem is nothing getting added into the database and I am not getting any errors. I am new to programming so I have no idea as to where I might be going wrong.
private void insertToDb() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, INVEST_URL,
itemSelectedJson, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(AddInvEst.this, "The echoed response is "+response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type","application/json");
headers.put("Accept", "application/json");
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
This is code for creating a jsonArray
private void selectedItems() {
billType = (invEstSwitch.isChecked() ? textViewEstimate : textViewInvoice)
.getText().toString();
itemselected.put("custInfo", custSelected.toString());
itemselected.put("invoiceNo", textViewInvNo.getText().toString());
itemselected.put("barcode", barCode.getText().toString());
itemselected.put("desc", itemDesc.getText().toString());
itemselected.put("weight", weightLine.getText().toString());
itemselected.put("rate", rateAmount.getText().toString());
itemselected.put("makingAmt", makingAmount.getText().toString());
itemselected.put("net_rate", netRate.getText().toString());
itemselected.put("itemTotal", itemtotal.getText().toString());
itemselected.put("vat", textViewVat.getText().toString());
itemselected.put("sum_total", textViewSum.getText().toString());
itemselected.put("bill_type", billType);
itemselected.put("date", textViewCurrentDate.getText().toString());
//Add the map to the Array
itemSelectedJson.put(itemselected);
index++;
}
And this is my php code.
<?php
require "init.php";
$json = file_get_contents('php://input');
//$data = json_decode($json,true);
// remove the ,true so the data is not all converted to arrays
$data = json_decode($json);
// Now process the array of objects
foreach ( $data as $inv ) {
$custInfo = $inv->custInfo;
$rate = $inv->rate;
$weight= $inv->weight;
$desc= $inv->desc;
$makingAmt= $inv->makingAmt;
$vat= $inv->vat;
$itemTotal= $inv->itemTotal;
$sum_total= $inv->sum_total;
$barcode= $inv->barcode;
$net_rate= $inv->net_rate;
$date= $inv->date;
$invoiceNo= $inv->invoiceNo;
$bill_type= $inv->bill_type;
$sql = "INSERT INTO selected_items
(custInfo, invoiceNo, barcode, desc,
weight, rate, makingAmt,net_rate,
itemTotal,vat,sum_total,bill_type,date)
VALUES
('$custInfo','$invoiceNo','$barcode','$desc',
'$weight','$rate','$makingAmt','$net_rate',
'$itemTotal','$vat','$sum_total','$bill_type','$date')";
$res = mysql_query($sql,$con);
if(!$res){
$result = new stdClass();
$result->status = false;
$result->msg = mysql_error();
echo json_encode($result);
exit;
}
}
?>
You missed to add a method getParams() inside the post request, it should have this structure
StringRequest stringRequest = new StringRequest(Request.Method.POST, "url",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
errorHandler(error);
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put("KEY1", key1);
params.put("KEY2", key2);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

Categories