Volley send JSONObject to server with POST method - post

I want to send a jsonobject with below format to server by using volley library
{
"user_id": 12,
"answers": {
"11": 3,
"12": 4,
"13": 5
}
}
JSONObject object = new JSONObject();
try {
object.put("user_id", user_id);
JSONObject answers = new JSONObject();
for (int i = 0; i < questions.size(); i++) {
JSONObject answer = new JSONObject();
answer.put(questions.get(i).getId(),questions.get(i).getAnswer());
answers.put("answers", answer);
object.put("answers", answer);
}
} catch (JSONException e) {
e.printStackTrace();
}
If I want to use StringRequest how should I send this JsonObject to server by using POST method

You can use the following working sample code. I have tested. Hope this helps!
try {
jsonBody = new JSONObject();
jsonBody.put("Title", "VolleyApp Android Demo");
jsonBody.put("Author", "BNK");
jsonBody.put("Date", "2015/08/26");
requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(1, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
textView.setText(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText(error.toString());
}
}) {
#Override
public String getBodyContentType() {
return String.format("application/json; charset=utf-8");
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
requestBody, "utf-8");
return null;
}
}
};
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
UPDATE: To create JSONObject as your requirement, use the following:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("11", 3);
jsonObject.put("12", 4);
jsonObject.put("13", 5);
JSONObject jsonObject2 = new JSONObject().put("answers", jsonObject);
jsonObject2.put("user_id", 12);
} catch (JSONException e) {
e.printStackTrace();
}

use the following sample code
RequestQueue queue = Volley.newRequestQueue(this);
private void serverFronJsonObjReq() {
showProgressDialog();
Map<String, String> postParam= new HashMap<String, String>();
postParam.put("username", "singh#gmail.com");
postParam.put("password", "123456");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.BASE_URL_LOGIN, new JSONObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjReq.setTag(TAG);
// Adding request to request queue
queue.add(jsonObjReq);
// Cancelling request
/* if (queue!= null) {
queue.cancelAll(TAG);
} */
}

Related

Android Volley POST request out of synchronization

I'm using the implementation 'com.android.volley:volley:1.1.1' to make a POST call to a REST web service. Unfortunately, the conclusion (i.e. User does not exist) is reached before the response comes back from the server and is always wrong (In reality user actually does exist).
On the console, the logger messages appear in the wrong order:
E/: THIS IS SUPPOSED TO HAPPEN SECOND - USER NOT FOUND ALERT
I/: THIS IS SUPPOSED TO HAPPEN FIRST: VALIDATING DATA
After hours of reading, I found that a Callback Interface will ensure proper execution order. However, after implementing it, the result is the same. What could be wrong, please?
ControladorLoginExistente.Java
public class ControladorLoginUsrExistente {
public AbstractMap.SimpleEntry<String, Map<String, String>> callEndpointLoginUsrExistente(Context context) {
try {
JSONObject jsonRequest = new JSONObject();
jsonRequest.put("email", "mymail#themail.com");
jsonRequest.put("password", "12345");
final JSONObject[] jsonResponse = {null};
new PostRequestConVolley().getResponse(Constantes.URL_ACCESO_USUARIO_EXISTENTE, jsonRequest, context, new VolleyCallback() {
#Override
public void onSuccessResponse(JSONObject jsonObject) {
jsonResponse[0] = jsonObject;
Log.i(null,"THIS IS SUPPOSED TO HAPPEN FIRST: VALIDATING DATA");
}
});
Boolean exito = jsonResponse[0].getBoolean("exito");
String descripcion = jsonResponse[0].getString("descripcion");
String codigoHttp = jsonResponse[0].getString("codigoHttp");
JSONArray respuestaTransaccion = jsonResponse[0].getJSONArray("respuestaTransaccion");
if(exito == false || codigoHttp.equals("200")){
Log.e(null,"THIS IS SUPPOSED TO HAPPEN SECOND: USER NOT FOUND ALERT");
return new AbstractMap.SimpleEntry<>(descripcion, new HashMap<>());
}
Log.i(null,"THIS IS SUPPOSED TO HAPPEN SECOND: USER NOT FOUND ALERT");
return new AbstractMap.SimpleEntry<>(Constantes.EXITO, new HashMap<>());
} catch (Exception ex) {
Log.e(null,"THIS IS SUPPOSED TO HAPPEN SECOND: USER NOT FOUND ALERT");
return new AbstractMap.SimpleEntry<>("ERROR: " + ex.toString(), new HashMap<>());
}
}
}
PostRequestConVolley.java
public class PostRequestConVolley {
public JSONObject getResponse(String url, JSONObject body, Context context, final VolleyCallback callback) {
try {
RequestQueue queue = Volley.newRequestQueue(context);
JsonObjectRequest jsonRequest = new JsonObjectRequest(POST, url, body,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
callback.onSuccessResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(null, error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("Connection", "keep-alive");
return params;
}
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
Log.i(null, "El HTTP code es:" + response.statusCode);
return super.parseNetworkResponse(response);
}
};
queue.add(jsonRequest);
} catch (Exception ex) {
ex.printStackTrace();
}
return body;
}
}
VolleyCallbackInterface
import org.json.JSONObject;
public interface VolleyCallback {
void onSuccessResponse(JSONObject jsonObject);
}

How to to praise multiple Youtube channels using Volley

I'm creating an app for all my clients youtube channels, I'm using volley to praise the channels,
my problem is when I click on any channels it only retrieve one channel, so how can I make the volley understands that it should fetch different channels on click
here is the code sample >
ListView channelList;
ArrayList<VideoDetails> videoDetailsArrayList;
ChannelAdapter channelAdapter;
String channelUrl="";
String channelId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_channel);
channelList = findViewById(R.id.channelList);
videoDetailsArrayList = new ArrayList<>();
channelAdapter = new ChannelAdapter(ChannelActivity.this,videoDetailsArrayList);
channelUrl = String.format(getIntent().getStringExtra("channelUrl"), channelId);
channelId = getIntent().getStringExtra("id");
displayVideos();
}
private void displayVideos() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, channelUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("items");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonVideoId = jsonObject1.getJSONObject("id");
JSONObject jsonObjectSnippet = jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectDefault = jsonObjectSnippet.getJSONObject("thumbnails").getJSONObject("medium");
String video_Id = jsonVideoId.getString("videoId");
VideoDetails vd = new VideoDetails();
vd.setVideoId(video_Id);
vd.setTitle(jsonObjectSnippet.getString("title"));
vd.setDescription(jsonObjectSnippet.getString("description"));
vd.setUrl(jsonObjectDefault.getString("url"));
videoDetailsArrayList.add(vd);
}
channelList.setAdapter(channelAdapter);
channelAdapter.notifyDataSetChanged();
}catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
}
);
requestQueue.add(stringRequest);
}
}

How to Parsing JSON Array file withOuth name?

Pleas Expert help me..!!
I have a Json some like this
["google.com","youtube.com","facebook.com","tweeter.com","instagram.com"]
And i need to display in ListView.
Pleas Help..!!
And Thaks.
I can finish it by yourself with the following code
JsonArrayRequest jsonObjReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
//JSONArray array = new JSONArray(response);
for (int i = 0; i < response.length(); i++) {
//JSONObject arry = response.getJSONObject(i);
ListFA data = new ListFA();
data.setName(response.get(i).toString());
forbidlist.add(data);
}
}
catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq);

http post blackberry (null response)

I have used this code mod from some url here :
HttpConnection httpConnection = (HttpConnection) Connector.open(webservice_address,Connector.READ_WRITE);
httpConnection.setRequestMethod(HttpConnection.POST);
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false);
encPostData.append("category", String.valueOf(category));
byte[] postData = encPostData.toString().getBytes("UTF-8");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postData.length));
OutputStream os = httpConnection.openOutputStream();
os.write(postData);
os.flush();
os.close();
return httpConnection.getResponseMessage();
But response is always the same, i obtain a "null all times , when i was expected to have a JSON object response , any idea?
P.S: I'm sure server sends data
P.S: I have tried with Connector.READ_WRITE with the same result.
P.S: I'm doing it in the blackberry 9930 simulator
Try like this sample code:
public class ConnectionThread extends Thread
{
String url;
HttpConnection httpConnection;
InputStream inputStream;
String id="0";
StringBuffer stringBuffer=new StringBuffer();
public ConnectionThread(String url)
{
this.url=url;
}
public void run()
{
try
{
httpConnection=(HttpConnection)Connector.open("Giver Your URL"+";interface=wifi");
URLEncodedPostData oPostData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
oPostData.append("category",id);//Parameters list;
oPostData.append("categoryName","Categ1");
System.out.println("================"+oPostData.toString());
httpConnection.setRequestMethod(HttpConnection.POST);
httpConnection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, oPostData.getContentType());
byte [] postBytes = oPostData.getBytes();
httpConnection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, Integer.toString(postBytes.length));
OutputStream strmOut = httpConnection.openOutputStream();
strmOut.write(postBytes);
strmOut.flush();
strmOut.close();
int response=httpConnection.getResponseCode();
if(response==HttpConnection.HTTP_OK)
{
inputStream = httpConnection.openInputStream();
int c;
while((c=inputStream.read())!=-1)
{
stringBuffer.append((char)c);
}
callBack(stringBuffer.toString());
}
else
{
callBack("ERROR");
}
}
catch (Exception e)
{
synchronized (UiApplication.getEventLock())
{
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
StartUp.exceptionHandling(e.getMessage());
}
}
finally
{
try
{
if(httpConnection!=null)
{
httpConnection.close();
}
if(inputStream!=null)
{
inputStream.close();
}
}
catch (Exception e2)
{}
}
}
private void callBack(String response)
{
if(response.equals("ERROR"))
{
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
// Put an alert here that "URL Not found";
}
else
{
try
{
System.out.println(response);
//do what you want;
}
catch (Exception e)
{
// Put an alert here that "Data Not found";
}
}
}
}
This is a sample code for POST the data;
Cau u please add Connector.READ_WRITE in Connector.open
HttpConnection httpConnection = (HttpConnection) Connector.open(webservice_address,Connector.READ_WRITE);
Have you tried to avoid calling os.close() before reading the response?

Blackberry screen renew with new data

I am developing a Blackberry Application. I have a map in a screen. I want to refresh map's data with new data which i am getting from my web service. I am using BlockingSenderDestination in a Thread. When i request "get data" its return new data. no problem. I am using invokelater function to call my maprefresh function with passing arguments but i got illegalargumentexception.
Any suggestion to solve my problem or any better way to do this?
Here is my code:
public class MyMainScreen extends MainScreen {
RichMapField map;
MyClassList _myclassList;
private String _result2t;
public MyMainScreen(JSONArray jarray)
{
map = MapFactory.getInstance().generateRichMapField();
MapDataModel mapDataModel = map.getModel();
JSONObject json = null;
boolean getdata=false;
for (int i=0;i<jarray.length();i++)
{
try
{
json=jarray.getJSONObject(i);
getdata=true;
}
catch(Exception e)
{
}
if(getdata)
{
try
{
double lat = Double.valueOf(json.getString("LATITUDE")).doubleValue();
double lng = Double.valueOf(json.getString("LONGITUDE")).doubleValue();
String myclassdata= json.getString("myclassdata").toString();
MyClass ben = new MyClass(myclassdata);
_myclassList.addElement(ben);
MapLocation termimapitem = new MapLocation( lat, lng, "","");
mapDataModel.add((Mappable)termimapitem,"1");
}
catch(Exception e)
{
//mesajGoster("Hatalı Veri");
}
}
else
{
//mesajGoster("Listeye Eklenemedi");
}
}
}
private void GetTerminals(String companyNo){
final String companyNoR= companyNo;
Thread t = new Thread(new Runnable()
{
public void run()
{
Message response = null;
String uriStr = "http://webservice";
BlockingSenderDestination bsd = null;
try
{
bsd = (BlockingSenderDestination)
DestinationFactory.getSenderDestination
("o", URI.create(uriStr));
if(bsd == null)
{
bsd =
DestinationFactory.createBlockingSenderDestination
(new Context("o"),
URI.create(uriStr)
);
}
response = bsd.sendReceive();
if(response != null)
{
BSDResponse(response,companyNoR);
}
}
catch(Exception e)
{
}
finally
{
if(bsd != null)
{
bsd.release();
}
}
}
});
t.start();
}
private void BSDResponse(Message msg,final String companyNo)
{
if (msg instanceof ByteMessage)
{
ByteMessage reply = (ByteMessage) msg;
_result2t = (String) reply.getStringPayload();
} else if(msg instanceof StreamMessage)
{
StreamMessage reply = (StreamMessage) msg;
InputStream is = reply.getStreamPayload();
byte[] data = null;
try {
data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
} catch (IOException e) {
// process the error
}
if(data != null)
{
_result2t = new String(data);
}
}
try {
final JSONArray jarray= new JSONArray(_result2t);
final String username=_userName;
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("The Toolbar i");
Yenile(jarray);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void Yenile(JSONArray jarray){
MapDataModel mapDataModel = map.getModel();
mapDataModel.remove("1");
map.getMapField().update(true);
_terminalList = new TerminalList();
map= MapFactory.getInstance().generateRichMapField();
MapDataModel mapDataModel = map.getModel();
JSONObject json = null;
boolean getdata=false;
for (int i=0;i<jarray.length();i++)
{
try
{
json=jarray_terminaller.getJSONObject(i);
getdata=true;
}
catch(Exception e)
{
}
if(getdata)
{
try
{
double lat = Double.valueOf(json.getString("LATITUDE")).doubleValue();
double lng = Double.valueOf(json.getString("LONGITUDE")).doubleValue();
String myclassdata= json.getString("myclassdata").toString();
MyClass ben = new MyClass(myclassdata);
_myclassList.addElement(ben);
MapLocation termimapitem = new MapLocation( lat, lng, "","");
mapDataModel.add((Mappable)termimapitem,"1");
}
catch(Exception e)
{
//mesajGoster("Hatalı Veri");
}
}
else
{
//mesajGoster("Listeye Eklenemedi");
}
}
}
}
To refresh the screen: do like this:
public class LoadingScreen extends MainScreen{
LoadingScreen()
{
createGUI();
}
public void createGUI()
{
//Here you write the code that display on screen;
}}
we know that this is the actual way of creating a screen;
Now if you want to refresh the screen write like below:
deleteAll();
invalidate();
createGUI();//here it creates the screen with new data.
Instead of writing in InvokeLater method better to write the above three lines in run method after Thread.sleep(10000);
If you have any doubts come on stackOverFlow chat room name "Life for Blackberry" for clarify your and our doubts.
I found a solution to my question.
After getting the data i was sending it via new run method:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
MyFunction(jarray);
}});
But i was need to synchronize with main thread. So the solution:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
synchronized(Application.getEventLock()) {
Yenile(jarray);
}
}
});

Resources