i am getting this error while implementing swipe refresh layout - android

i am getting below error
setOnRefreshListener
(android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener)
in SwipeRefreshLayout cannot be applied
to
(in.com.goalert.activity.MainActivity)
at
swipeRefreshLayout.setOnRefreshListener(this);
full code is below
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private SessionManager pref;
private SQLiteHandler db;
private ListView listView;
private FeedListAdapter listAdapter;
public static List<FeedItem> feedItems =new ArrayList<>();
private SwipeRefreshLayout swipeRefreshLayout;
private String URL_FEED = "http://api.androidhive.info/feed/feed.json";
static int count = 0;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initNavigationDrawer();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
pref = new SessionManager(getApplicationContext());
db = new SQLiteHandler(getApplicationContext());
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
public void onRefresh() {
Log.i("onRefresh","onRefresh");
fetchfeed();
}
private void fetchfeed() {
Log.i("fetchfeed","fetchfeed");
String URL_FEED = "http://www.goalert.in/feed/engineering.json";
swipeRefreshLayout.setRefreshing(true);
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d("Response",response.toString());
if (response != null) {
swipeRefreshLayout.setRefreshing(false);
parseJsonFeed(response);
}
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonReq);
// Adding request to volley request queue
//AppController.getInstance().addToRequestQueue(jsonReq);
// showing refresh animation before making http call
}
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}

You can try to use below code for swipeRefreshLayout This code is work for me.
Here is SwipeRefreshLayout XML code snippiest.
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_refresh_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:divider="#null"
android:dividerHeight="0dp" />
</android.support.v4.widget.SwipeRefreshLayout>
Here is the java code snippiest look like as per your requirement or code
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeView.setEnabled(false);
swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
(new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
swipeView.setRefreshing(false);
try {
onRefresh();
} catch (Exception e) {
e.printStackTrace();
}
}
}, 3000);
}
});
// user defined on-refresh method
private void onRefresh() {
Log.i("onRefresh","onRefresh");
fetchfeed();
}
private void fetchfeed() {
Log.i("fetchfeed","fetchfeed");
String URL_FEED = "http://www.goalert.in/feed/engineering.json";
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d("Response",response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonReq);
}
Remains you can use your code as per your requirement.
I suggest to try to use this solution. It will work

you have to implement the MainActivity with android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener

my problem is solved by
doing
implements SwipeRefreshLayout.OnRefreshListener

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

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

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

How do implement swipe to refresh on fragments for json feeds called from other activity

I want to add swipe to refresh i cant find out how to call on refresh from ScrollableTabActivity.java
OneFragment.java
public class OneFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private ListView listView;
private FeedListAdapter listAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private FeedListAdapter adapter;
private int id = 0;
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_one, container, false);
listView = (ListView) view.findViewById(R.id.list);
listAdapter = new FeedListAdapter(getActivity(), ScrollableTabsActivity.feedItems);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
listView.setAdapter(listAdapter);
swipeRefreshLayout.setOnRefreshListener(this);
return view;
}
ScrollableTabsActivity.java
public class ScrollableTabsActivity extends AppCompatActivity {
private static final String TAG = ScrollableTabsActivity.class.getSimpleName();
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
public static List<FeedItem> feedItems =new ArrayList<>();
public static List<FeedItem> feedItems1 =new ArrayList<>();
public static List<FeedItem> feedItems2 =new ArrayList<>();
public static List<FeedItem> feedItems3 =new ArrayList<>();
public static List<FeedItem> feedItems4 =new ArrayList<>();
private String URL_FEED = "http://www.goalert.in/feed/engineering.json";
private String URL_FEED1 = "http://www.goalert.in/feed/medical.json";
private String URL_FEED2 = "http://www.goalert.in/feed/bschool.json";
private String URL_FEED3 = "http://www.goalert.in/feed/law.json";
private String URL_FEED4 ="http://www.goalert.in/feed/GovernmentExams.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrollable_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_FEED);
Cache cache1 = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry1 = cache1.get(URL_FEED1);
Cache cache2 = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry2 = cache2.get(URL_FEED2);
Cache cache3 = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry3 = cache3.get(URL_FEED3);
Cache cache4 = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry4 = cache4.get(URL_FEED4);
//if and else for Engineering Feeds
feedItems.clear();
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
//if and else for Medical feeds
feedItems1.clear();
if (entry1 != null) {
// fetch the data from cache
try {
String data = new String(entry1.data, "UTF-8");
try {
parseJsonFeed1(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_FEED1, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed1(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
//if and else for bschool feeds
feedItems2.clear();
if (entry2 != null) {
// fetch the data from cache
try {
String data = new String(entry2.data, "UTF-8");
try {
parseJsonFeed2(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_FEED2, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed2(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
feedItems3.clear();
//if and else for law feeds
if (entry3 != null) {
// fetch the data from cache
try {
String data = new String(entry3.data, "UTF-8");
try {
parseJsonFeed3(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_FEED3, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed3(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
feedItems4.clear();
//if and else for Government Exams feeds
if (entry4 != null) {
// fetch the data from cache
try {
String data = new String(entry4.data, "UTF-8");
try {
parseJsonFeed4(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_FEED4, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed4(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
} catch (JSONException e) {
e.printStackTrace();
}
}
private void parseJsonFeed1(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems1.add(item);
}
// notify data changes to list adapater
} catch (JSONException e) {
e.printStackTrace();
}
}
private void parseJsonFeed2(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems2.add(item);
}
// notify data changes to list adapater
} catch (JSONException e) {
e.printStackTrace();
}
}
private void parseJsonFeed3(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems3.add(item);
}
// notify data changes to list adapater
} catch (JSONException e) {
e.printStackTrace();
}
}
private void parseJsonFeed4(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems4.add(item);
}
// notify data changes to list adapater
} catch (JSONException e) {
e.printStackTrace();
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new OneFragment(), "Engineering");
adapter.addFrag(new TwoFragment(), "Medical");
adapter.addFrag(new ThreeFragment(), "B-School");
adapter.addFrag(new FourFragment(), "Law");
adapter.addFrag(new FiveFragment(), "Government Services");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_logout, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.profile_done) {
SharedPreferences preferences = getSharedPreferences("AndroidHiveLogin", 0);
preferences.edit().remove("isLoggedIn").commit();
startActivity(new Intent(ScrollableTabsActivity.this, LoginActivity.class));
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Since your Fragments implement SwipeRefreshLayout.OnRefreshListener, you can simply call onRefresh(). If your intention is to manually force a refresh.
Example:
((SwipeRefreshLayout.OnRefreshListener) pagerAdapter.getItem(position)).onRefresh();

Consuming APIs with volley?

I am trying to consume APIs with the library volley, but i can't because it doesn't show me anything when I run the app.
I think the problem is that the URL API has that in it (json):
{"books":[{"book":{PARAMETERS...}}]}
so I can't access my parameters. Then my URL API doesn't have .json at the end of the URL but I don't think that's the problem.
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://############";
private ProgressDialog pDialog;
private List<Books> booksList = new ArrayList<Books>();
private ListView listView;
private Adapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new Adapter(this, booksList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
//getActionBar().setBackgroundDrawable(
// new ColorDrawable(Color.parseColor("#1b1b1b")));
JsonArrayRequest booksReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Books books = new Books();
Books.setTitle(obj.getString("title"));
Books.setPhoto_url(obj.getString("image"));
booksList.add(books);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
Controller.getInstance().addToRequestQueue(booksReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
My json in the URL API:
{
"books": [
{
"book": {
"title": "namebook",
"photo_url": {
"src": "http://######",
"alt": ""
}
}
}
]
}
So how can I get to show them?
Try using
JsonObjectRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) instead of JsonArrayRequest as your response seems to be JSONObject
Also, there is no such key image in your response
Books.setPhoto_url(obj.getString("image"));
Looking at your JSON response, if you try following code, it should work:
JsonObjectRequest artistReq = new JsonObjectRequest(Method.GET, url, null, new Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
if (response.optJSONArray("books") != null) {
JSONArray books = response.getJSONArray("books");
for (int i = 0; i < books.length(); i++) {
JSONObject book = books.getJSONObject(i);
String title = book.getString("title");
// next K,V pair consist of JSONObject photo_url
JSONObject photoUrl = book.getJSONObject("photo_url");
String photoSrc = photoUrl.getString("src");
String photoAlt = photoUrl.getString("alt");
// use extracted values in your Book object
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
Hope it would help!

Categories

Resources