Append json array request with a sessionaid - android

I am sending a request to retrieve an array of information from a mysql database using php script. At first it worked with just the url only, but I am struggling to add sessionID to the JsonArrayRequest as a parameter. How can I add my parameter sessionID with the array request?
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
String sessionID;
TextView email, fullname , contact;
String emailStr, fullnameStr, contactStr;
String url = "http://kutso011.000webhostapp.com/RetrieveData.php";
String jsonResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rq = Volley.newRequestQueue(this);
email = (TextView)findViewById(R.id.txtemaill);
fullname = (TextView)findViewById(R.id.txtFullnamee);
contact = (TextView)findViewById(R.id.txtContactt);
sessionID = getIntent().getStringExtra("UserID");
sendjsonrequest();
}
private void sendjsonrequest() {
JsonArrayRequest req = new JsonArrayRequest(url, sessionID,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String emailStr = person.getString("email");
String contactStr = person.getString("Contact");
String fullnameStr = person.getString("FullName");
email.setText(emailStr);
fullname.setText(fullnameStr);
contact.setText(contactStr);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
}
});
// Adding request to request queue
//AppController.getInstance().addToRequestQueue(req);
rq.add(req);
//rq.add(jsonObjectRequest);
}
}

public class Profile extends AppCompatActivity {
private String sessionID;
RequestQueue rq;
String jsonResponse;
String url = "http://kutso011.000webhostapp.com/October/retrieveData.php";
EditText fname_,lname_,contact_,email_;
public void initViews()
{
fname_ = (EditText)findViewById(R.id.etFName);
lname_ = (EditText)findViewById(R.id.etLName);
contact_ = (EditText)findViewById(R.id.etContact);
email_ = (EditText)findViewById(R.id.etMail);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
rq = Volley.newRequestQueue(this);
initViews();
sessionID = getIntent().getStringExtra("sessionID");
sendjsonrequest(sessionID);
}
private void sendjsonrequest(final String sessionID)
{
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try
{
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject profileInfo = (JSONObject) response
.get(i);
String fname = profileInfo.getString("FirstName"); //
String lname = profileInfo.getString("LastName");
String contact = profileInfo.getString("Contact");
String email = profileInfo.getString("Email");
Toast.makeText(getApplicationContext(), fname , Toast.LENGTH_LONG).show();
fname_.setText("fname");
lname_.setText(lname);
contact_.setText(contact);
email_.setText(email);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(),"Could not fetch data, connection error " , Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams()
{
// Posting parameters to retrieve profile url
Map<String, String> params = new HashMap<String, String>();
params.put("sessionID", sessionID);
return params;
}
};
// Adding request to request queue
//AppController.getInstance().addToRequestQueue(req);
rq.add(req);
//rq.add(jsonObjectRequest);
}
}

Related

how to login from json object in json error

public class Login extends AppCompatActivity {
private static String LOGIN_URL = "http://172.26.154.132:75";
private EditText username;
private EditText password;
private Button buttonLogin;
private ProgressBar loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.input_email1);
password = (EditText) findViewById(R.id.input_password);
buttonLogin = (Button) findViewById(R.id.btn_login);
loading = findViewById(R.id.loading);
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail = username.getText().toString().trim();
String mPass = password.getText().toString().trim();
if(!mEmail.isEmpty() || !mPass.isEmpty()){
Login1(mEmail, mPass);
} else {
username.setError("Please insert email");
password.setError("Please insert password");
}
}
});
}
private void Login1(final String username, final String password) {
loading.setVisibility(View.VISIBLE);
buttonLogin.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("data");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success.equals("data")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
buttonLogin.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "error" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
buttonLogin.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "error" + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
The response:
{
"status": true,
"message": "User login successful.",
"data": [
{
"sno": "165",
"username": "khushboo.iit#gmail.com",
"user_id_generate": "khushbu#Paswan2018782",
"password": "25f9e794323b453885f5181f1b624d0b",
"is_verified": "1",
"hash": "",
"user_type": "icb_user",
"user_role": "admin"
}
]
}
If your API successfully return data then the problem is JSON parsing. JSON data not parsed successfully. Because "data" contains an array not a single String value.
Try this
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("status");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
buttonLogin.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "error" + e.toString(), Toast.LENGTH_SHORT).show();
}
I didnt understood question properly but i think i know what you meant.
As there are two functions one is for success and one is for failure you can handle cases like this..
Use JSONObjectRequest instead of string request, It will return you a JSONObject string instead of a string response. Or You can convert the string into a JSONObject like this
JSONObject response = new JSONObject(response)
and then you can parse the jsonObject like this.
if(respose.optString("status")==true)
//success
else
//failed
If you want to print the error msg which is coming from server... do it like this:
error.networkResponse.statusCode
error.networkResponse.message

Volley POST request android

I am not sure i should use which type of content to POST to the api because I am very new to this developing world.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
button = (Button)findViewById(R.id.reg_btn_sign_up);
btnCancel = (Button)findViewById(R.id.reg_button_cancel);
Email = (EditText)findViewById(R.id.reg_email);
Name = (EditText)findViewById(R.id.reg_name);
Pass = (EditText)findViewById(R.id.reg_pass);
ConPass = (EditText)findViewById(R.id.reg_confirm_pass);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
email = Email.getText().toString();
name = Name.getText().toString();
password = Pass.getText().toString();
conPass = ConPass.getText().toString();
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("username", email);
jsonBody.put("password", password);
jsonBody.put("name", name);
} catch (JSONException e) {
e.printStackTrace();
}
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, reg_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String status = jsonObject.getString("status");
String result = jsonObject.getString("result");
builder.setTitle("Server Response...");
builder.setMessage(result);
} catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
MySingleton.getmInstance(RegisterActivity.this).addRequestQueue(stringRequest);
}
});
}
}
This is the log I get in logcat:
W/System.err: org.json.JSONException: Value
{"status":0,"result":"Access restricted"} of type org.json.JSONObject
cannot be converted to JSONArray
I do it correctly in POSTMAN but I failed to get the result I want in android.
API added in command.
try this
public void login(final String user, final String pass) {
Log.e("Constant.KEY_URL", String.valueOf(Constant.KEY_URL));
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.KEY_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//you will get your response in log
Log.e("response", response);
if (user.equals("") || pass.equals("")) {
Toast.makeText(getApplicationContext(), "username or password is empty", Toast.LENGTH_LONG).show();
} else if (!response.equals("empty")) {
Log.e("isempty", "yes");
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONArray array1 = array.getJSONObject(i).getJSONArray("data");
for (int j = 0; j < array1.length(); j++) {
startActivity(intent);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("isempty", "else");
Toast.makeText(getApplicationContext(), "Username or password is incorrect", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "username or password is empty", Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
Log.e("Error", "msg==>" + error);
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> reqMap = new LinkedHashMap<>();
reqMap.put("username", user);
reqMap.put("password", pass);
reqMap.put("method", "login");
Log.e("request","login" + reqMap);
return reqMap;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 30, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
requestQueue.add(stringRequest);
stringRequest.setTag("TAG");
}
call this login method on your button click event
btnlogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
user = editusername.getText().toString().trim();
pass = editpassword.getText().toString().trim();
login(user, pass);
}
});
I'm assuming that you are doing sign up function using volley request response..Relate to my code which i have used for login purpose,you can change it according to your needs..Hope it helps
The response you are getting is JSONObject and not JSONArray
try following code in onResponse method:
try {
JSONObject jsonObject = new JSONObject (response);
String status = jsonObject.getString("status");
String result = jsonObject.getString("result");
builder.setTitle("Server Response...");
builder.setMessage(result);
} catch (JSONException e){
e.printStackTrace();
}
Your are trying to parse an array from your response but you are getting an JSONObject.
So first change this line when you get the response
JSONObject jsonObject = new JSONObject(response);
and check the status
if(jsonObject.getString("status").equalsIgnoreCase("0")){
// show error message or whatever
}else if(jsonObject.getString("status").equalsIgnoreCase("1")){
// then parse your array if response has it
}
Use this
JSONObject jsonObject = new JSONObject (response.toString());
Instead of
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);

i want send json file to my server from android what should i do in doInBackground method?

my backend is laravel and i want to send json file to a specific rout
i already create my json plz help
public class MainActivity extends AppCompatActivity {
EditText usernameview;
EditText passwordview;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameview = (EditText)findViewById(R.id.username) ;
passwordview = (EditText)findViewById(R.id.password) ;
Button login = (Button) findViewById(R.id.loginid);
}
public void senddatatoserver(View v) {
String username= usernameview.getText().toString();
String password = passwordview.getText().toString();
JSONObject login = new JSONObject();
try {
login.put("username",username);
login.put("password",password);
} catch (JSONException e) {
e.printStackTrace();
}
if (login.length() > 0) {
new SendDataToServer().execute(String.valueOf(login));
}
}
here is my class to send data i just wanna know what i should write in doinbackground methode
class SendDataToServer extends AsyncTask<String,String,String> {
#Override
protected String doInBackground(String... params) {
}
#Override
protected void onPostExecute(String s) {
}
}
you can use volley to send request
StringRequest stringRequest = new StringRequest(Request.Method.POST, YOUR_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
for (int i = 0; i < response.length(); i++) {
JSONObject json; // convert String to JSONObject
try {
json = new JSONObject(response);
JSONArray jsonArray = json.getJSONArray("data");
lyric_string = jsonArray.getJSONObject(0).getString("song_lyric");
artist_string = jsonArray.getJSONObject(0).getString("song_artist");
//album_string = jsonArray.getJSONObject(0).getString("song_album");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error message
dismissDialog();
lyric.setText("Sorry No Lyric Found");
lyric.setVisibility(View.VISIBLE);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("song_name", "A song Name");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

How to update json data using volley method on Android?

I get the error no value for city.
I'm new to Android. I was unable to pass the spinner data using PHP URL, volley method. And in my XML I'm using the spinner and text views city, id and pass the city list through spinner URL.
Here is my activity:
private void spinnerapi(){
sprCoun = (Spinner) findViewById(R.id.spinner);
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String serverURL = "server url";
final StringRequest getRequest = new StringRequest(Request.Method.POST, serverURL,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("officerResponse", response);
try {
JSONObject jsonObject = new JSONObject(response);
String str_status = jsonObject.getString("status");
String str_message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectGuest = jsonArray.getJSONObject(i);
city_name = jsonObjectGuest.getString("cityname");
city_id = jsonObjectGuest.getString("cityid");
listarraylist.add(new CityModel(city_name));
}
sprCoun.setAdapter(new ArrayAdapter<String>
(RegistrationActivity.this, android.R.layout.simple_spinner_dropdown_item, list));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_LONG).show();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
// Toast.makeText(context, "" + error, Toast.LENGTH_LONG).show();
Log.d("tyghj", String.valueOf(error));
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
queue.add(getRequest);
}

Android volley how to receive and send a json

I making an app and in a specific part I send a string and receive a json. I USE VOLLEY
It works good, but now i need to send a json.
HERE IS MY CODE:
public static final String DATA_URL = "http://unynote.esy.es/cas/read_allorder.php?id="; // THIS HAVE TO CHANGE JUST TO LOCALHOST:8080/LOGIN
HERE:
public class Config {
public static final String DATA_URL = "http://unynote.esy.es/cas/read_allorder.php?id="; // THIS HAVE TO CHANGE JUST TO LOCALHOST:8080/LOGIN
public static final String KEY_NAME = "COD_ALUMNO";
public static final String KEY_ADDRESS = "COD_ASIGNATURA";
public static final String KEY_VC = "GRUPO_SECCION";
public static final String KEY_AULA = "AULA";
public static final String KEY_DIA = "DIA";
public static final String KEY_INICIO = "INICIO";
public static final String KEY_FIN = "FIN";
public static final String JSON_ARRAY = "result";
}
AND HERE IS THE PART OF VOLLEY CODE
public class TabsActivity extends AppCompatActivity implements
View.OnClickListener {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
int cont=1;
String[ ] contenido = new String[7];
String f="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainint);
editTextId = (EditText) findViewById(R.id.editTextId);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editTextId.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
Toast.makeText(getBaseContext(), "si", Toast.LENGTH_LONG).show();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TabsActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
// Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();
String name="";
String address="";
String grupo = "";
String aula = "";
String dia = "";
String inicio = "";
String fin = "";
try {
Toast.makeText(getBaseContext(), "LOGIN... ", Toast.LENGTH_LONG).show();
JSONObject jsonObject = new JSONObject(response);
JSONArray ja = jsonObject.getJSONArray("orders");
// JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
for (int i = 0; i < ja.length(); i++) {
JSONObject collegeData = ja.getJSONObject(i);
name = collegeData.getString("id");
address = collegeData.getString("item");
grupo = collegeData.getString("GRUPO_SECCION");
aula = collegeData.getString("AULA");
dia = collegeData.getString("DIA");
inicio = collegeData.getString("INICIO");
fin = collegeData.getString("FIN");
///database
DBAdapter db= new DBAdapter(this);
db.open();
long id = db.insertContact(address, aula,dia,inicio,fin );
db.close();
db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst())
{ do{
contenido=getcontenido(c);
}while (c.moveToNext());
}
db.close();
cont= Integer.parseInt( contenido[0]);
/// database
/// alarms
int [] time;
time = parsetime(inicio);
int horai = time[0];
int minutoi = time[1];
int diaa = getDay(dia);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, horai);
cal.set(Calendar.MINUTE, minutoi);
cal.set(Calendar.DAY_OF_WEEK, diaa);
cal.add(Calendar.SECOND, 2);
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.putExtra("name", address);
//intent.putExtra("curos bn",1);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(getBaseContext(),
cont+1, intent, PendingIntent.FLAG_UPDATE_CURRENT );
AlarmManager alarmManager =
(AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), 24 * 7 * 60 * 60 * 1000 , pendingIntent);
////alarms
f=f+"codigo alumno:\t"+name+"\ncodigo/nombre curso:\t" +address+ "\ngrupo:\t"+grupo+"\naula:\t"
+aula+"\ndia:\t"+dia+"\ninicio:\t"+inicio+"\nfin:\t"+fin+"\n:\t";
}
// Toast.makeText(getBaseContext(), collegeData.length(), Toast.LENGTH_LONG).show();
//collegeData.toString();
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText(f);
}
I JUS SENT THE STRING editTextId.getText() . That is a code for each user , but now i need to send a json with that string .
'CCODUSU' '45875621'
CCODUSU is the identifier
I would take a look at StringRequests. Here is an example of how to send things to a PHP file, which updates a database, or can do whatever:
SetMyStuff.java:
package com.example.your_app.database_requests;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class SetMyStuff extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://example.com/SetMyStuff.php";
private Map<String, String> params;
public SetMyStuff(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;
}
}
To call this StringRequest:
Response.Listener<String> listener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (!success) {
Log.e(TAG, "Could not update stuff.");
} else {
Log.e(TAG, "Updated stuff.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
SetMyStuff setMyStuffRequest = new SetMyStuff(username, password, listener);
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(setMyStuffRequest);
The PHP file that recieves this:
<?php
$password = $_POST["password"];
$username = $_POST["username"];
$con = mysqli_connect("website.com", "dbusername", "dbpassword", "dbtable");
$response = array();
$response["success"] = false;
/* Do something */
$response["success"] = true;
echo json_encode($response);
?>
Do you mean you need send a JSON which contains the editTextId.getText().toString().trim(), if you want to do this, you must spell out a complete and correct JSON.
'CCODUSU' '45875621'
The string you post is not a json, you need to modify it into this:
{"CCODUSU": "45875621"}
Once you give this string after your Config.DATA_URL, the server will receive the id parameter and it is the JSON.
I also came up with this same issue.On the course of finding way I have developed a way that might help you.
If you want to post json to the server then you can create JsonObjectRequest as:
public class AppJSONObjectRequest extends JsonObjectRequest{
private Response.Listener<JSONObject> listener;
private Map<String, String> headers;
public AppJSONObjectRequest(int method, String url, JSONObject jsonObject, Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener, Map<String, String> headers) {
super(method, url, jsonObject, reponseListener, errorListener);
this.headers = headers;
this.listener = reponseListener;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
}
And then you can use this jave file in your activity or fragment to send json and recieve response like this below:
JSONObject parameters = new JSONObject();
try {
parameters.put("f_name", "name1");
parameters.put("l_name", "name2");
.......
}catch (Exception e){
e.printStackTrace();
}
AppJSONObjectRequest objectRequest = new AppJSONObjectRequest(Request.Method.PUT, url, parameters, RequestSuccessListener, RequestErrorListener, getHeaders); //headers if u have
//url: your request base url
VolleySingleton volleySingleton = VolleySingleton.getInstance(this);
volleySingleton.addToRequestQueue(objectRequest);
And you can receive json as :
Response.Listener<JSONObject> RequestSuccessListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "Response" + " " + response);
}
};
Response.ErrorListener RequestErrorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
you can get headers as:
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("x-auth-token", Constant.API_KEY_X_AUTH_TOKEN);
return headers;
}
VolleySingleton class
public class VolleySingleton {
private static VolleySingleton mInstance;
private Context mContext;
private RequestQueue mRequestQueue;
private VolleySingleton(Context context){
this.mContext = context;
mRequestQueue = getRequestQueue() ;
}
public static synchronized VolleySingleton getInstance(Context context){
if(mInstance == null){
mInstance = new VolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req){
getRequestQueue().add(req);
}
}
Just you can implement above sample... then hope you will get what you want.it may be copy paste code but it covers overall enough to solve your problem.

Categories

Resources