Cannot connect to the API using Volley - android

I am trying to get a JSON request from an API using volley but it didn't seem to work. I did try another dummy API and it works but not for this one. The one I am currently using has headers with key and value. Also, on checking the API on postman, I saw that the JSON format begins with '[' so I am not sure what to put for the JSONObject. Also, I am not sure if I added the header right. I am very new to android and would definitely appreciate it if someone could help me out.
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "http://apidev.travelhouse.world/api/v1/packages";
JsonArrayRequest request = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject hit = response.getJSONObject(i);
String creatorName = hit.getString("holiday_name");
String imageUrl = hit.getString("primary_image");
String likeCount = hit.getString("package_price");
mExampleList.add(new ExampleItem(imageUrl, creatorName, likeCount));
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(MainActivity.this, "Failed to connect", Toast.LENGTH_LONG).show();
}
}) {
/** Passing some request headers* */
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("X-API-KEY", "CODEX#123");
return headers;
}
};
mRequestQueue.add(request);
}

Replace your JsonObjectRequest with:
JsonArrayRequest request = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {....}
}
}

Related

Volley is not pulling Json data from my URL

people so I have a valid URL with JSON data in it, I pull the data with volley but it's not working for some reason, when I change the URL it works. But I need to use this URL with this data in my project. I think the structure of the URL is the problem, but I don't know how to fix it, Please help. Thank you!
The URL I am using is https://zlatnakopacka.mk/api/TopOfferPreview_feed?source=zk
public class TestOne extends AppCompatActivity {
String url = "https://zlatnakopacka.mk/api/TopOfferPreview_feed?source=zk";
RecyclerView recyclerView;
PonudiAdapter adaptor;
ArrayList<Ponudi> ponudis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_one);
switchSve = findViewById(R.id.switch1);
recyclerView = findViewById(R.id.testRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adaptor = new PonudiAdapter(getApplicationContext());
recyclerView.setAdapter(adaptor);
ponudis = new ArrayList<>();
getData("1");
switchSve.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true) {
getData("sve");
} else {
getData("1");
}
}
});
private void getData(final String Sport) {
// final ProgressDialog progressDialog = new ProgressDialog(this);
// progressDialog.setMessage("Се вчитува...");
// progressDialog.show();
ponudis.clear();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Ponudi ponudi = new Ponudi();
ponudi.setSh_sport_id(jsonObject.getString("sh_sport_id"));
ponudi.setTim1(jsonObject.getString("tim1"));
ponudi.setTim2(jsonObject.getString("tim2"));
ponudi.setLiga_header(jsonObject.getString("liga_header"));
ponudi.setDatum_vreme(jsonObject.getString("datum_vreme"));
ponudi.setKh1(jsonObject.getString("kh1"));
ponudi.setKhx(jsonObject.getString("khx"));
ponudi.setKh2(jsonObject.getString("kh2"));
ponudi.setKod(jsonObject.getString("broj"));
if (ponudi.getSh_sport_id().equals(Sport)) {
ponudis.add(ponudi);
} if (Sport.equals("sve")) {
ponudis.add(ponudi);
}
}
} catch (JSONException e) {
Toast.makeText(TestOne.this, "Json is not valid", Toast.LENGTH_SHORT).show();
}
adaptor.setData(ponudis);
adaptor.notifyDataSetChanged();
// progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(TestOne.this, "Error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
}
In response you are getting below error.
"javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found."
I found some answers here is reference that will help you.
Trusting all certificates using HttpClient over HTTPS
Replace getData() Method
Write This method -
private void getData() {
// final ProgressDialog progressDialog = new ProgressDialog(this);
// progressDialog.setMessage("Се вчитува...");
// progressDialog.show();
ponudis.clear();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Ponudi ponudi = new Ponudi();
ponudi.setSh_sport_id(jsonObject.getString("sh_sport_id"));
ponudi.setTim1(jsonObject.getString("tim1"));
ponudi.setTim2(jsonObject.getString("tim2"));
ponudi.setLiga_header(jsonObject.getString("liga_header"));
ponudi.setDatum_vreme(jsonObject.getString("datum_vreme"));
ponudi.setKh1(jsonObject.getString("kh1"));
ponudi.setKhx(jsonObject.getString("khx"));
ponudi.setKh2(jsonObject.getString("kh2"));
ponudi.setKod(jsonObject.getString("broj"));
if (ponudi.getSh_sport_id().equals("1")) {
ponudis.add(ponudi);
} else if(ponudi.getSh_sport_id().equals("sve")) {
ponudis.add(ponudi);
}
}
} catch (JSONException e) {
Toast.makeText(TestOne.this, "Json is not valid", Toast.LENGTH_SHORT).show();
}
adaptor.setData(ponudis);
adaptor.notifyDataSetChanged();
// progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(TestOne.this, "Error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}

Can't figure out how the header authentication works when parsing Json

I am trying to get some data from an online API via Json, but can't figure out how the authentication works as I have never done this before.
It is not a user-password pair, but based on a unique key.
The Curl looks like this:
curl -X GET --header 'Accept: application/json' --header "authorization: Bearer [unique key]" 'url to Json Object'
Haven't tried much else as I am new to implementing json in java. The list does not load and am getting the following in logcat:
E/Volley: [31231] BasicNetwork.performRequest: Unexpected response code 403 for URL
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private PlayerListAdapter mAdapter;
private ArrayList<PlayerListItem> mPlayerList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.playerList);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mPlayerList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJson();
}
private void parseJson() {
String url = getString(R.string.url_to_members);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject players = jsonArray.getJSONObject(i);
String playerName = players.getString("name");
String playerRole = players.getString("role");
int playerTrophies = players.getInt("trophies");
int playerDonations = players.getInt("donations");
mPlayerList.add(new PlayerListItem(playerName, playerRole, playerTrophies, playerDonations));
}
mAdapter = new PlayerListAdapter(MainActivity.this, mPlayerList);
mRecyclerView.setAdapter(mAdapter);
} 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> headers = new HashMap<>();
String apiToken = "Bearer" + Base64.encodeToString(getString(R.string.api_key).getBytes(), Base64.NO_WRAP);
headers.put("Accept:", "application/json");
headers.put("authorization:", "Bearer " + apiToken);
return headers;
}
};
mRequestQueue.add(request);
}
}

Append json array request with a sessionaid

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);
}
}

Sending a variable to mysql

I want to send the Id_student variable to MySQL but face to the following exception:
org.json.JSONException: Value 0 of type java.lang.Integer cannot be
converted to JSONArray
I have attached my code as following:
int id_student=123;
String GET_JSON_DATA_HTTP_URL ="http://pharamjo.96.lt/Select/ImageJsonData.php?";
String JSON_IMAGE_TITLE_NAME = "Id_student";
String JSON_IMAGE_URL = "Url";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
//show = (TextView)findViewById(R.id.show);
/*Intent intent = getIntent();
id_student = intent.getStringExtra("student");
//show.setText(id_student);*/
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL + id_student ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Select", "onResponse");
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("********Select********",error.getMessage());
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
Would you please guide me to solve my problem?

int org.json.JSONArray.length() on a null object reference

I'm using volley library to connect to server and I have a Transaction class and a Server class with this codes:
Trans:
public class Trans extends Server {
public Object suggest(Context context) {
return connect("xxxxxxx", Request.Method.GET);
}
}
Server:
public Object connect(String url, int method) {
final Object[] object = {null};
StringRequest postRequest;
postRequest = new StringRequest(method, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
object[0] = response;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
int socketTimeout = 20000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(postRequest);
return object[0];
}
But when I'm trying to get JSONArray with this:
#Override
protected void onResume() {
ArrayList<Suggests> arrayList = new ArrayList<>();
JSONArray jsonArray = (JSONArray) trans.suggest(MainActivity.this);
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject item = (JSONObject) jsonArray.get(i);
Suggests suggests = new Suggests();
suggests.title = item.getString("title");
suggests.type = item.getString("type");
arrayList.add(suggests);
} catch (JSONException e) {
e.printStackTrace();
}
}
super.onResume();
}
Application force closed and I have this error in logcat:
java.lang.RuntimeException: Unable to resume activity {ir.aftabeshafa.shafadoc/ir.aftabeshafa.shafadoc.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
What's the problem and how can I fix it?
Going off the suggestions in the comments,
Step 1 Define an interface that will pass-along the result you want. The <T> is a generic type, so you can return whatever data you want. You'll see that in Step 2.
public interface AsyncResponse<T> {
void onResponse(T response);
}
Step 2 Update the Server and Trans classes to take this as a parameter
public class Server {
public void connect(String url, int method, final AsyncResponse<String> asyncResponse) {
StringRequest request = new StringRequest(method, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (asyncResponse != null) {
asyncResponse.onResponse(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VolleyError", error.getMessage());
Log.e("VolleyError", new String(error.networkResponse.data));
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
int socketTimeout = 20000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(request);
}
}
Side question: Do you really need the Context? It isn't used...
public class Trans extends Server {
public void suggest(Context context, AsyncResponse<String> asyncResponse) {
connect("xxxxxxxx", Request.Method.GET, asyncResponse);
}
}
Step 3 Use your method like so to get a result in a callback. This was tested against the url http://jsonplaceholder.typicode.com/users, which returns a JSONArray of 10 User objects.
The ArrayAdapter was added for a full example since it didn't appear the ArrayList in the question was useful for anything.
public class MainActivity extends AppCompatActivity {
private ArrayList<User> arrayList;
private Trans trans;
private ArrayAdapter<User> adapter;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
trans = new Trans();
arrayList = new ArrayList<User>();
adapter = new ArrayAdapter<User>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(adapter);
}
#Override
protected void onResume() {
trans.suggest(MainActivity.this, new AsyncResponse<String>() {
#Override
public void onResponse(String response) {
arrayList.clear(); // prevent duplicate data
try {
// The URL that was tested returns a JSONArray
// Change to JSONObject, if necessary
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = (JSONObject) jsonArray.get(i);
User user = new User();
user.username = item.getString("name");
user.email = item.getString("email");
arrayList.add(user);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Notify since the arrayList has changed the adapter
adapter.notifyDataSetChanged();
}
});
super.onResume();
}
}

Categories

Resources