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?
Related
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);
}
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 log in code who connecting to my php file on my host using volley
everything works great but when i log off and log in again, saved cache memory remember my old information even if i changed it.
i tried to use:
requestQueue.getCache().clear();
stringRequest.setShouldCache(false);
not clearing my cache
this is my code:
private void sendRequest(){
StringRequest stringRequest = new StringRequest(Request.Method.GET,DBConstants.LOG_IN_USER + mEmail + "&password=" + mPassword,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray user = null;
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
user = jsonObject.getJSONArray(JSON_ARRAY);
JSONObject jo = user.getJSONObject(0);
gates = new ArrayList<String>(5);
gateData = new ArrayList<String>();
mEmail = jo.getString(DBConstants.KEY_LOGIN_EMAIL);
mPassword = jo.getString(DBConstants.KEY_LOGIN_PASSWORD);
name = jo.getString(DBConstants.KEY_LOGIN_NAME);
if(!mEmail.equals("null")) {
level = Integer.parseInt(jo.getString(DBConstants.KEY_LOGIN_LEVEL));
for (int i = 1; i < 6; i++) {
gates.add(jo.getString(DBConstants.KEY_LOGIN_GATE + i));
if(!gates.get(i-1).equals("null")) {
for (String dataString : gates.get(i-1).split(";")) {
gateData.add(dataString);
}
newGate = new Gate(gateData.get(0),gateData.get(1),gateData.get(2),
Integer.parseInt(gateData.get(3)),Integer.parseInt(gateData.get(4)),gateData.get(5));
myHandler.addNewGate(newGate);
getAuthorizedList(newGate);
gateData.clear();
}
}
login = true;
} else {
login = false;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
login = false;
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this.getApplicationContext());
requestQueue.getCache().clear();
stringRequest.setShouldCache(false);
requestQueue.add(stringRequest);
}
sorry you can close
on my hosting account i had cache manager, i turned it off and it works great!
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);
I have php file when user post existing ticknumber the php will echo JSON code for one array of that was posted, I linked it with Activity that will do same job of php file but when I click on button I get toast message "please check the number" like php page echo " error " but it's not true because I tried by postman and it's work
<?php
if ($_SERVER ['REQUEST_METHOD']=='POST') {
$ticketnumber = $_POST['ticketnumber'];
require_once('config.php');
$con->set_charset('utf8');
$sql = " SELECT * FROM contact WHERE ticketnumber = '$ticketnumber' ";
$res = mysqli_query($con, $sql);
$result = array();
while($get = mysqli_fetch_array($res))
{
array_push($result,array('ticketnumber' =>$get[5], 'subject' =>$get[4],'response' =>$get[6]));
}
if(!empty($result)){
echo json_encode(array("responseticket"=>$result));
} else {
echo " error";
}
}
?>
supportActivity.java
public class supportActivity extends Fragment 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://abvb.com/aaa/getticket.php";
private RequestQueue requestQueue1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_support, container, false);
getActivity().setTitle("Get Ticket");
ticketsupport = (EditText)view.findViewById(R.id.insertticketnumber);
supportlist = (ListView)view.findViewById(R.id.supportlistview);
adapter = new supportAdapter(getActivity(), con);
supportlist.setAdapter(adapter);
button = (Button)view.findViewById(R.id.buttonsupprt);
button.setOnClickListener(this);
return view;
}
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("error")) {
Toast.makeText(getActivity(), "please check the number", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = jsonObject.getJSONArray("responseticket");
JSONObject jTicket = jsonArray.getJSONObject(0);
String Ticketnumber = jTicket.getString("ticketnumber");
String Subject = jTicket.getString("subject");
String Response = jTicket.getString("response");
supportContent support = new supportContent();
support.setTicketnumber(Ticketnumber);
support.setSubject(Subject);
support.setResponse(Response);
con.add(support);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "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;
}
};
requestQueue1 = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue1.add(stringRequest1);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View view){
inquiry();
}
}
when ticketnumber existed then php will echo JSON like this
{"responseticket":[{"ticketnumber":"285","subject":"\u0627\u062d\u0628\u0643\u0645 \u0643\u0644\u0643\u0645","response":"vcvc"}]}
Your PHP expects "ticketnumber" in POST arguments:
$ticketnumber = $_POST['ticketnumber'];
Change your android code from:
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticknumber", ticketinput);
return map;
}
to:
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticketnumber", ticketinput);
return map;
}