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
}
Related
I wrote android app to read json using volley.
If i use example URL from internet - i don't have problem, the data is read. But when i try to read data from local host, I am getting an error.
The same data i can see in web browser in my emulator.
my URL: "http://10.0.2.2/volley_sample/get_data.php"
my code:
private void sendGetRequest() {
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url = "http://10.0.2.2/volley_sample/get_data.php"; //it doesn't work
//String url ="https://reqres.in/api/users/2"; //it works
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 10 characters of the response string.
get_response_text.setText("Response is: " + response.substring(0, 10));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
get_response_text.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
adres "http://10.0.2.2/volley_sample/get_data.php" works in web browser in my emulator.
I tried also "http://192.168....", "127.0.0.1....", "localhost/volley_sample...." etc., and neither works.
adres "https://reqres.in/api/users/2" (example from internet) work without problem.
ofc. i added "<uses-permission android:name="android.permission.INTERNET"/>"
I have no idea what I am doing wrong :(
I am not sure what I am doing wrong. I am very new to this and just jumped straight into trying to make API calls. I am trying to retrieve information from rapidAPI for a simple project I am working on to view prices of stocks and so on. I am using the volley package from Android Studio to make my APIcalls to retrieve JSON and trying to put that into a textView. The way I imagine this to work is that I press a button and then once that is clicked, it runs the code to get the information and then shows the response in the textView. however, when the button is clicked, nothing happens. no error or response of any sort.
private TextView mTextViewResult;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewResult= findViewById(R.id.text_view_result);
Button buttonParse= findViewById(R.id.button_parse);
mQueue= Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
jsonParse();
}
});
}
private void jsonParse(){
String url="https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/get-quotes?region=CA&lang=en&symbols=VEQT.TO";
JsonObjectRequest request= new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray= response.getJSONArray("result");
JSONObject result=jsonArray.getJSONObject(0);
int marketPrice= result.getInt("regularMarketPrice");
mTextViewResult.setText(String.valueOf(marketPrice));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextViewResult.setText("" +error.toString());
}
}){
#Override
public Map<String,String> getHeaders() throws AuthFailureError{
Map<String,String> params= new HashMap<>();
params.put("x-rapidapi-host", "apidojo-yahoo-finance-v1.p.rapidapi.com");
params.put("x-rapidapi-key", "APIKEY");
return params;
}
};
mQueue.add(request);
}
}
From what you've posted are you sure your x-rapidapi-key is APIKEY. Pretty sure that's the primary reason of your issue. Only after you put a valid API key in your request header, will your API call return a proper expected response.
You can read how to generate the rapidapi key from their official docs here
Currently the response you receive on api call using the wrong apikey is something like this:
{
"message": "Key doesn't exists"
}
Now in your java code you are looking for a JSONArray based on the key "result", while the response currently only has "message" being returned. That's the reason nothing happens, you can try finding the value in response for message and get the error messages if you wish. Generate a valid rapidapi key and try again, Good luck!
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.
I create an application for Android, which saves GPS coordinates and displays them with addresses.
I have a function:
public String getAddressByGpsCoordinates(String latlan) {
requestQueue = Volley.newRequestQueue(this);
String url= "http://maps.googleapis.com/maps/api/geocode/json?latlng="+latlan+"&sensor=true&key=(I have a correct key :))";
JsonObjectRequest request = new JsonObjectRequest(url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
address = response.getJSONArray("results").getJSONObject(0).getString("formatted_address");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
return address;
}
It is returned NULL all the time.
Can You help me what is wrong with my code?
Using JsonObjectRequest with a RequestQueue is an asynchronous mechanism--the work is performed in the background and the onResponse callback is called whenever the response is ready.
Because of this, it is very likely that you return from your method before onResponse gets called, and since address isn't set beforehand (that you've shown, anyway), its value will be null.
If you want to block your thread until the request has completed and set the value of address, you should use a RequestFuture: Can I do a synchronous request with volley?
My java skills are quite good, still I fail to grasp what happens here.
I am programming an android app and right now I am programming a class which uses the Google Volley API in order to interact with a web-server.
The problem is that I want the class to be called like this:
Server_interaction s_i = new Server_interaction(getApplication);
String text = s_i.post_request();
Text should now contain the returned post request, in my case the string "Hello from server". Instead, it turns out to be null. This happens because the post_request method seems to return before having executed the post_request.
Here is the Server_interaction class:
public class Server_interaction
{
String server_url = "someipadress/greeting.php"; //this address is correct, but I want to hide it for you guys :)
String response_string;
Context myContext;
RequestQueue requestQueue;
public static final String TAG = Server_interaction.class.getSimpleName();
/* Here we add a constructor that takes in context. We need a context for volley requestqueue, and this is an elegant way*/
public Server_interaction(Context context)
{
myContext = context;
requestQueue = Volley.newRequestQueue(myContext);
}
public String post_request()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
response_string = response;
requestQueue.stop();
Log.i(TAG, "the response is: "+ response_string);
}
}
, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
response_string = "Something went wrong";
//error.printstacktrace()
requestQueue.stop();
}
}
); //stringrequest parameter end
//add request to requestqueue
requestQueue.add(stringRequest);
Log.i(TAG, "the response again:: "+ response_string);
return response_string;
}
}
When being executed, logcat shows this:
01-22 19:00:44.878 2954-2954/com.example.koenraad.Exigentia I/Server_interaction: the response again:: null
01-22 19:00:44.926 2954-2954/com.example.koenraad.Exigentia I/Server_interaction: the response is: hello from server
So this means that the string is null when being returned, then afterwards it is set. How can this be fixed?
Thanks in advance!
Your code is asynchrounous.
The StringRequest object created in method post_request() will be used by the framework after the method returns.