Get POST Result in JSON - java

I'm sending the data with the POST. I get the answer with JSON.
If I use plain text instead of JSON, it's working but It doesn't work with JSON.
I do not receive any error screen in the application
if (status) = true -> Register OK
IMPORT:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import javax.xml.transform.Result;
JSON:
[{"status":true,"result":"registerSuccessful","message":"Register succeeded"}]
JAVA Code:
private void registernewuser() {
StringRequest request = new StringRequest(Request.Method.POST, registerUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
String RegisterResultString = jsonResponse.getString("status");
if (RegisterResultString.equals("true")) {
Toast.makeText(getApplicationContext(), "Successfully Registered User", Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Sorry, Error Registering New User", Toast.LENGTH_LONG).show();
}
} 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("registeruser", "true");
params.put("username", username.getText().toString().trim());
params.put("userpassword", userpassword.getText().toString().trim());
params.put("useremail", useremail.getText().toString());
return params;
}
};
Volley.newRequestQueue(this).add(request);
}
I'm not having trouble building applications. But I can't find my fault.

Your JSON code is a JSONArray with a single JSONObject because of square brackets. So, just set type of your jsonResponse as JSONArray and fetch a JSONObject using the JSONArray.getJSONObject(0) method.
JSONArray jsonResponse = new JSONArray(response);
String registerResultString = jsonResponse.getJSONObject(0).getString("status");

You need to add the header to your request to indicate the JSON usage :
request.addHeader("content-type", "application/json");
Else it will interpret it as plain text.

You can call the request as JSONRequest
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
your_url, new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};

Related

Android Studio Java JSON fetching data problem

PLEASE HELP, WHAT IS WRONG WITH MY CODE, IT DISPLAYS NOTHING BUT ZEROS AND NULL
I already search through tutorials, i even copied the whole code but i cant get the data from this API, my textviews on int are returning zeros and my textviews on string are returning null after a press the update button.
here is my api link = api link
here is the result
package com.example.firstapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private TextView confirmed, recovered, deaths, country, date;
private RequestQueue mQueue;
private Button update;
private int c,r,d;
private String co,da;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
confirmed = findViewById(R.id.confirmed);
recovered = findViewById(R.id.recovered);
deaths = findViewById(R.id.deaths);
country = findViewById(R.id.country);
date = findViewById(R.id.date);
update = findViewById(R.id.update);
mQueue = Volley.newRequestQueue(this);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
confirmed.setText(String.valueOf(c));
recovered.setText(String.valueOf(r));
deaths.setText(String.valueOf(d));
country.setText(co);
date.setText(da);
}
});
}
private void jsonParse(){
String url = "https://covid-api.mmediagroup.fr/v1/cases?country=Philippines";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("All");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject cases = jsonArray.getJSONObject(i);
c = cases.getInt("confirmed");
r = cases.getInt("recovered");
d = cases.getInt("deaths");
co = cases.getString("country");
da = cases.getString("updated");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(),
Toast.LENGTH_LONG).show();
}
});
mQueue.add(request);
}
}
I don't know what is the problem here, can someone help
I already fixed it thank you so much.
my solution is I removed JsonArray.
package com.example.firstapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private TextView confirmed, recovered, deaths, country, date;
private RequestQueue mQueue;
private Button update;
private int c,r,d;
private String co,da;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
confirmed = findViewById(R.id.confirmed);
recovered = findViewById(R.id.recovered);
deaths = findViewById(R.id.deaths);
country = findViewById(R.id.country);
date = findViewById(R.id.date);
update = findViewById(R.id.update);
mQueue = Volley.newRequestQueue(this);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse(){
String url = "https://covid-api.mmediagroup.fr/v1/cases?country=Philippines";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
//JSONArray jsonArray = response.getJSONArray();
for (int i = 0; i < response.length(); i++) {
JSONObject cases = response.getJSONObject("All");
c = cases.getInt("confirmed");
r = cases.getInt("recovered");
d = cases.getInt("deaths");
co = cases.getString("country");
da = cases.getString("updated");
confirmed.setText(String.valueOf(c));
recovered.setText(String.valueOf(r));
deaths.setText(String.valueOf(d));
country.setText(co);
date.setText(da);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(),
Toast.LENGTH_LONG).show();
}
});
mQueue.add(request);
}
}
I replaced
JSONObject cases = jsonArray.getJSONObject(i);
with
JSONObject cases = response.getJSONObject("All");
and removed
JSONArray jsonArray = response.getJSONArray();
because it is not necessary.

Twitter oauth with volley

I want to create an app that can post tweets to my twitter account.
I'm very new to coding and android so I'm struggling a lot here.
I can get a successful response using postman so i know my twitter API keys and secrets etc are correct.
But my question is. How do I take that postman request and turn it into something android can send.
Here's my first attempt.
I guess I'm not passing the tokens correctly?
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private TextView post_reponse_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button post_request_button=findViewById(R.id.test);
post_reponse_text=findViewById(R.id.get_response_data);
post_request_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postRequest();
}
});
}
private void postRequest(){
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url="https://api.twitter.com/1.1/statuses/user_timeline.json";
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
post_reponse_text.setText("Post Data : " +response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
post_reponse_text.setText("Post Data : Failed");
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap <String, String>();
params.put("screen_name", "realnamehere");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("API Key", "placerealtokenshere");
params.put("API Secret", "placerealtokenshere");
params.put("TWITTER_ACCES_TOKEN", "placerealtokenshere");
params.put("TWITTER_ACCES_TOKEN_SECRET", "placerealtokenshere");
return params;
}
};
queue.add(stringRequest);
}
}
Below is the curl request as supplied by twitter. How so i code that up?
curl --request POST \
--url 'https://api.twitter.com/1.1/statuses/update.json?status=Hello%20world' \
--header 'authorization: OAuth oauth_consumer_key="CONSUMER_API_KEY", oauth_nonce="OAUTH_NONCE", oauth_signature="OAUTH_SIGNATURE", oauth_signature_method="HMAC-SHA1", oauth_timestamp="OAUTH_TIMESTAMP", oauth_token="ACCESS_TOKEN", oauth_version="1.0"' \

how to pass header api key in volley

I am new to android and volley
I'm straggling with JSON path
spent a lot of time debugging this code but unfortunately could not find the bug, can someone help me find the issue in this code. I am not able to see data on the activity page
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class dailyshop extends AppCompatActivity {
private RecyclerView mRecycler;
private cardAdapter mCardAdapter;
private ArrayList<carditem> mCardList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dailyshop);
mRecycler = findViewById(R.id.recycler_view);
mRecycler.setHasFixedSize(true);
mRecycler.setLayoutManager(new LinearLayoutManager(this));
mCardList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON(){
String url = "https://fortnite-api.theapinetwork.com/store/get";
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String itemName = jsonObject.getString("name");
String imageUrl = jsonObject.getString("background");
int vCount = jsonObject.getInt("cost");
mCardList.add(new carditem(imageUrl,itemName,vCount));
}
mCardAdapter = new cardAdapter(dailyshop.this, mCardList);
mRecycler.setAdapter(mCardAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "mycode");
return params;
}
};
mRequestQueue.add(request);
}
}
I tried to use custom API without key in same JSON child and it worked
api json file
{
"lastUpdate":1563408000,
"language":"en",
"data":[
{
"itemId":"0ac5766-6f9355e-6575a4e-abaef79",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"500",
"occurrences":1,
"isNew":true
},
"item":{
"name":"Glitter",
"description":"",
"type":"emote",
"rarity":"rare",
"costmeticId":null,
"images":{
"icon":"https://fortnite-public-files.theapinetwork.com/emote/a7eb82676b96bc1ff2129ee739d70d4a.png",
"featured":null,
"background":"https://fortnite-public-files.theapinetwork.com/image/0ac5766-6f9355e-6575a4e-abaef79.png",
"information":"https://fortnite-public-files.theapinetwork.com/image/0ac5766-6f9355e-6575a4e-abaef79/item.png"
},
"backpack":{
},
"obtained_type":"vbucks",
"ratings":{
"avgStars":4.18,
"totalPoints":614,
"numberVotes":147
}
}
},
{
"itemId":"d2e8284-fb06feb-ea3fbe3-c41fd8b",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"800",
"occurrences":3,
"isNew":false
},
"item":{
"name":"Star Wand",
"description":null,
"type":"pickaxe",
"rarity":"rare",
"costmeticId":null,
"images":{
"icon":"https://fortnite-public-files.theapinetwork.com/pickaxe/e0907bc2a6058035c5bf96820da6c21f.png",
"featured":null,
"background":"https://fortnite-public-files.theapinetwork.com/image/d2e8284-fb06feb-ea3fbe3-c41fd8b.png",
"information":"https://fortnite-public-files.theapinetwork.com/image/d2e8284-fb06feb-ea3fbe3-c41fd8b/item.png"
},
"backpack":{
},
"obtained_type":"vbucks",
"ratings":{
"avgStars":4.07,
"totalPoints":789,
"numberVotes":194
}
}
},
{
"itemId":"eb00ead-bb56b45-05e52f8-2398d3a",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"300",
"occurrences":1,
"isNew":true
},
"item":{
"name":"Scanline",
"description":"",
"type":"wrap",
"rarity":"uncommon",
"costmeticId":null,
"images":{
"icon":"https://fortnite-public-files.theapinetwork.com/wrap/5677d39e97ba5bf8d92e25bc520e7cc0.png",
"featured":null,
"background":"https://fortnite-public-files.theapinetwork.com/image/eb00ead-bb56b45-05e52f8-2398d3a.png",
"information":"https://fortnite-public-files.theapinetwork.com/image/eb00ead-bb56b45-05e52f8-2398d3a/item.png"
},
"backpack":{
},
"obtained_type":"vbucks",
"ratings":{
"avgStars":4.82,
"totalPoints":164,
"numberVotes":34
}
}
},
{
"itemId":"a784814-93b4ea3-3c26b6f-631fac7",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"500",
"occurrences":1,
"isNew":true
}
}
]
}
I need help with JSON path and if there is something wrong with my code
Try this:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String credentials = "username" + ":" + "password";
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic " + base64EncodedCredentials);
return headers;
}

return data from method (JSON Array)

I have one method with this url:
String url = "http://brunos.000webhostapp.com/teste/obter_id.php?descricao=" + value;
And i want to return the result of this method.
i have tried the VolleyCallback callback but i cant send the value to the method
package com.example.fabio.domoticaa;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Divi_Dispo extends AppCompatActivity {
String x;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_divi__dispo);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String[] count = new String[1];
final String[] id = new String[1];
Intent intent = getIntent();
String value = intent.getStringExtra("divisao");
final EditText nomediv = (EditText) findViewById(R.id.editText4);
Count(value);
nomediv.setText(x);//want set th result of Count(value)
}
public void Count(String value) {
final String[] count = new String[1];
// Send data
try {
RequestQueue queue = Volley.newRequestQueue(Divi_Dispo.this);
String url = "http://brunos.000webhostapp.com/teste/obter_id.php?descricao=" + value ;
JsonArrayRequest jsonRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jObj = new JSONObject(String.valueOf(response.get(0)));
count[0] = jObj.getString("COUNT(id)");//want return this valor
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonRequest);
} catch (Exception ex) {
} finally {
}
}
public interface VolleyCallback {
void onSuccess(String result);
}
}

Android - Post image within json object to server using volley library

I want post json object included image to my server using Volley Library it post empty fields to server , image file posted successfully
I should post Json in this formate
{ "user_id":"value" , "post_title":"value","Specialty":"value","post_detail":"value", "uploaded_file","file" }
here is my android code
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.imaadv.leaynik.Util.AppConstants;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Created by NT on 10/26/15.
*/
public class PhotoMultipartRequest<T> extends Request<T> {
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private Response.Listener<T> mListener;
private File mImageFile;
protected Map<String, String> headers;
private JSONObject params;
private String file_name;
private boolean hasFile;
public PhotoMultipartRequest(JSONObject params, String url, Response.ErrorListener errorListener, Response.Listener<T> listener, String file_name, File imageFile, boolean hasFile) {
super(Method.POST, url, errorListener);
mListener = listener;
mImageFile = imageFile;
this.params = params;
this.file_name = file_name;
this.hasFile = hasFile;
BuildMultiPartEntity();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<>();
}
headers.put("accept", "application/json");
headers.put("Content-type","application/json");
return headers;
}
private void BuildMultiPartEntity() {
// Set keys = params.keySet();
// for (Iterator i = keys.iterator(); i.hasNext(); ) {
// String key = (String) i.next();
// try {
//
// }catch (Exception e){
// e.printStackTrace();
// }
//
// }
StringBody userId = new StringBody(params.get(AppConstants.USER_ID) ,ContentType.APPLICATION_JSON);
StringBody postDetail = new StringBody(params.get(AppConstants.POST_DETAIL) ,ContentType.APPLICATION_JSON);
StringBody postTitle = new StringBody(params.get(AppConstants.POST_TITLE) ,ContentType.APPLICATION_JSON);
StringBody Speciality = new StringBody(params.get(AppConstants.SPECIALTY) ,ContentType.APPLICATION_JSON);
mBuilder.addPart(AppConstants.USER_ID ,userId );
mBuilder.addPart(AppConstants.POST_DETAIL ,postDetail );
mBuilder.addPart(AppConstants.POST_TITLE ,postTitle );
mBuilder.addPart(AppConstants.SPECIALTY ,Speciality );
mBuilder.addTextBody(AppConstants.DATA, params.toString());
if (hasFile) {
mBuilder.addBinaryBody(file_name, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
}
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
#Override
public String getBodyContentType() {
String contentTypeHeader = mBuilder.build().getContentType().getValue();
return contentTypeHeader;
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}
return bos.toByteArray();
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
T result = null;
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
Log.i("Error1", volleyError.getMessage());
return super.parseNetworkError(volleyError);
}
#Override
public void deliverError(VolleyError error) {
Log.i("Error2", error.getMessage());
super.deliverError(error);
}
}
Could any one guide me what is wrong in my code
You can see your answer on follow this 3 link.....
Click here
http://www.survivingwithandroid.com/2013/05/android-http-downlod-upload-multipart.html
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server/
Best Luck..

Categories