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;
}
Related
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'm running an app quiz with 2 table like this https://gyazo.com/641f6e45006ab4f6d962a81d60e1ba69 , https://gyazo.com/be10c2f550f63b4ebc55eda61c3f0f15.
My register -login activity works fine but the issue is when I try to send the score value to database. No errors and no message that's running. Can you help me please?
public class Results extends AppCompatActivity implements OnClickListener {
private Button bt_save;
private TextView tv_label;
int totalscore ;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
tv_label = (TextView) findViewById(R.id.tv_label);
Button bt_Begin = (Button) findViewById(R.id.bt_Begin);
bt_save = (Button)findViewById(R.id.bt_save);
bt_save.setOnClickListener(this);
SharedPreferences sharedPreferences = getSharedPreferences("sharedPref",Context.MODE_PRIVATE);
Integer result = sharedPreferences.getInt("rightAnswerCount", 0);
SharedPreferences sharedPreferencess = getSharedPreferences("sharedPref",Context.MODE_PRIVATE);
Integer results = sharedPreferencess.getInt("rightAnswerCountt",0);
totalscore=(result+results);
tv_label.setText("" +totalscore);
}
private void saveRequest() {
final String score = tv_label.getText().toString().trim();
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Registrating user...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.RESULT_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> key = new HashMap<>();
key.put("totalscore", score+"");
return key;
}
};
RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
}
#Override
public void onClick(View view) {
if (view == bt_save)
saveRequest();
}
this is my php file dbOp1
<?php
class dbOperation1{
private $con;
function __construct(){
require_once dirname(__FILE__).'/connect.php';
$db = new connect();
$this->con = $db->connect();
}
public function saveScore($score){
$stmt = $this->con->prepare("INSERT INTO `test_score`(`id`,`score`) VALUES(NULL, ?);");
$stmt->bind_param("i",$score);
if($stmt->execute()){
return 1;
}else{
return 2;
}
}
}
?>
And this is my Result php:
<?php
error_reporting(0);
require_once 'dbOp1.php';
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
if(
isset($_POST['score']))
{
$db = new dbOperation1();
$result = $db->saveRequest(
$_POST['score']
);
if($result == 1){
$response['error'] = false;
$response['message'] = "User registered sussessfully";
}elseif($result == 2){
$respone['error'] = true;
$response['message'] = "Some error";
}
}
}
echo json_encode($response);
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.
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);
}
}
**
the parameters of volley (company_id && branch_id)
equal null although I got its real data before via MyRequestQueue_Company so it causes volley response is nullpointer exception
Why do company_id and branch_id equal null in MyRequestQueue_Drivers? How can I solve this?
public class CheckinActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String company_id, branch_id;
Spinner driver_name_spinner;
private String User_URL = "http://example.com/api/user?token=";
private String Drivers_URL = "http://example.com/api/getDrivers?company_id=1&branch_id=15";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkin);
driver_name_spinner = (Spinner) findViewById(R.id.driver_name_spinner);
next = (Button) findViewById(R.id.next);
SharedPreferences sharedPref = getSharedPreferences("userinfo", getApplicationContext().MODE_PRIVATE);
final String token = sharedPref.getString("token", "");
final RequestQueue MyRequestQueue_Company = Volley.newRequestQueue(this);
// GET COMPANY_ID AND BRANCH_ID FORM API
StringRequest MyStringRequest_Company = new StringRequest(Request.Method.GET, User_URL + token, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsono = null;
jsono = new JSONObject(response);
JSONObject jarray = jsono.getJSONObject("user");
company_id = jarray.getString("company_id");
branch_id = jarray.getString("branch_id");
Log.d("User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
});
MyRequestQueue_Company.add(MyStringRequest_Company);
// CALL ANOTHER WEBSERVICES TO GET DRIVERS DATA
RequestQueue MyRequestQueue_Drivers = Volley.newRequestQueue(getApplicationContext());
StringRequest MyStringRequest_Drivers = new StringRequest(Request.Method.POST, Drivers_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Drivers Response", response);
try {
JSONObject jsono = null;
jsono = new JSONObject(response);
JSONArray jarray = jsono.getJSONArray("Drivers");
List<String> drivers;
drivers = new ArrayList<String>();
for (int i = 0; i < jarray.length(); i++) {
JSONObject newobject = jarray.getJSONObject(i);
driver_name_txt = newobject.getString("name");
Log.d("Driver Name", driver_name_txt);
drivers.add(driver_name_txt);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item, drivers);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
driver_name_spinner.setAdapter(dataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Drivers Error",error.toString());
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
// BRANCH_ID AND COMPANY_ID ARE EQUAL NULL !?
MyData.put("branch_id", branch_id);
MyData.put("company_id", company_id);
Log.d("Last User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
return MyData;
}
};
MyRequestQueue_Drivers.add(MyStringRequest_Drivers);
driver_name_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
TextView tmpView = (TextView) driver_name_spinner.getSelectedView().findViewById(android.R.id.text1);
tmpView.setTextColor(Color.WHITE);
driver_name_txt = parent.getItemAtPosition(position).toString();
Log.d("driver_name_original", driver_name_txt);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
If you want to use getParams function, than I would suggest to define a flag and modify your function like:
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsono = null;
jsono = new JSONObject(response);
JSONObject jarray = jsono.getJSONObject("user");
company_id = jarray.getString("company_id");
branch_id = jarray.getString("branch_id");
Log.d("User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
requestFinished = true;
} catch (JSONException e) {
e.printStackTrace();
}
}
And your getParams would look like :
protected Map<String, String> getParams() {
if(!requestFinished) return null;
Map<String, String> MyData = new HashMap<String, String>();
// BRANCH_ID AND COMPANY_ID ARE EQUAL NULL !?
MyData.put("branch_id", branch_id);
MyData.put("company_id", company_id);
Log.d("Last User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
return MyData;
But I would suggest to you to use the Observer pattern instead.