Volley JsonObjectRequest sending 3 JSONObject in same request? - android

I created a JsonObjectRequest that I use to send a JSONObject to my WebService. When I try send this JSONObject the object is sending but send 3 objects instead 1. Looking in my data base there's 3 objects added.
I can't understand why this problem, because I always send 1 JSONObject but in webservice there's 3 objects.
I tried to use Postman of Google Chrome, and using Postman send 1 JSONObject normally.
What can be ?
JsonObjectRequest
public JsonObjectRequest sendContatoToEmpresa(String nome,
String email,
String telefone,
String assunto,
String mensagem,
String idEmpresa,
final ContatoAdapter listener){
urlPost.append(WebServiceURL.getBaseWebServiceURL());
urlPost.append("/ws/contatos/contatos/add.json");
JSONObject jsObject = new JSONObject();
try {
JSONObject objs = new JSONObject();
objs.put("nome", nome);
objs.put("email", email);
objs.put("telefone", telefone);
objs.put("assunto", assunto);
objs.put("mensagem", mensagem);
objs.put("pessoa_id", idEmpresa);
jsObject.put("Contato", objs);
Log.i("JSONOBJECT->", jsObject.toString());
}catch(JSONException e){
Log.e("JSONException->", e.getLocalizedMessage());
}
Log.i("URL CONTATO EMPRESA->", urlPost.toString());
JsonObjectRequest apc = new JsonObjectRequest(Request.Method.POST,
urlPost.toString(),
jsObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
try {
Log.i("JSOBJECT->", jsonObject.toString());
if(jsonObject.getString("status").equals("999")){
listener.isSend(true);
}else{
listener.isSend(false);
}
} catch (JSONException e) {
Log.e("JSONException->", e.getLocalizedMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("ERROR METHOD:", "sendContatoToEmpresa in ContatoDAO: " + volleyError.getLocalizedMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String auth = new String(android.util.Base64.encode((BasicAuthenticationRest.USERNAME + ":" + BasicAuthenticationRest.PASSWORD).getBytes(), android.util.Base64.URL_SAFE | android.util.Base64.NO_WRAP));
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Authorization", "Basic " + auth);
return headers;
}
};
return apc;
}
Activity
public Integer sendContatoToEmpresa(String nome,
String email,
String telefone,
String assunto,
String mensagem,
String idEmpresa){
final int[] send = {0};
if(nome.length() == 0 ||
email.length() == 0 ||
telefone.length() == 0 ||
assunto.length() == 0 ||
mensagem.length() == 0){
Toast.makeText(getView().getContext(), "Informe todos os campos", Toast.LENGTH_SHORT).show();
send[0] = 0;
}else{
final ProgressDialog progress = new CustomProgressDialog().getCustomProgress(null, getView().getContext());
progress.show();
JsonObjectRequest app = new ContatoDAO().sendContatoToEmpresa(nome,
email,
telefone,
assunto,
mensagem,
idEmpresa,
new ContatoAdapter(){
#Override
public void isSend(Boolean value) {
if(value){
send[0] = 1;
}
progress.dismiss();
}
});
CustomVolleySingleton.getInstance(getView().getContext()).addToRequestQueue(app);
}
return send[0];
}
CustomVolleySingleton
public class CustomVolleySingleton extends Application{
private static CustomVolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
public static final String TAG = "VolleyPatterns";
private CustomVolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new CustomVolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}

Try to do the following:
app.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Here you can change the timeout (MY_SOCKET_TIMEOUT_MS) and change the number of attempts (DefaultRetryPolicy.DEFAULT_MAX_RETRIES)

Related

jsonexception value <br of type java.lang.string cannot be converted to jsonarray

i need to show post of user .. i make recyclerview
and php file when you pass a user_id you get your post in RecyclerView ..
For testing i made php file get all posts of users and worked successfully,
but when i make php file when you are passing a user_id it worked on post man and get result as array postman result
its the same result of first php file that get all posts
but in android php file one get result and show it in recyclerview with no problem
with seconed php file give me a message "jsonexception value
thats my java code
private void load(){
final String user_id=SharedPref.getInstance(getActivity()).getid();
RequestQueue rq= Volley.newRequestQueue(getActivity());
JsonArrayRequest jar=new JsonArrayRequest(Request.Method.POST, Constants.MyPOST_URL,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int x=0;x<response.length();x++)
{
try {
JSONObject obj=response.getJSONObject(x);
location=obj.getString("location");
description=obj.getString("description");
bloodtype=obj.getString("bloodtype");
number=obj.getString("number");
date=obj.getString("created_at");
GetMyPost data=new GetMyPost(description,location,bloodtype,number,date);
data_list.add(data);
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new RecyclerViewAdapter(getActivity(),data_list);
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),error.getMessage(),Toast.LENGTH_LONG).show();
}
}
)
{
#Override
protected Map<String,String> getParams() {
Map<String,String> params = new HashMap<String, String>();
params.put("user_id",user_id);
return params;
}
};
rq.add(jar);
}
i get user_id from sharedpref i tested it and return my id with no problem
please help me
send params to server
Map<String, String> params = new HashMap<String, String>();
try {
params.put("user_id", user_id);
JSONObject JsonObj = new JSONObject(params);
JsonArrayRequest jar=new JsonArrayRequest
(Request.Method.POST,
Constants.MyPOST_URL ,
JsonObj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
getData_and_set_Model(response);
}catch (Exception ex){
ex.printStackTrace();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(productActivity.this,"VolleyError : " +
error.getMessage()+ "", Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectReq);
}catch (Exception ex){}
and
create class AppController extends Application
in AndroidManifest >
> <application
> android:name=".AppController"
>
> <uses-permission android:name="android.permission.INTERNET" />
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
you problem is send server
Tell me if it is not resolved

How to I send POST parameters in this android studio code [duplicate]

This question already has answers here:
Sending POST data in Android
(17 answers)
Closed 5 years ago.
I'm new to android and learning it now. I'm working on an application where I was able to get response form a get request successfully. Now I want to execute a POST request with a single parameter this is what I've came up with so far:
public class BGTask extends AsyncTask<String, String, String > {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
String color = "null";
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
//I want to pass the id parameter
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
int status = parentObject.getInt("status");
if(status == 1) {
color = parentObject.getString("bgcolor");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return color;
}
}
The variable color is in hex code i.e #FF0089
** Use volley library for GET , POST and network calls it's very simple and efficient **
First create AppController.java
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}
}
Second make POST request
public void Send() {
final String First = "";
final String Second = "";
StringRequest stringRequest = new StringRequest(Request.Method.POST, CREATEORDER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE", response);
JSONObject jObj = null;
try {
jObj = new JSONObject(response);
String success = jObj.getString("success");
String errorMessage = jObj.getString("message");
if (success.equals("")) {
Intent intent = new Intent(SendGiftActivity.this, PayScreenActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(SendGiftActivity.this, errorMessage, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(SignUpActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SendGiftActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_FIRST_PARAMETERS, First);
params.put(KEY_SECOND_PARAMETER, Second);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Include volley library
compile 'com.android.volley:volley:1.0.0'
Don't forget to add android:name=".AppController" in application tag of manifest file

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.

Passing parameters in Volley JSONArray Request

I am trying to get posts from server based on a parameter i.e. email address. How do I send parameters in JSONArrayRequest so that only those posts are retrieved which are matched with the given parameter? Here is my code:
JsonArrayRequest:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i= 0; i<response.length(); i++){
try {
JSONObject object = response.getJSONObject(i);
Post post = new Post();
post.setContent(object.getString("Content"));
post.setDate(object.getString("PostDate"));
post.setTime(object.getString("PostTime"));
postArray.add(post);
PostList.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getmInstance().addToRequestQueue(jsonArrayRequest);
And this is the AppController.Java class:
public class AppController extends Application {
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
public static final String TAG = AppController.class.getSimpleName();
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getmInstance() {
return mInstance;
}
public RequestQueue getmRequestQueue()
{
if(mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getmImageLoader(){
getmRequestQueue();
if(mImageLoader == null){
mImageLoader = new ImageLoader(this.mRequestQueue, new BitmapCache());
}
return mImageLoader;
}
public <T> void addToRequestQueue(Request<T> request, String tag ){
request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getmRequestQueue(). add(request);
}
public <T> void addToRequestQueue(Request<T> request ){
request.setTag(TAG);
getmRequestQueue(). add(request);
}
public void cancelPendingRequest(Object tag){
if(mRequestQueue != null){
mRequestQueue.cancelAll(tag);
}
}
}
void MakePostRequest() {
StringRequest postRequest = new StringRequest(Request.Method.POST, EndPoints.BASE_URL_ADS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
value1= jsonResponse.getString("Your ID1");
value2= jsonResponse.getString("Your ID2");
} catch (JSONException e) {
e.printStackTrace();
banner_id = null;
full_id = null;
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
value1= null;
value2= null;
}
}
) {
// here is params will add to your url using post method
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("app", getString(R.string.app_name));
//params.put("2ndParamName","valueoF2ndParam");
return params;
}
};
Volley.newRequestQueue(this).add(postRequest);
}
this post request is using this compile 'com.mcxiaoke.volley:library:1.0.19' volley version.
i am just adding app name as parameter.you can add more params.

posting data to server in json format using volley

Hello i am posting data to server in json format,
but it returns volley server error in error response`
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject jobj=new JSONObject();
try {
jobj.put("id",”123”);
jobj.put("session","new");
JSONArray array = null;
array = new JSONArray();
for (int i = 0;i<3;i++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","test");
jsonObject.put("content","test");
jsonObject.put("time"," 2016-04-07T11:44:22.407Z ");
array.put(jsonObject);
}
Log.e(" array "," arrr"+array.toString());
jobj.put("data",array);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("jsondata",jobj.toString());
JsonObjectRequest sr= new JsonObjectRequest(post_url, jobj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#OveRequestQueue queue = Volley.newRequestQueue(this);
JSONObject jobj=new JSONObject();
try {
jobj.put("id",”123”);
jobj.put("session","new");
JSONArray array = null;
array = new JSONArray();
for (int i = 0;i<3;i++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","test");
jsonObject.put("content","test");
jsonObject.put("time"," 2016-04-07T11:44:22.407Z ");
array.put(jsonObject);
}
Log.e(" array "," arrr"+array.toString());
jobj.put("data",array);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("jsondata",jobj.toString());
JsonObjectRequest sr= new JsonObjectRequest(post_url, jobj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}rride
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/json");
return params;
}
};
queue.add(sr);`
Have a singleton which handles the request queue.
public class VolleySingleton {
// Singleton object...
private static VolleySingleton instance;
final private RequestQueue requestQueue;
private static ImageLoader imageLoader;
//Constructor...
private VolleySingleton(Context context) {
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<>(100000000);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
// Singleton method...
public static VolleySingleton getInstance(Context context) {
if (instance == null) {
instance = new VolleySingleton(context);
}
return instance;
}
public RequestQueue getRequestQueue(Context context) {
if (requestQueue != null) {
return requestQueue;
} else {
getInstance(context);
return requestQueue;
}
}
private RequestQueue getRequestQueue() {
return requestQueue;
}
public static ImageLoader getImageLoader(Context context) {
if (imageLoader != null) {
return imageLoader;
} else {
getInstance(context);
return imageLoader;
}
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag("App");
getRequestQueue().add(req);
}
}
Then using the below method you can send the request.
public void postVolley(final Context context, String url, JSONObject jsonObject) {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject responseJson) {
Log.e("success", "" + responseJson.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "" + error);
}
}) {
/**
* Setting the content type
*/
#Override
public String getBodyContentType() {
return "application/json;charset=UTF-8";
}
};
VolleySingleton.getInstance(context).addToRequestQueue(jsonObjReq);
}
This works fine for me.

Categories

Resources