Why isn't Android Volley request working? - java

I simply trying to get JSON data from url (https://krokapp.by/api/rest/tags/?format=json):
RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRequestQueue = Volley.newRequestQueue(this);
String url = "https://krokapp.by/api/rest/tags/?format=json";
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, response -> {
Log.d("krok_data", response.toString());
}, error -> {
Log.d("krok_data", "Error");
error.printStackTrace();
});
mRequestQueue.add(request);
}
However, when I try this with different JSON api, for example:
https://samples.openweathermap.org/data/2.5/weather?id=2172797&appid=b6907d289e10d714a6e88b30761fae22
everything works fine. Is there something wrong with the API I'm trying to get data from?

Since the ressource you are calling returns a JSON array, simply change the volley request type from JsonObectRequest to JsonArrayRequest.
Should look like this then:
RequestQueue mRequestQueue = Volley.newRequestQueue(this);
String url = "https://krokapp.by/api/rest/tags/?format=json";
final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
response -> Log.d("krok_data", response.toString()),
error -> {
Log.d("krok_data", "Error");
error.printStackTrace();
});
mRequestQueue.add(request);

Related

Can not store response data public to access outside in android

I can get very strange issue in my project. I can get the response from volley over the internet and after reposne I want to store it in sharedpref, but issue is that when I get the response and showed up within resonse function then it shows correct data, but when I used to save it outside the response function sharedpref it gives 0. I declared the string public and top of the class but got no luck. Am very strange whats the issue.
SharedPreferences savelogin = getSharedPreferences("login",MODE_PRIVATE);
final SharedPreferences.Editor slogin = savelogin.edit();
String url = "https://datafinderdatabase.xyz/dfapi/FetchId.php?username="+fuser;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
userid = response.toString();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toasty.error(getApplicationContext(), "Network Issue", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
slogin.putString("username",fuser);
slogin.putString("password",fpass);
slogin.putString("userid",userid);
slogin.commit();
This is because your call to the API is asynchronous. Therefore, the result you get back may be processed after that function finishes. To solve this, you can take a Interface approach, explained here for a similar issue:
wait until firebase retrieves data
OR: you need to save the variable to the shared preferences inside the onResponse function.
These:
slogin.putString("username",fuser);
slogin.putString("password",fpass);
slogin.putString("userid",userid);
slogin.commit();
must be inside this:
#Override
public void onResponse(String response) {
userid = response.toString();
//here
}

How to make a GET request with parameters to a JSON in Java using Volley?

I'm doing a school project where i need to parse a JSON and make queries to get specific values. The API in question is this one http://data.nba.net/10s/prod/v2/2018/teams.json and I only want the teams of the "standard" array.
For example I want only the teams which are NBA Franchise, I tried the following:
private void loadTeams() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application);
String franchise = preferences.getString("isnbafranchise", "true");
Uri baseUri = Uri.parse(NBA_REQUEST_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendQueryParameter("isnbafranchise", franchise);
RequestQueue requestQueue = Volley.newRequestQueue(application);
StringRequest request = new StringRequest(Request.Method.GET, uriBuilder.toString(), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
List<NBATeam> teamList = QueryUtils.extractFeatureFromJson(response);
teams.setValue(teamList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error Volley", error.toString());
}
});
requestQueue.add(request);
}
But it is the same as without the appendQueryParameter, returns all the taams. I've also tried doing a GET request from Mozilla (http://data.nba.net/10s/prod/v2/2018/teams.json?isnbafranchise=true) and the same result, which makes me think that I'm not doing the query correctly.

Send a POST request in android with a String body

Alright, I've looked all over the website for a possible solution to send a POST request using android but I don't seem to understand the usage of Volley here or the method which was starting an async thread to make the request.
private RequestQueue signupRequestQ = Volley.newRequestQueue(this);
#Override
public void onClick(View view) {
String postUrl = "https://mypost.url";
signupRequestQ.start();
switch (view.getId()) {
case R.id.signupBtn:
if (((EditText) findViewById(R.id.passwordSignup)).getText().toString().length() < 6) {
Dialog.showInvalidInputFieldsDialog(this,"Password must be longer than 5 characters").show();
} else {
try {
StringRequest strRequest = new StringRequest(Request.Method.POST, postUrl,
response -> {
System.out.println(response);
},
error -> {
System.out.println("What the funk");
}) {
#Override
protected Map<String, String> getParams() {
LinkedHashMap<String, String> postForm = new LinkedHashMap<String, String>();
postForm.put("test", "var");
return postForm;
}
};
signupRequestQ.add(strRequest);
} catch (ParseException e) {
System.out.println("Something went wrong");
}
}
}
For some reason, this code causes my app to crash with a java.lang.RuntimeException and java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getCacheDir()' on a null object reference.
However, I should not be encountering the NullPointerException as the Volley RequestQueue javadoc clearly stated that I only had to provide a context for the newRequestQueue method which I did.
Could anyone please help with my issue? Thank you!
It's because you instanciate your RequestQueue with a null Context at the top of your Activity :
private RequestQueue signupRequestQ = Volley.newRequestQueue(this); // "this" is null here
Try to create your RequestQueue in the onCreate() method of your Activity like :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
signupRequestQ = Volley.newRequestQueue(this);
}

Android: Error connecting Android app with Database using php and json

My android app needs to send a string, and based on that, needs to get a response from the database.
I have a php that receives the string from the app, queries the database, and returns the response using echo json_encode($response_array); which works fine on the browser and echoes in a json object format.
However, In the app, I am using Volley. The php array $response_array above sends multiple strings which i need to display in the app textview.
I have set up volley in the gradle dependencies.
However, on running the app from my phone (which is connected on my laptop hotspot), the error i get is "null". This is the sample code from the app.
TextView o,t;
private RequestQueue requestQueue;
private static final String URL = "http://172.25.33.189/fadapp/mirror.php";
private StringRequest request;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
o=(TextView)findViewById(R.id.tryOne);
t=(TextView)findViewById(R.id.tryTwo);
requestQueue = Volley.newRequestQueue(this);
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonobject = new JSONObject(response);
if (jsonobject.names().get(0).equals("name")) {
o.setText(jsonobject.getString("name"));
if(jsonobject.getString("stat").equals("1")) {
t.setText(R.string.inText);
t.setTextColor(Color.parseColor("#00FF00"));
} else {
t.setText(R.string.outText);
t.setTextColor(Color.parseColor("#FF0000"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, ""+error.getMessage(), Toast.LENGTH_SHORT).show();;
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("speid", "database query string here");
return hashMap;
}
};
requestQueue.add(request);
Have you grant the intenet access to the app with ?
If you are hosting from your laptop you may need to open the port 80, to be sure that the problem isn't yor Volley set-up try to query for example google and print the response that should be a 200 http code

How to receive data from web asynchronous and use the result string in the next line of code?

I want to get some JSON code from my API. I wish to do something like this in the OnCreate:
try
{
String jsonstr = getSomeThingAndPauseAndroid("http://someplace.com/api/xyz");
if (!jsonstr.isEmpty()) JSONObject jsonobj = new JSONObject(jsonstr);
}
catch { // handle error }
But when it happens, Android just go doing stuff and don't wait for the request to complete and response and I get nothing on jsonstr.
Is there some way to do that not needing a lot of new class files?
The correct way to do this is to make the request asynchronously and trigger a method on response. This is an example using Google's Volley:
//Start volley:
RequestQueue queue = Volley.newRequestQueue(this); // this = context
final String url = "http://someplace.com/api/xyz"";
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
//This is where you setup your UI
//Remember to dismiss the ProgressDialog
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
//Remember to dismiss the ProgressDialog
Log.d("Error.Response", response);
}
}
);
// add it to the RequestQueue
//Here you should add a ProgressDialog so the user knows to wait
queue.add(getRequest);

Categories

Resources