How Do I automatically update TexT? Android Studio? - android

I am parsing a JSON response and when I click a button it updates the text but only on refresh, how do I get it to instantly, and dynamically update the texT??
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);
}
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");
String selectedId = currentQuestions.getString("selected");
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);
blogs.setSelected(selectedId);
System.out.print(Answerid);
listblogs.add(blogs);
}
System.out.println(data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
The only thing I have tried it recalling the jsonarray in my listener
public void OnDown(View view) {
CharSequence IdDownVote = ((TextView) ((RelativeLayout) view.getParent()).getChildAt(1)).getText();
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_DOWN = "someURL";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_DOWN, 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");
}

Related

Returning ArrayList from AsyncTask

I am trying to get urls of songs from a server. I want to get all urls in an arraylist which can be shown in a recycler view in next activity. URLs are correctly received when I try to see them using Toast or log. But when I try to get them as a return result of AsyncTask it shows size = 0 for the arraylist returned. I have followed the answers from this question specially by Blackbelt. But that proved to be of no use. Comments are disabled on that answer. So, here I am posting my question with the modified code. Here is the code I have written.
interface OnFetchUrlsListener
{
public void onUrlsFetched(ArrayList<String> arrayList);
public void onUrlsError(String error);
}
public class SplashScreen extends AppCompatActivity implements OnFetchUrlsListener{
#Override
public void onUrlsFetched(ArrayList<String> arrayList) {
Toast.makeText(this, "result size : "+arrayList.size(), Toast.LENGTH_SHORT).show();
}
#Override
public void onUrlsError(String error) {
}
private static RequestQueue mQueue;
public static ArrayList<String> songsArray ;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
songsArray = new ArrayList<String>();
String uri = Uri.parse("https://dee9c999.ngrok.io/audio/data/WebsiteSourceCode/api/all_songs.php/?allsongs=allsongs").toString();
new FetchSongs(this).execute(uri);
}
private class FetchSongs extends AsyncTask<String, String, ArrayList<String>> {
private OnFetchUrlsListener mListener;
public FetchSongs(OnFetchUrlsListener listener){
mListener = listener;
}
#Override
protected ArrayList<String> doInBackground(String... params) {
//some heavy processing resulting in a Data String
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, params[0], 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++) {
songsArray.add(jsonArray.getString(i));
}
}
catch (JSONException e) {
e.printStackTrace();
Log.d("JSON Parse", String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(SplashScreen.this, "Load error!!", Toast.LENGTH_SHORT).show();
}
});
mQueue.add(request);
return songsArray;
}
#Override
protected void onPreExecute() {}
#Override
protected void onPostExecute(ArrayList<String> result) {
if(mListener!=null)
{
mListener.onUrlsFetched(result);
}
}
}
}
[Edit]
private ArrayList<String> startHeavyProcessing(String uri) {
final ArrayList<String> result = new ArrayList<String>();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, uri, 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++) {
result.add(jsonArray.getString(i));
Toast.makeText(SplashScreen.this, jsonArray.getString(i), Toast.LENGTH_SHORT).show();
}
songs_fetched = true;
}
catch (JSONException e) {
e.printStackTrace();
songs_fetched = false;
Log.d("JSON Parse", String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(SplashScreen.this, "Load error!!", Toast.LENGTH_SHORT).show();
}
});
mQueue.add(request);
return result;
}
Now, when I try to print result of the function startHeavyProcessing() it is returning an arraylist of size 0 but inside the function it is getting the songs urls perfectly fine.
I've solved Your problem on a different way ...
as usual define this interface
public interface OnFetchUrlsListener {
void onUrlsFetched(ArrayList<String> arrayList);
void onUrlsError(String error);
}
write down a class, say, VolleyCall where volley get request will happen & result/response will be returned using listener
public class VolleyCall {
private String TAG = VolleyCall.class.getSimpleName();
private String mUrl;
private OnFetchUrlsListener mOnFetchUrlsListener;
private ArrayList<String> mSongs;
private RequestQueue mQueue;
public VolleyCall(Context context, String url, OnFetchUrlsListener onFetchUrlsListener) {
mSongs = new ArrayList<>();
mUrl = url;
mOnFetchUrlsListener = onFetchUrlsListener;
mQueue = Volley.newRequestQueue(context);
}
public void parse() {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, mUrl, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e(TAG, "_log : onResponse : response : " + response.toString());
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
mSongs.add(jsonArray.getString(i));
}
mOnFetchUrlsListener.onUrlsFetched(mSongs);
} catch (JSONException e) {
Log.e(TAG, "_log : onResponse : JSONException : " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "_log : onErrorResponse : error : " + error.getMessage());
mOnFetchUrlsListener.onUrlsError(error.getMessage());
}
});
mQueue.add(request);
Log.e(TAG, "_log : songsArray_size : " + mSongs.size());
}
}
modify your main activity
public class SplashScreen extends AppCompatActivity implements OnFetchUrlsListener {
private String TAG = SplashScreen.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "https://dee9c999.ngrok.io/audio/data/WebsiteSourceCode/api/all_songs.php/?allsongs=allsongs";
VolleyCall call = new VolleyCall(SplashScreen.this, url, SplashScreen.this);
call.parse();
}
#Override
public void onUrlsFetched(ArrayList<String> arrayList) {
Log.e(TAG, "_log : onUrlsFetched : is_arrayList_null : " + (arrayList == null));
if (arrayList != null) {
Log.e(TAG, "_log : onUrlsFetched : arrayList_size : " + arrayList.size());
}
String file_names = "";
for (String s : arrayList) {
file_names = file_names.concat(s + "\n");
}
TextView tv = findViewById(R.id.text);
tv.setText(file_names);
}
#Override
public void onUrlsError(String error) {
Log.e(TAG, "_log : onUrlsError : " + error);
}
}
Try this, you dont need to return arraylist if you use this, at the end of function arraylist will have all the values
ArrayList<String> result = new ArrayList<>();
private void startHeavyProcessing(String uri) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, uri, 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++) {
result.add(jsonArray.getString(i));
}
}
catch (JSONException e) {
e.printStackTrace();
Log.d("JSON Parse", String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}

String to jsonObject

On the below code i want to use Response but it throws JSONException
StringRequest strReq = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v(TAG, "Response: " + response);//output {"error":false}
try {
JSONObject jo = new JSONObject(response); // java.lang.String cannot be converted to JSONObject
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Sample JSON string:
{
"error": false,
"uid": "5b081af13eb974.69226352",
"user": {
"name": "66699",
"created_at": "2018-05-25 18:47:21"
}
}
How i should solve this?
Well, to retrieve the content of your response you don't need to use JSON while using POST request. Instead do something like this :
if (response.equalsIgnoreCase("yourResponseFromTheWebService")) {
...
Toast
} else if (response.equalsIgnoreCase("OtherPossibleResponse")){
....
Toast
} else{
....
Toast
}
in case of GET request you should do something like this :
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// display response
try {
//put response into string
JSONArray Jresult = response.getJSONArray("user");
for (int i = 0; i < Jresult.length(); i++) {
JSONObject json_data = Jresult.getJSONObject(i);
String lName = json_data.getString("name");
String lCreatedAt = json_data.getString("created_at");
//create a model class with your user info like name and created_at and for every user found create a new user object and store its info.
_myUser.add(new User(lName, lCreatedAt));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(getRequest);

android api json Parser

hi i have an app shows the online streamers from Twitch.tv and the data comes from request i send but i cant parse them this is my code
public ArrayList<Twitch> ParseTwitch(JSONArray object, Context context){
ArrayList<Twitch> chanels = new ArrayList<>();
try {
for (int i = 0;i<object.length();i++){
JSONObject streamObjct = object.getJSONObject(i);
JSONObject chanel = streamObjct.getJSONObject("channel");
JSONObject url= streamObjct.getJSONObject("preview");
final Twitch twitch = new Twitch();
twitch.setName(chanel.getString(CHANEL_NAME));
twitch.setStatus(chanel.getString(CHANEL_STATUS));
twitch.setGame(streamObjct.getString(GAME));
twitch.setLanguage(chanel.getString(BROADCASTER_LANGUAGE));
twitch.setViewrs(streamObjct.getInt(VIEWRS));
String imageUrl = url.getString("medium");
ImageRequest request =new ImageRequest(imageUrl, new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
twitch.setLogo(response);
}
}, 0, 0, null, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue quew = Volley.newRequestQueue(context);
quew.add(request);
chanels.add(twitch);
}
return chanels;
}catch (JSONException e){
e.printStackTrace();
}
return chanels;
}
and this my request
https://api.twitch.tv/kraken/search/streams?query=poker&client_id=gxdzx71jhztgyypn4kjemm1htovv1o
at least can anyone tell me should i work with sqlite Database or not?
where i called TwitchParcer
private void prepareData(String url, final ListView mListView) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray stream = response.getJSONArray("streams");
TwitchApiParser parser = new TwitchApiParser();
ArrayList items= parser.ParseTwitch(stream);
TwitchAdapter adapter = new TwitchAdapter(getContext(),
R.layout.activity_last_news_fragment,items);
mListView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "Ridi Bro", Toast.LENGTH_SHORT).show();
}
});
RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
quew.add(request);
}
and this is new Error
Process: app.mma.introsliderproject, PID: 11542
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at app.mma.PokerInfo.twitch.TwitchAdapter.getView(TwitchAdapter.java:39)
i solve the problem this is the complete code
public class TwitchFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.twitch_main, container, false);
String url="http://192.168.1.101/mySite/Flowers/flowers2.json";
ListView mListView = (ListView) view.findViewById(R.id.twitch_last);
prepareData(url,mListView);
return view;
}
private void prepareData(String url, final ListView mListView) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray stream = response.getJSONArray("streams");
TwitchApiParser parser = new TwitchApiParser();
ArrayList items= parser.ParseTwitch(stream,getActivity().getApplicationContext());
TwitchAdapter adapter = new TwitchAdapter(getContext(),
R.layout.twitch,items);
mListView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "Ridi Bro", Toast.LENGTH_SHORT).show();
}
});
RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
quew.add(request);
}
and the parser
public class TwitchApiParser {
private final String CHANEL_NAME="display_name";
private final String GAME="game";
private final String CHANEL_STATUS = "status";
private final String BROADCASTER_LANGUAGE = "broadcaster_language";
private final String VIEWRS = "viewers";
public ArrayList<Twitch> ParseTwitch(JSONArray object, Context context){
ArrayList<Twitch> chanels = new ArrayList<>();
try {
for (int i = 0;i<object.length();i++){
JSONObject streamObjct = object.getJSONObject(i);
JSONObject chanel = streamObjct.getJSONObject("channel");
JSONObject url= streamObjct.getJSONObject("preview");
final Twitch twitch = new Twitch();
twitch.setName(chanel.getString(CHANEL_NAME));
twitch.setStatus(chanel.getString(CHANEL_STATUS));
twitch.setGame(streamObjct.getString(GAME));
twitch.setLanguage(chanel.getString(BROADCASTER_LANGUAGE));
twitch.setViewrs(streamObjct.getInt(VIEWRS));
String imageUrl = url.getString("medium");
ImageRequest request =new ImageRequest(imageUrl, new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
twitch.setLogo(response);
}
}, 0, 0, null, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue quew = Volley.newRequestQueue(context);
quew.add(request);
chanels.add(twitch);
}
return chanels;
}catch (JSONException e){
e.printStackTrace();
}
return chanels;
}

String Request from FirebaseMessagingService using volley doesn't work

When I'm using volley to send request to the server it doesn't work and throws a runtime error.
public class MyFCMService extends FirebaseMessagingService {
String url, title, message;
String category_id;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
title = remoteMessage.getData().get("title");
message = remoteMessage.getData().get("message");
String id = remoteMessage.getData().get("ID");
if (check(id).equals("6")) {
sendNotification(title, message);
} else {
sendNotification("khalid", "khalid");
}
}
public String check(String id) {
url = "http://www.tobeacademy.com/api/get_post/?post_id=" + id;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("post");
category_id = array.getJSONObject(0).getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(this).add(stringRequest);
return category_id;
}
Volley requests complete asynchronously. The onResponse() method of your listener does not execute until the reuqested data is received from the tobeacademy server.
That means that in your check() method, the value returned by category_id is not valid because it is returned before the listener onResponse() has executed and defined it.
You need to refactor your code to something like this:
public void check(String id, final String title, final String message) {
url = "http://www.tobeacademy.com/api/get_post/?post_id=" + id;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("post");
String category_id = array.getJSONObject(0).getString("id");
if (category_id.equals("6")) {
sendNotification(title, message);
} else {
sendNotification("khalid", "khalid");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(this).add(stringRequest);
}

Not execute Volley JSON onResponse function

When I call getData.It seems that it is hard to get the result out from the onResponse. I know it cannot work in this current way. Could anyone help me to settle this problem?
getData()
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(SPINNER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d("Country_name","hi");
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(JSON_ARRAY);
Log.v("xxxxx",result.toString());
String mysh=result.toString().substring(1, result.toString().length()-1);
JSONArray jsonArray = new JSONArray(mysh);
//Calling method getCountry to get the country from the JSON Array
getCountry(jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
Try this i think it should work
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(SPINNER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
getCountry(jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Try that, this will help.
private void getData() {
String tag_string_req = "req_name";
spotsDialog.show();
StringRequest strReq = new StringRequest(Method.POST,
YOUR URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response.toString());
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("YOUR ARRAY NAME");
for (int i=0;i<array.length();i++){
String result = array.getString(i).toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
}
});
strReq.setRetryPolicy(new RetryPolicy() {
#Override
public void retry(VolleyError arg0) throws VolleyError {
}
#Override
public int getCurrentTimeout() {
return 0;
}
#Override
public int getCurrentRetryCount() {
return 0;
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
Happy To Help.

Categories

Resources