Integrating Loaders and recycler view not working - java

I am using a loader and a OkHttp client to get data from a news API and populate the data in a recycler view. I used a progress bar to show until the the loader is finished loading the data . But all I see is the progress bar, the recycler view is not showing up.
Please help me
MainActivity.java
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<ArrayList<News>> {
private static final int LOADER_ID = 1 ;
private String url = "https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=latest&apiKey=<API KEY>";
private ProgressBar progressBar;
private NewsAdapter mAdapter;
private RecyclerView recList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
recList.setHasFixedSize(true);
getSupportLoaderManager().initLoader(LOADER_ID , null , this);
}
#Override
public Loader<ArrayList<News>> onCreateLoader(int id, Bundle args) {
return new AsyncTaskLoader<ArrayList<News>>(this) {
#Override
public ArrayList<News> loadInBackground() {
return makeConnectionAndParseData(url);
}
};
}
#Override
public void onLoadFinished(Loader<ArrayList<News>> loader, ArrayList<News> data) {
progressBar.setVisibility(View.INVISIBLE);
mAdapter = new NewsAdapter(data);
recList.setAdapter(mAdapter);
// The data is brought back here after the network call is executed in the variable data.
// Update the recycler view here to show the list of news
// Take care of exception cases like no network connection , invalid url and other extreme cases
}
#Override
public void onLoaderReset(Loader<ArrayList<News>> loader) {
// Reset the recycler view . The UI should not show recycler view when the loader is reset
// Update the UI with a text view to let the user know about the error
}
private String makeNetworkConnection(String url)
{
OkHttpClient client = new OkHttpClient();
try {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private ArrayList<News> parseJsonIntoArrayList(String json)
{
final ArrayList<News> newsArrayList;
try {
newsArrayList = null;
JSONObject object = new JSONObject(json);
JSONArray articles = object.getJSONArray("articles");
for (int i=0 ; i<articles.length() ; i++)
{
JSONObject articleObjects = articles.getJSONObject(i);
String author = articleObjects.getString("author");
String title = articleObjects.getString("title");
String desc = articleObjects.getString("description");
String imageUrl = articleObjects.getString("imageUrl");
String clickableUrl = articleObjects.getString("url");
newsArrayList.add(new News(title,desc,imageUrl,clickableUrl,author));
}
return newsArrayList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
private ArrayList<News> makeConnectionAndParseData(String url)
{
String jsonResponse = makeNetworkConnection(url);
return parseJsonIntoArrayList(jsonResponse);
}}
NewsAdapter.java
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsHolder> {
ArrayList<News> mNewsData;
public NewsAdapter(ArrayList<News> newsData)
{
mNewsData = newsData;
}
public class NewsHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView titleTv , descTv ;
private ImageView newsImageView;
public NewsHolder(View itemView) {
super(itemView);
titleTv = (TextView) itemView.findViewById(R.id.newsTitle);
descTv = (TextView) itemView.findViewById(R.id.newsDesc);
newsImageView = (ImageView) itemView.findViewById(R.id.newsImage);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// Handle the click item here.
}
}
#Override
public NewsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View inflatedView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item , parent , false);
return new NewsHolder(inflatedView);
}
#Override
public void onBindViewHolder(NewsHolder holder, int position) {
News news = mNewsData.get(position);
holder.titleTv.setText(news.getNewsTitle());
holder.descTv.setText(news.getNewsSubtitle());
String imageUrl = news.getImageUrl();
Picasso.with(holder.newsImageView.getContext())
.load(imageUrl)
.into(holder.newsImageView);
}
#Override
public int getItemCount() {
return mNewsData.size();
}}
In android monitor , there was
01-10 14:55:59.319 10318-10318/com.sriram.news E/RecyclerView: No adapter attached; skipping layout
Please tell me where I have gone wrong
And is my implementation of the recycler view correct? I'm still confused about recycler view.
Thanks in advance

Place
mAdapter = new NewsAdapter();
recList.setAdapter(mAdapter);
above
recList.setLayoutManager(llm);
recList.setHasFixedSize(true);
and fix NewsAdapter.java
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsHolder> {
ArrayList<News> mNewsData;
// remove constructor
public void addAll(List<News> newsData) {
mNewsData = newsData;
}
...
}
MainActivity.java
#Override
public void onLoadFinished(Loader<ArrayList<News>> loader, ArrayList<News> data) {
progressBar.setVisibility(View.INVISIBLE);
mAdapter.addAll(data);
mAdapter.notifyDataSetChanged();
}

Related

Recyclerview empty on first load

Hi like it says in the title im trying to make my recyclerview work but it always show empty on first load. Only when i change activity and come back it appear. The data is fetched on create but dont seem to get passed to the adapter.
So my question is : How to load data in recyclerview on first load ?
RecyclerViewFragment.java
private static final String TAG = "RecyclerViewFragment";
private static final String KEY_LAYOUT_MANAGER = "layoutManager";
private static final int SPAN_COUNT = 2;
private static final int DATASET_COUNT = 60;
public static ArrayList<String> arraylist_News = new ArrayList<String>();
public static ArrayList<String> arraylist_Thumbs = new ArrayList<String>();
public static ArrayList<String> arraylist_Links = new ArrayList<String>();
private static String URL = "https://mangascan.cc/";
public String titre;
public String name;
public String img;
public String lien;
private enum LayoutManagerType {
GRID_LAYOUT_MANAGER,
LINEAR_LAYOUT_MANAGER
}
protected LayoutManagerType mCurrentLayoutManagerType;
protected RadioButton mLinearLayoutRadioButton;
protected RadioButton mGridLayoutRadioButton;
protected RecyclerView mRecyclerView;
protected CustomAdapter mAdapter;
protected RecyclerView.LayoutManager mLayoutManager;
protected String[] mDataset;
protected String[] mDatasetName;
protected String[] mDatasetImg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize dataset, this data would usually come from a local content provider or
// remote server.
initDataset();
new getWebsite().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recycler_view_frag, container, false);
rootView.setTag(TAG);
// BEGIN_INCLUDE(initializeRecyclerView)
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
//mRecyclerView.setHasFixedSize(false);
// LinearLayoutManager is used here, this will layout the elements in a similar fashion
// to the way ListView would layout elements. The RecyclerView.LayoutManager defines how
// elements are laid out.
mLayoutManager = new LinearLayoutManager(getActivity());
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
if (savedInstanceState != null) {
// Restore saved layout manager type.
mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
.getSerializable(KEY_LAYOUT_MANAGER);
}
setRecyclerViewLayoutManager(mCurrentLayoutManagerType);
// END_INCLUDE(initializeRecyclerView)
// getParentFragmentManager().beginTransaction().detach(this).attach(this).commit();
mAdapter = new CustomAdapter(getActivity(),mDataset,mDatasetName,mDatasetImg);
// Set CustomAdapter as the adapter for RecyclerView.
mRecyclerView.setAdapter(mAdapter);
mAdapter.ResetValues(mDataset);
// mAdapter.notifyItemRangeChanged(0, arraylist_News.size());
return rootView;
}
/**
* Set RecyclerView's LayoutManager to the one given.
*
* #param layoutManagerType Type of layout manager to switch to.
*/
public void setRecyclerViewLayoutManager(LayoutManagerType layoutManagerType) {
int scrollPosition = 0;
// If a layout manager has already been set, get current scroll position.
if (mRecyclerView.getLayoutManager() != null) {
scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
}
mLayoutManager = new LinearLayoutManager(getActivity(),RecyclerView.HORIZONTAL, false);
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.scrollToPosition(scrollPosition);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save currently selected layout manager.
savedInstanceState.putSerializable(KEY_LAYOUT_MANAGER, mCurrentLayoutManagerType);
super.onSaveInstanceState(savedInstanceState);
}
/**
* Generates Strings for RecyclerView's adapter. This data would usually come
* from a local content provider or remote server.
*/
private void initDataset() {
mDataset = new String[arraylist_News.size()];
for (int i = 0; i < arraylist_News.size(); i++) {
mDataset[i] = String.valueOf(arraylist_News.get(i));
}
mDatasetName = new String[arraylist_Links.size()];
for (int i = 0; i < arraylist_Links.size(); i++) {
mDatasetName[i] = String.valueOf(arraylist_Links.get(i));
}
mDatasetImg = new String[arraylist_Thumbs.size()];
for (int i = 0; i < arraylist_Thumbs.size(); i++) {
mDatasetImg[i] = String.valueOf(arraylist_Thumbs.get(i));
}
}
private class getWebsite extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
arraylist_News.clear();
arraylist_Thumbs.clear();
arraylist_Links.clear();
}
private static final String userAgent = "Mozilla/5.0 (jsoup)";
#Override
protected Void doInBackground(Void... voids) {
try {
Document doc = Jsoup.connect(URL).userAgent(userAgent).timeout(12000).get();
//scan-mangas get news script
Element news = doc.select(".hot-thumbnails").first();
// Log.d("jSoup", news.toString());
for (Element e : news.select(".span3")){
titre = e.select("p").text().toString();
//Log.d("okk", titre);
img = e.select("img").attr("src");
lien = e.select("a").attr("href");
name = e.getElementsByClass("label label-warning").text().toString();
arraylist_News.add((titre));
arraylist_Thumbs.add(img);
arraylist_Links.add(name);
}
for (String str_Agil : arraylist_Thumbs) // using foreach
{
Log.e("NEWS:: " , str_Agil);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
((CustomAdapter)mRecyclerView.getAdapter()).ResetValues(mDataset);
mAdapter.notifyDataSetChanged();
mAdapter.notifyItemRangeInserted(0, arraylist_News.size());
//System.out.println("update ui");
mRecyclerView.removeAllViews();
}
});
}
}
CustomAdapter.java
private String[] mDataSet;
private String[] mDataSetName;
private String[] mDataSetImg;
Context context;
// BEGIN_INCLUDE(recyclerViewSampleViewHolder)
/**
* Provide a reference to the type of views that you are using (custom ViewHolder)
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView textView;
private final TextView textView2;
private final ImageView imgView;
public ViewHolder(View v) {
super(v);
// Define click listener for the ViewHolder's View.
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Element " + getAdapterPosition() + " clicked.");
}
});
textView = (TextView) v.findViewById(R.id.textView);
textView2 = (TextView) v.findViewById(R.id.textView2);
imgView = (ImageView) v.findViewById(R.id.thumbnail);
}
public TextView getTextView() {
return textView;
}
public TextView getTextView2() {
return textView2;
}
}
// END_INCLUDE(recyclerViewSampleViewHolder)
/**
* Initialize the dataset of the Adapter.
*
* #param dataSet String[] containing the data to populate views to be used by RecyclerView.
*/
public CustomAdapter(Context context, String[] dataSet, String[] dataSet1, String[] dataSet2) {
mDataSet = dataSet;
mDataSetName = dataSet1;
mDataSetImg = dataSet2;
this.context = context;
}
// BEGIN_INCLUDE(recyclerViewOnCreateViewHolder)
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
// Create a new view.
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.text_row_item, viewGroup, false);
return new ViewHolder(v);
}
// END_INCLUDE(recyclerViewOnCreateViewHolder)
// BEGIN_INCLUDE(recyclerViewOnBindViewHolder)
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
Log.d(TAG, mDataSet[position] + " set.");
// Get element from your dataset at this position and replace the contents of the view
// with that element
viewHolder.getTextView().setText(mDataSet[position]);
viewHolder.getTextView2().setText(mDataSetName[position]);
Picasso.with(viewHolder.imgView.getContext()).load(mDataSetImg[position]).into(viewHolder.imgView);
}
// END_INCLUDE(recyclerViewOnBindViewHolder)
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataSet.length;
}
public void ResetValues(String[] dataSet)
{
notifyDataSetChanged();
}
Thanks fellows devs
Bump
heres the full project so you can test it : https://drive.google.com/file/d/15rx7vELGiwlIfxZH3Np6Joycrsf4PxO_/view?usp=sharing
i been struggling for three months on this please help
This solution based on code in Google drive
Goto PageViewFragment.java and change this
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
if(pageAdapter==null){
pageAdapter =new PageAdapter(getActivity(), mDataset);
mRecyclerView.setAdapter(pageAdapter);
} else {
pageAdapter.notifyDataSetChanged();
Log.d("dataset", "changed");
}
}
});
To this
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
initDataset();
pageAdapter = new PageAdapter(getActivity(), mDataset);
mRecyclerView.setAdapter(pageAdapter);
}
});

create recycler view in fragment?

i want create a fragment and have inside a recycler view for show products ...
but when i render it is show this error : RecyclerView: No adapter attached; skipping layout
below i copy my codes;
this code is for adapter class :
private ArrayList<Products> ProductsList;
private Context context;
public Adapter(ArrayList<Products> productsList, Context context) {
ProductsList = productsList;
this.context = context;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.row_layout, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
Products products = ProductsList.get(position);
holder.txtName.setText(products.getName());
holder.txtPrice.setText("$ " + products.getPrice());
Picasso.get().load(Config.ipValue + "/images/" + products.getPhoto()).into(holder.imgV);
holder.imgV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(AnimationUtils.loadAnimation(context, android
.R.anim.slide_in_left));
}
});
}
#Override
public int getItemCount() {
return ProductsList.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView txtName;
TextView txtPrice;
ImageView imgV;
public MyHolder(View itemView) {
super(itemView);
txtName = itemView.findViewById(R.id.rowTxtProductName);
txtPrice = itemView.findViewById(R.id.rowTxtPrice);
imgV = itemView.findViewById(R.id.rowImgProduct);
}
}
and this one for web api class :
public class WebApiHandler {
Context context;
String apiLink = "";
ArrayList<Products> products = new ArrayList<>();
public WebApiHandler(Context context) {
this.context = context;
}
void apiConnect(String type) {
switch (type) {
case "getproducts": {
apiLink = Config.getProductsWebApi;
break;
}
}
ProgressDialog dialog = ProgressDialog.show(context, "Connecting...",
"please wait", false, false);
StringRequest request = new StringRequest(Request.Method.POST,
apiLink, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
showJson(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
}
});
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(request);
}
private void showJson(String response) {
products.clear();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
products.add(p);
}
} catch (JSONException e) {
e.printStackTrace();
}
VerticalFragment.productsArrayList = products;
IData iData = (IData) context;
iData.sendData();
}}
and my fragment code :
public class VerticalFragment extends Fragment implements IData {
RecyclerView rcVertical;
WebApiHandler webApiHandler;
static ArrayList<Products> productsArrayList = new ArrayList<>();
public VerticalFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_vertical, container, false);
rcVertical = view.findViewById(R.id.rcVertical);
webApiHandler = new WebApiHandler(getContext());
webApiHandler.apiConnect("getproducts");
rcVertical.addOnItemTouchListener(new RecyclerTouchListener(getContext(), rcVertical,
new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
ProductActivity.products = productsArrayList.get(position);
startActivity(new Intent(getContext(), ProductActivity.class));
}
#Override
public void onLongClick(View view, int position) {
}
}));
return view;
}
#Override
public void sendData() {
Adapter adapter = new Adapter(productsArrayList, getContext());
rcVertical.setLayoutManager(new LinearLayoutManager((getContext())));
rcVertical.setItemAnimator(new DefaultItemAnimator());
rcVertical.setAdapter(adapter);
}}
i should say i create a interface and have one method i say it sendData
This is a common error when there is no adapter attached to recyclerview upon showing recyclerview. It will not cause any harm to your app, but you could avoid it by setting empty adapter without data, and later when you get your data, provide it to your adapter and notify it
Edit - Example added
Create setter for your list in adapter. After that, in your fragment make adapter global and in onCreateView make instance of your adapter and attach it to recyclerview
adapter = new Adapter(new ArrayList<>(), getContext());
rcVertical.setAdapter(adapter);
...Initialize recyclerview...
And then in your sendData interface put your loaded values in it
adapter.setData(productsArrayList);
adapter.notifyDataSetChanged();

i want to make realtime changing data On RecyclerView

I'am trying to make refresh every 1 sec in my RecyclerView but i don't know how can i do it iam using my API , when something changed in my api i want to make that change in my RecylerView whitout the swiper or i want to make the swiper swipe every 1 sec .. so this is my Code :
public class InformationNow extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private RequestQueue requestQueue;
private SwipeRefreshLayout refresh;
private ArrayList<TrashCanModel> trashCanModels = new ArrayList<>();
private JsonArrayRequest arrayRequest;
private Dialog dialog;
private RecyclerView recyclerView;
private InformationNowAdapter informationNowAdapter ;
private String url = "http://192.168.1.34:9090/TrashCanData/lastrow";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information_now);
refresh = (SwipeRefreshLayout) findViewById(R.id.Swiper);
recyclerView = (RecyclerView) findViewById(R.id.Now);
dialog = new Dialog(this);
refresh.setOnRefreshListener(this);
refresh.post(new Runnable() {
#Override
public void run() {
trashCanModels.clear();
getData();
}
});
}
private void getData() {
refresh.setRefreshing(true);
arrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i++) {
try {
//JSONArray jsonArray = response.getJSONArray("users");
jsonObject = response.getJSONObject(i);
TrashCanModel cat = new TrashCanModel();
cat.setDistance(jsonObject.getInt("distance"));
cat.setTemperature(jsonObject.getInt("temperature"));
cat.setHumidity(jsonObject.getInt("humidity"));
Log.e("*********", cat.getDistance().toString());
Log.e("*********", cat.getTemperature().toString());
Log.e("*********", cat.getHumidity().toString());
trashCanModels.add(cat);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapterPush(trashCanModels);
refresh.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(InformationNow.this);
requestQueue.add(arrayRequest);
}
private void adapterPush(ArrayList<TrashCanModel> trashCanModels) {
informationNowAdapter = new InformationNowAdapter(this, trashCanModels);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(informationNowAdapter);
}
#Override
public void onRefresh() {
trashCanModels.clear();
getData();
}
}
and my adapter :
public class InformationNowAdapter extends RecyclerView.Adapter<InformationNowAdapter.MyViewHolder>{
private Context context ;
private ArrayList<TrashCanModel> trashCanModels;
private String url = "";
//
public InformationNowAdapter (Context context , ArrayList<TrashCanModel> trashCanModels) {
this.context = context;
this.trashCanModels=trashCanModels;
}
#NonNull
#Override
public InformationNowAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view ;
LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.trashcan_list , parent , false);
return new InformationNowAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull InformationNowAdapter.MyViewHolder holder, int position) {
//holder.id.setText("#"+String.valueOf(position+1));
holder.distance.setText(trashCanModels.get(position).getDistance().toString());
holder.temperature.setText(trashCanModels.get(position).getTemperature().toString());
holder.humidity.setText(trashCanModels.get(position).getHumidity().toString());
}
#Override
public int getItemCount() {
return trashCanModels.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView distance , temperature , humidity ;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
distance = (TextView) itemView.findViewById(R.id.distance);
temperature = (TextView) itemView.findViewById(R.id.temperature);
humidity = (TextView) itemView.findViewById(R.id.humidity);
//
}
}
}
so how can i make refresh data every 1 sec !
You can use Timer to do that
Timer repeatTask = new Timer();
repeatTask.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
trashCanModels.clear();
getData();
}
}, 0, 1000);
call repeatTask.cancel() when you want to stop
But I think you should use push notification when your api change or use firebase or socket.io instead

How to create a OnItemClickListener for custom list view when passing data from php using json

I am creating an app where a list of hotels will be shown, all the data is coming from MySQL using JSON and PHP, I created the custom list view by extending the base adapter to a custom one, but I am not able to implement a OnItemClickListener for the listview, as i want to show the Hotel Name of that row in Toast whenever the user clicks on a row of list view. I tried various example available on internet, but i just doesn't work.
Adapter
public class CustomListAdapterHotel extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<WorldsBillionaires> billionairesItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapterHotel(Activity activity, List<WorldsBillionaires> billionairesItems) {
this.activity = activity;
this.billionairesItems = billionairesItems;
}
#Override
public int getCount() {
return billionairesItems.size();
}
#Override
public Object getItem(int location) {
return billionairesItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_hotel, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
//NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
TextView hotel_name = (TextView) convertView.findViewById(R.id.hotel_name);
TextView zone = (TextView) convertView.findViewById(R.id.zone);
TextView contact_person = (TextView) convertView.findViewById(R.id.contact_person);
TextView contact_number = (TextView) convertView.findViewById(R.id.contact_number);
TextView btc_direct = (TextView) convertView.findViewById(R.id.btcdirect);
// getting billionaires data for the row
WorldsBillionaires m = billionairesItems.get(position);
// name
hotel_name.setText(String.valueOf(m.getHotel_Name()));
zone.setText(String.valueOf(m.getHotel_Zone()));
contact_person.setText(String.valueOf(m.getContact_Person()));
contact_number.setText(String.valueOf(m.getContact_Number()));
btc_direct.setText(String.valueOf(m.getBtc_Direct()));
return convertView;
}
}
Model
public class WorldsBillionaires {
private String hotel_name,hotel_zone,contact_person,contact_number,btc_direct;
public WorldsBillionaires(String hotel_name, String hotel_zone, String contact_person, String contact_number, String btc_direct) {
this.hotel_name=hotel_name;
this.hotel_zone=hotel_zone;
this.contact_person=contact_person;
this.contact_number=contact_number;
this.btc_direct=btc_direct;
}
public WorldsBillionaires() {
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public String getHotel_Name() {
return hotel_name;
}
public void setHotel_Name(String hotel_name) {
this.hotel_name = hotel_name;
}
public String getHotel_Zone() {
return hotel_zone;
}
public void setHotel_Zone(String hotel_zone) {
this.hotel_zone = hotel_zone;
}
public String getContact_Person() {
return contact_person;
}
public void setContact_Person(String contact_person) {
this.contact_person = contact_person;
}
public String getContact_Number() {
return contact_number;
}
public void setContact_Number(String contact_number) {
this.contact_number = contact_number;
}
public String getBtc_Direct() {
return btc_direct;
}
public void setBtc_Direct(String btc_direct) {
this.btc_direct = btc_direct;
}
}
Main Activity
public class ShowHotel extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
// Billionaires json url
private ProgressDialog pDialog;
private List<WorldsBillionaires> worldsBillionairesList = new ArrayList<WorldsBillionaires>();
private ListView listView;
private CustomListAdapterHotel adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_hotel);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapterHotel(this, worldsBillionairesList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest billionaireReq = new JsonArrayRequest("http://192.168.247.1/AdminBihar/getHotel.php?zone="+methods.zone,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
WorldsBillionaires worldsBillionaires = new WorldsBillionaires();
worldsBillionaires.setHotel_Name(obj.getString("hotel_name"));
worldsBillionaires.setThumbnailUrl(obj.getString("image"));
worldsBillionaires.setHotel_Zone(obj.getString("zone"));
worldsBillionaires.setContact_Person(obj.getString("contact_person"));
worldsBillionaires.setContact_Number(obj.getString("contact_number"));
worldsBillionaires.setBtc_Direct(obj.getString("btc_direct"));
// adding Billionaire to worldsBillionaires array
worldsBillionairesList.add(worldsBillionaires);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(billionaireReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
so after you get json data, in activity that shows your list do something like this:
public class DisplayListView extends AppCompatActivity {
ListView listView;
protected void onCreate(){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_list_view);
listView = (ListView) findViewById(R.id.listview);
hotelAdapter = new CustomListAdapterHotel (this, R.layout.row_layout);
listView.setAdapter(hotelAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Model stuff = (Model) hotelAdapter.getItem(position);
String hotelName = stuff.getHotel_Name();
Toast.makeText(getApplicationContext(), hotelName, Toast.LENGTH_SHORT).show();
}
});
there, this worked for me :)

How to implement coverflow layout from existing gridview images

i am using eclipse.
Basically what i am trying to implement is that , that i have a gridView which is fetching images from mysql database dynamically using JSON.
Now , instead of gridview i want to show them as coverflow view.
I have searched through the internet , but was not able to find any library or example for dynamic images , i only found for static images stored in the app itself and not on external database.
My code are as follows:-
MainActivity.java:-
public class MainActivity extends Activity implements OnClickListener {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://eventassociate.com/wedding/photomania";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private PullToRefreshGridView mPullRefreshGridView;
private GridView gridView;
private CustomListAdapter adapter;
ImageButton blackcapture;
private static int RESULT_LOAD_IMAGE = 1;
String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.gallary_activity_main);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.list);
gridView = mPullRefreshGridView.getRefreshableView();
mPullRefreshGridView.setOnRefreshListener(new OnRefreshListener2<GridView>() {
#Override
public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
adapter.notifyDataSetChanged();
gridView.setAdapter(adapter);
gridView.invalidateViews();
mPullRefreshGridView.onRefreshComplete();
}
adapter = new CustomListAdapter(this, movieList);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Movie m5 = movieList.get(position);
Intent i = new Intent(getApplicationContext(),
FullImageActivity.class);
i.putExtra("movieobject", m5);
startActivity(i);
}
});
Adapter Class:-
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.gallary_list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
// ...............................................
TextView title = (TextView) convertView.findViewById(R.id.title);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
return convertView;
}
Movie.java:-
public class Movie implements Parcelable{
private String title,thumbnailUrl;
public Movie() {
// TODO Auto-generated constructor stub
}
public Movie(String name, String thumbnailUrl
) {
this.title = name;
this.thumbnailUrl = thumbnailUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = "http://eventassociate.com/wedding/"+thumbnailUrl;
}
// Parcelling part
public Movie(Parcel in){
String[] data = new String[2];
in.readStringArray(data);
this.title = data[0];
this.thumbnailUrl = data[1];
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.title,
this.thumbnailUrl,
});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
I successfully implemented this as GridView , but i am facing trouble in implementing this as coverflow design or something like that.
I searched on the net and i find this code , but only for static images:-
public class SimpleExample extends Activity {
// =============================================================================
// Child views
// =============================================================================
private FancyCoverFlow fancyCoverFlow;
// =============================================================================
// Supertype overrides
// =============================================================================
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.fancyCoverFlow = (FancyCoverFlow) this.findViewById(R.id.fancyCoverFlow);
this.fancyCoverFlow.setAdapter(new FancyCoverFlowSampleAdapter());
this.fancyCoverFlow.setUnselectedAlpha(1.0f);
this.fancyCoverFlow.setUnselectedSaturation(0.0f);
this.fancyCoverFlow.setUnselectedScale(0.5f);
this.fancyCoverFlow.setSpacing(50);
this.fancyCoverFlow.setMaxRotation(0);
this.fancyCoverFlow.setScaleDownGravity(0.2f);
this.fancyCoverFlow.setActionDistance(FancyCoverFlow.ACTION_DISTANCE_AUTO);
}
// =============================================================================
// Private classes
// =============================================================================
}
Adapter.java:-
public class FancyCoverFlowSampleAdapter extends FancyCoverFlowAdapter {
// =============================================================================
// Private members
// =============================================================================
private int[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5, R.drawable.image6,};
// =============================================================================
// Supertype overrides
// =============================================================================
#Override
public int getCount() {
return images.length;
}
#Override
public Integer getItem(int i) {
return images[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getCoverFlowItem(int i, View reuseableView, ViewGroup viewGroup) {
ImageView imageView = null;
if (reuseableView != null) {
imageView = (ImageView) reuseableView;
} else {
imageView = new ImageView(viewGroup.getContext());
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setLayoutParams(new FancyCoverFlow.LayoutParams(300, 400));
}
imageView.setImageResource(this.getItem(i));
return imageView;
}
}
Can someone help me , in solving my problem.
Thanks.
My final code with coverflow:-
MainActivity:-
public class MainActivity extends Activity implements OnClickListener {
// Log tag
private static final String TAG = album.MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://eventassociate.com/wedding/androidadminimages";
private ProgressDialog pDialog;
private List<Moviealbum> movieList = new ArrayList<Moviealbum>();
private FancyCoverFlow fancyCoverFlow;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.album_activity_main);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
this.fancyCoverFlow = (FancyCoverFlow) this.findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
this.fancyCoverFlow.setAdapter(new CustomListAdapter(this, movieList));
this.fancyCoverFlow.setUnselectedAlpha(1.0f);
this.fancyCoverFlow.setUnselectedSaturation(0.0f);
this.fancyCoverFlow.setUnselectedScale(0.5f);
this.fancyCoverFlow.setSpacing(50);
this.fancyCoverFlow.setMaxRotation(0);
this.fancyCoverFlow.setScaleDownGravity(0.2f);
this.fancyCoverFlow.setActionDistance(FancyCoverFlow.ACTION_DISTANCE_AUTO);
fancyCoverFlow.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Moviealbum m5 = movieList.get(position);
Intent i = new Intent(getApplicationContext(),album.
FullImageActivity.class);
i.putExtra("movieobject", m5);
startActivity(i);
}
});
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Moviealbum movie = new Moviealbum();
movie.setTitle(obj.getString("no"));
movie.setThumbnailUrl(obj.getString("alinks"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue...................................
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
AdapterClass :-
public class CustomListAdapter extends FancyCoverFlowAdapter {
private Activity activity;
private LayoutInflater inflater;
List<Moviealbum> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Moviealbum> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getCoverFlowItem(int position, View reuseableView, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (reuseableView == null)
reuseableView = inflater.inflate(R.layout.gallary_list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) reuseableView
.findViewById(R.id.thumbnail);
// ...............................................
TextView title = (TextView) reuseableView.findViewById(R.id.title);
// getting movie data for the row
Moviealbum m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
return reuseableView;
}
The app runs fine , but after loading blank screen is shown with no images.
Logcat:-
Your issue isn't with the CoverFlow code, but rather where you're doing your network operation. On app load, begin your network request for your JSON payload, show a spinner to show the app is loading, and populate your Adapter once your images are loaded. I'm assuming you have network code already given your GridView implementation? Let me know if I've missed something. I hope that helps!
EDIT:
Once you've added images to your Adapter make sure you call notifyDataSetChanged() to tell your adapter to reload its views.
EDIT 2:
Look at this line here:
this.fancyCoverFlow.setAdapter(new CustomListAdapter(this, movieList));
You're passing a new CustomListAdapter rather than passing in your adapter variable. Try fixing that and let me know if it works.

Categories

Resources