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" />
Related
I've recently tried to develop a servlet and then connect it to my android app but I can't get it to work properly.
This is my login servlet
#WebServlet(name = "login", value = "/auth/login")
public class AuthUser extends HttpServlet {
private Gson gson = new Gson();
public void init() {
Dao.registerDriver();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
String id = request.getParameter("id");
String psw = request.getParameter("psw");
HttpSession s = request.getSession();
PrintWriter out = response.getWriter();
HashMap<String, Object> responseJson = new HashMap<>();
Student student;
if(id != null && psw != null) {
student = FetchFromDB.fetchStudentData(id);
if (student != null && student.getPassword().equals(psw)) {
s.setAttribute("username", student.getNumber());
s.setAttribute("surname", student.getSurname());
s.setAttribute("role", student.getRole());
responseJson.put("id", request.getSession().getId());
responseJson.put("user", student);
responseJson.put("message", "Logged succesfully");
out.print(new Gson().toJson(responseJson));
} else {
responseJson.put("message", "The mail or the username is not correct, please try again");
out.println(new Gson().toJson(responseJson));
}
} else {
responseJson.put("message", "The mail or username value is null, check that out");
}
out.flush();
}
public void destroy() {
}
}
I call this servlet from my login page in my android app as follow:
private void login() throws MalformedURLException {
RequestQueue queue = Volley.newRequestQueue(this);
String username = usernameText.getText().toString();
String psw = passwordText.getText().toString();
String url = Costants.URL + "auth/login?id="+username+"&psw="+psw+"";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url,
null,
response -> {
Log.d("In onResponse", ""+response);
try {
Log.d("In callServer", "Object returned: " +response.toString());
intent.putExtra("key-username", usernameText.getText().toString());
intent.putExtra("key-role", response.getJSONObject("user").getString("role"));
intent.putExtra("key-surname", response.getJSONObject("user").getString("surname"));
intent.putExtra("key-session-id", response.getString("id"));
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> {
VolleyLog.d("In onErrorResponse", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjReq);
}
When I click in the login button it works, so it communicates with the servlet and the main activity starts as it should do.
BUT when I try to make another call from my MainActivity the session in the servlet won't be recognised and so the user appears as unkown, here's the code of the mainActivity.
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
String usernameOfLoggedUser;
String surnameOfLoggedUser;
String roleOfLoggedUser;
String sessionId;
Bundle extras;
private UserViewModel viewModel;
private BookedLessonsViewModel bookedLessonsViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
extras = getIntent().getExtras();
usernameOfLoggedUser = extras.getString("key-username", "NoValue");
surnameOfLoggedUser = extras.getString("key-surname", "NoValue");
roleOfLoggedUser = extras.getString("key-role", "NoValue");
sessionId = extras.getString("key-session-id", "NoValue");
showWelcomeToast(usernameOfLoggedUser);
setViewModelUser(usernameOfLoggedUser, roleOfLoggedUser, surnameOfLoggedUser);
fetchBookedLessons(usernameOfLoggedUser);
setupUIElements();
}
/**
* Fetch lessons from db and set the model view for the lessons booked
* #param username
*/
private void fetchBookedLessons(String username) {
String url = Costants.URL + "book/bookedLessonsForUser";
ArrayList<BookedLesson> bookedLessons = new ArrayList<>();
CustomRequest jsonCustomReq = new CustomRequest(
Request.Method.GET,
url,
null,
sessionId,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("in onResponse", response.toString());
// int i = 0;
// try {
// JSONArray reservations = response.getJSONArray("reservations");
// while(i < reservations.length()) {
// JSONObject reservation = reservations.getJSONObject(i);
// String idUser = reservation.getString("idUser");
// String idTeacher = reservation.getString("idTeacher");
// String subject = reservation.getString("nameSubject");
// String day = reservation.getString("day");
// String slot = reservation.getString("slot");
// String status =reservation.getString("status");
//
// BookedLesson bookedLesson = new BookedLesson(idUser, idTeacher, slot, subject, day, status);
// bookedLessons.add(bookedLesson);
// i++;
// }
// } catch (JSONException e) {
// e.printStackTrace();
// } finally {
// setViewModelLessons(bookedLessons);
// }
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonCustomReq);
}
private void showWelcomeToast(String username) {
Toast toast = Toast.makeText(getApplicationContext(), "You are logged as: " + username, Toast.LENGTH_SHORT*2);
toast.show();
}
#Override
protected void onResume() {
super.onResume();
fetchBookedLessons(usernameOfLoggedUser);
}
private void setupUIElements() {
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(binding.navView, navController);
}
/**
* Set the model view for the user so that every fragment has the data for the logged user
* #param usernameOfLoggedUser
* #param roleOfLoggedUser
* #param surnameOfLoggedUser
*/
private void setViewModelUser(String usernameOfLoggedUser, String roleOfLoggedUser, String surnameOfLoggedUser) {
viewModel = new ViewModelProvider(this).get(UserViewModel.class);
viewModel.setUser(usernameOfLoggedUser);
viewModel.setRole(roleOfLoggedUser);
viewModel.setSurname(surnameOfLoggedUser);
viewModel.getUser().observe(this, username -> {
Log.d("In onCreate", "Share data: " + username);
});
}
/**
* Pass the array fetched and set the model view for the lessons
* #param lessons
*/
private void setViewModelLessons(ArrayList<BookedLesson> lessons) {
bookedLessonsViewModel = new ViewModelProvider(this).get(BookedLessonsViewModel.class);
bookedLessonsViewModel.setBookedLessons(lessons);
bookedLessonsViewModel.getBookedLessons().observe(this, bookedLessons -> {
Log.d("In getBookedLessons", "Lessons: " + bookedLessons.size());
});
}
}
But I get this value in return:
-26 13:48:47.053 12225-12225/com.example.bookinglessons D/in onResponse: {"message":"you're not logged"}
If you know what's going on it would be really helpful, thanks in advance.
I found the solution for this kind of problems.
You just need to add these lines in the onCreate of your first Activity (MainActivity in my case).
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
This solved my problems and mantained the session.
I have a app but have teen testing it on an LG G4 i just started testing on other devices but with my samsung s9 the http requests/POST i make to receive JSON data from an API wont work i can not even log into the app
So i have tried to google answers and look on this site to see if there is a solution but tried a lot of them none that worked the message i get from the logcat is:
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
tried to google those messages but came up with the same results as previous i am using the Volley library to POST to the server
This is my LoginActivity.java:
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText username = findViewById(R.id.username);
final EditText password = findViewById(R.id.password);
final Button loginButton = findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String uName = username.getText().toString();
final String pWord = password.getText().toString();
Response.Listener<String> listener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Map<String, List<String>> map = new HashMap<>();
JSONObject jsonResponse = new JSONObject(response);
String success = jsonResponse.getString("sukses");
if (success.equals("true")) {
JSONObject jsonArray = jsonResponse.getJSONObject(uName);
JSONArray regions = jsonArray.names();
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < regions.length(); i++) {
String id = regions.getString(i);
list.add(regions.getString(i).toString());
JSONObject regionArray = jsonArray.getJSONObject(id);
JSONArray fields = regionArray.names();
List<String> fieldName = new ArrayList<>();
for (int d = 0; d < fields.length(); d++) {
String field = fields.getString(d);
fieldName.add(field);
}
map.put(id, fieldName);
}
Intent farms = new Intent(LoginActivity.this, FarmsActivity.class);
farms.putExtra("username", uName);
farms.putExtra("password", pWord);
farms.putExtra("list", list);
farms.putExtra("map", (Serializable) map);
startActivity(farms);
} else {
AlertDialog.Builder invalid = new AlertDialog.Builder(LoginActivity.this);
invalid.setTitle("Login Failed");
invalid.setMessage("Invalid Login Details")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e){
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(uName, pWord, listener);
loginRequest.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
}
and this is the LoginRequest:
public class LoginRequest extends StringRequest{
private static final String LOGIN_REQUEST_URL = "MY HTML LINK";
private Map<String, String> params;
public LoginRequest(String username, String password, Response.Listener<String> listener) {
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams(){
return params;
}
}
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);
}
}
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;
}