I know this is the answer, but I couldn't add it to my code.
How can I return value from function onResponse of Volley?
<------
like here I created interface.
I did it all.
I just don't know how to convert this my code to it, and how to use the return value in other activities.
public void priceDate(Context contex, final String coin) {
String URL = "https://min-api.cryptocompare.com/data/top/exchanges/full?fsym=BTC&tsym=USD&api_key=" + apiKey;
//String a =
//json_Parser = new JSONParser(_usd);
RequestQueue requestQueue = Volley.newRequestQueue(contex);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d("Main",response.toString());}
DecimalFormat formatter = new DecimalFormat("#,###,###");
String yourFormattedString = formatter.format(100000);
try {
JSONObject Data = response.getJSONObject("Data");
JSONObject AggregatedData = Data.getJSONObject("AggregatedData");
try {
String Price = AggregatedData.getString("PRICE");
String formatPrice = formatter.format(Math.round(Float.valueOf(Price)));
_price.setText("Price :" + formatPrice);
} catch (Error e) {
_price.setText("Data Not Avvaliable");
}
try {
String Open = AggregatedData.getString("OPENDAY");
String formatOpen = formatter.format(Math.round(Float.valueOf(Open)));
_open.setText("Open :" + formatOpen);
} catch (Error e) {
_open.setText("Data Not Avvaliable");
}
try {
String Low = AggregatedData.getString("LOWDAY");
String formatLow = formatter.format(Math.round(Float.valueOf(Low)));
_low.setText("Low :" + formatLow);
} catch (Error e) {
_low.setText("Data Not Avvaliable");
}
try {
String High = AggregatedData.getString("HIGHDAY");
String formatHigh = formatter.format(Math.round(Float.valueOf(High)));
_high.setText("High :" + formatHigh);
} catch (Error e) {
_high.setText("Data Not Avvaliable");
}
try {
String Volume = AggregatedData.getString("VOLUMEDAY");
String formatVol = formatter.format(Math.round(Float.valueOf(Volume)));
_volume.setText("Volume :" + formatVol);
} catch (Error e) {
_volume.setText("Data Not Avvaliable");
}
try {
String LastUpdate = AggregatedData.getString("LASTUPDATE");
String convert = unix_time(Long.parseLong(LastUpdate));
_lastUpdate.setText("Last Update :" + LastUpdate);
} catch (Error e) {
_lastUpdate.setText("Data Not Avvaliable");
}
try {
String TradeId = AggregatedData.getString("LASTTRADEID");
_tradeId.setText("Trade Id :" + String.valueOf(Math.round(Float.parseFloat(TradeId))));
} catch (Error e) {
_tradeId.setText("Data Not Avvaliable");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
You can achieve this by using interface. Follow the below steps,
First create Interface in your application like,
public interface AsyncTaskListener {
void onRequestCompleted(JSONObject result, Integer statusCode);
}
And implement this interface in your activity where you want make request, Assume object of your volley class is objVolley, then your request will like below
public class YourActivity extends AppCompatActivity implements AsyncTaskListener {
public void priceDate(YourActivity.this, coin, YourActivity.this);
}
Then Your volley class and method like this,
public class PostDataHelper {
public void priceDate(Context contex, final String coin, final AsyncTaskListener asyncTaskListener) {
#Override
public void onResponse(JSONObject response) {
asyncTaskListener.onRequestCompleted(response, 200);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
asyncTaskListener.onRequestCompleted(response, 200);
}
});
}
}
Hope this will help you, Happy coding.
Your volley code is embedded into your activity code so there isn't much advantage to creating a interface.
You need to create a separate class for handling volley requests.
public class VolleyRequest {
VolleyCallback mResultCallback;
RequestQueue mRequestQueue;
public VolleyRequest(VolleyCallback resultCallback, Context context){
mResultCallback = resultCallback;
mRequestQueue = Volley.newRequestQueue(context);
}
public void cancelRequests(String TAG){
if(mRequestQueue != null){
mRequestQueue.cancelAll(TAG);
}
}
public void volleyGetRequest(String url, final String TAG) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (mResultCallback != null) {
mResultCallback.onSuccess(response, TAG);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (mResultCallback != null) {
mResultCallback.onError(error, TAG);
}
}
});
jsonObjectRequest.setTag(TAG);
mRequestQueue.add(jsonObjectRequest);
}
}
Then create a interface class to handle the callbacks
public interface VolleyCallback {
void onSuccess(JSONObject response, String tag);
void onError(VolleyError error, String tag);
}
Then in your activity class
private void initvolley(){
VolleyCallback volleyCallback = new VolleyCallback() {
#Override
public void onSuccess(JSONObject response, String tag) {
switch (tag){
//add response handling code here
}
}
#Override
public void onError(VolleyError error, String tag) {
//handle error response here
}
};
VolleyRequest volleyRequest = new VolleyRequest(volleyCallback, this);
String URL = "https://min-api.cryptocompare.com/data/top/exchanges/full?fsym=BTC&tsym=USD&api_key=" + apiKey;
volleyRequest.volleyGetRequest(URL, request_tag/*Request tag incase you have multiple requests in same activity*/);
}
Related
I want to make my own library for getting the weather. I made the same in MainActivity and it works but when a put the same method in an another Class java i get error with Tosts and getApplicationContext methods. How can i fix it
public class WeatherClass {
public static void getCurrentWeather(String location) {
final String[] urlCityGetTemperature = {"https://www.metaweather.com/api/location/"};
String urlCityGetId = "https://www.metaweather.com/api/location/search/?query=";
final String[] finishUrl = new String[1];
String tempUrl = "";
String city = "";
city = location;
if(city.equals("")) {
//тут пишем код, если ползователь ничего не ввел в поле и нажал на кнопку
}
else {
tempUrl = urlCityGetId + city;
String finalCity = city;
StringRequest stringRequest = new StringRequest(Request.Method.GET, tempUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
String output = "";
try {
JSONArray jsonResponce = new JSONArray(response);
if(response.equals("[]")) {
//уведомление о неккоректном вводе названия города
}
JSONObject jsonObjectZeroIndex = jsonResponce.getJSONObject(0);
int woeid = jsonObjectZeroIndex.getInt("woeid");
//tvRes.setText(output);
finishUrl[0] = urlCityGetTemperature[0] + output;
//тут мы будем получат температуру по id города.
StringRequest stringRequestGetTeperatureWithId = new StringRequest(Request.Method.GET, finishUrl[0], new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("finalLink", response);
String outputTemp = "";
String outPutWeather;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("consolidated_weather");
JSONObject jsonObectFromArray = jsonArray.getJSONObject(0);
int woeid = jsonObectFromArray.getInt("the_temp");
outputTemp = String.valueOf(woeid);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext);
requestQueue.add(stringRequestGetTeperatureWithId);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext);
requestQueue.add(stringRequest);
}
}
}
getApplicationContext and Toasts doesn't work.
You can pass second parameter Context to getCurrentWeather, and then pass that context to The Toast.
Here is getCurrentWeather Method inside WeatherClass Like This,
public class WeatherClass {
public static void getCurrentWeather(String location,Context context){
// Here is your fetch whether code
// Your Toast like this
Toast.makeText(context,"Your Message", Toast.LENGTH_SHORT).show();
}
}
When you call this method from MainActivity, call Method like this,
getCurrentWeather(location,getApplicationContext())
I"m populating the listview from online using JSON. It works great...But I wanted to implement method of SwipeRefresh layout such that old data will be replace with new one in every Swipe user make.
Instead of clearing old data with new one, Everytime on SwipeRefresh new data is added at the bottom of old data.
I also set notifysetAdapter; but it doesn't seems to work.
Here is my code
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
mExampleList.clear();
mExampleAdapter.notifyDataSetChanged();
parseJSON();
}
}
);
}
}
private void parseJSON() {
String url = getIntent().getStringExtra(EXTRA_URL);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
myProgressBar.setVisibility(View.GONE);
try {
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String videoTitle = hit.getString("title");
String link = hit.getString("link");
// String notes = hit.getString("notes");
// String question = hit.getString("question");
// String imageUrl = hit.getString("webformatURL");
// int likeCount = hit.getInt("likes");
mExampleList.add(new ExampleItem(videoTitle,link));
mExampleAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
mSwipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
mRequestQueue.add(request);
}
I need help to solve this.
Use setOnRefreshListener
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
parseJSON();
// just on refresh call parseJSON method
}
});
Clear data in parseJSON method before add new data, and set notifyDataSetChanged out for loop.
private void parseJSON() {
String url = getIntent().getStringExtra(EXTRA_URL);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
myProgressBar.setVisibility(View.GONE);
try {
mExampleList.clear();
JSONArray jsonArray = response.getJSONArray("hits");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String videoTitle = hit.getString("title");
String link = hit.getString("link");
// String notes = hit.getString("notes");
// String question = hit.getString("question");
// String imageUrl = hit.getString("webformatURL");
// int likeCount = hit.getInt("likes");
mExampleList.add(new ExampleItem(videoTitle,link));
}
mExampleAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
mSwipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
mSwipeRefreshLayout.setRefreshing(false);
}
});
mRequestQueue.add(request);
}
I'm making app in Android Studio and I can't set value of fields in anonymous class.
I know that "receivedNumber" is always diffrent than '-1' and value "isExist" have to be 'true', but in log is 'false'.
The same things happens with int field - always return '0'.
What should I do to set properly fields in anonymous class and use them in my main class.
private void isNumberExist()
{
String URL = "some url...";
final boolean[] isExist = new boolean[1];
objectRequest = new JsonObjectRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
int receivedNumber = response.getInt("id");
if (receivedNumber == -1) {
isExist[0] = false;
} else {
isExist[0] = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error
}
}
);
Log.e("isExist","value"+ isExist[0]);
requestQueue.add(objectRequest);
requestQueue.cancelAll(this);
}
It will always be false because you are logging isExist[0] before the http(s) request is executed
Please try this
private void isNumberExist()
{
String URL = "some url...";
final boolean[] isExist = new boolean[1];
objectRequest = new JsonObjectRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
int receivedNumber = response.getInt("id");
if (receivedNumber == -1) {
isExist[0] = false;
} else {
isExist[0] = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
// New log location
Log.e("isExist","value"+ isExist[0]);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error
}
}
);
requestQueue.add(objectRequest);
requestQueue.cancelAll(this);
}
I am working on a project and below my code basically takes an array of objects and sets the Id to each object, However, when I click on my objects I would like to get that Id. I tried a local variable and I could only get the Id of the last object, how do I do this? I would like to get the value of String Answerid = currentQuestions.getString("id"); into my OnDown clicklistener.
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_ANSWER, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs = parseJSONResponseQuestion(response);
mAdapterQuestion.setBloglist(listblogs);
System.out.println(response);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
});
mRequestQueue.add(request);
}
String globalVar = " ";
private ArrayList<Blogs> parseJSONResponseQuestion(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String questionId = currentQuestions.getString("questionId");
String votes = currentQuestions.getString("votes");
String Answerid = currentQuestions.getString("id");
System.out.println(response.length() + "length");
data.append(text + Answerid + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setMtext(text);
blogs.setVotes(votes);
blogs.setId(Answerid);
System.out.print(Answerid);
listblogs.add(blogs);
}
System.out.println(data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
public void OnDown(View view) {
System.out.println("VOTED Down");
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_UP = "someURL";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_UP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response + "reponse");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println("************Answer" + error + "error");
}
});
mrequestQueue.add(PostVoteUp);
System.out.println("VOTED DOWN");
}
}
Your click listener OnDown(View view) gets a view that was clicked. That's the only way you can identify what was clicked.
You should use View.getTag() to get the id:
Object obj = view.getTag();
The question is where can you add this code to set it:
View view = ...; // new View()?
view.setTag(object);
I'm trying to submit a simple post request using the facebook SDK.
Here's the code:
public void ShareLinkOnFacebook()
{
Facebook mFacebook = ((GlobalVars)getApplicationContext()).facebook;
AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook);
Bundle params = new Bundle();
params.putString("message", place.name );
params.putString("link", "http://www.facebook.com");
mAsyncFbRunner.request("me/feed", params, "POST", new RequestListener());
}
but I have compilation error saying that RequestListener cannot be Resolved to a type. what do I have to do in order to make it work?
Please check this listener.
public void postOnWall(String msg) {
Log.d("Tests", "Testing graph API wall post");
try {
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("description", "test test test");
response = mFacebook.request("me/feed", parameters,
"POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} catch(Exception e) {
e.printStackTrace();
}
}
Try this Its my working code:-
on wallpost Button click:-
mPostButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mFacebook.dialog(Class.this, "feed",
new SampleDialogListener());
}
&
public class SampleDialogListener extends BaseDialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("Facebook-Example", "Dialog Success! post_id=" + postId);
mAsyncRunner.request(postId, new WallPostRequestListener());
mDeleteButton.setVisibility(View.VISIBLE);
} else {
Log.d("Facebook-Example", "No wall post made");
}
}
}
& BaseDialogListner:---
public abstract class BaseDialogListener implements DialogListener {
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onCancel() {
}
}
public class WallPostRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
Log.d("Facebook-Example", "Got response: " + response);
String message = "<empty>";
try {
JSONObject json = Util.parseJson(response);
message = json.getString("message");
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
final String text = "Your Wall Post: " + message;
VideoUpload.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText(text);
}
});
}
}
& BaseRequestListner:--
public abstract class BaseRequestListener implements RequestListener {
public void onFacebookError(FacebookError e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onIOException(IOException e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}