RSS Feeder Android Application - rss

I'm building android app for Show RSS feeds, in one activity ,
I write the RSS Link in EditText and click button, then appear the RSS feeds (the news).
When i enter the RSS link and click the button in the first time the appear the news normally , but my problem is when I Enter a new link & press button: the news of the new link appear under the old News (news of the first link i have been entered in the EditText).
But I want to erase the old news and appear the RSS feed of the new link when i press button.
Any idea?
Thanks in advance.
My code:
In MainActivity:
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private static String rss_url = "http://www.thehindu.com/news/cities/chennai/chen-health/?service=rss";
ProgressDialog progressDialog;
Handler handler = new Handler();
RSSListView list;
RSSListAdapter adapter;
ArrayList<RSSNewsItem> newsItemList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
list = new RSSListView(this);
adapter = new RSSListAdapter(this);
list.setAdapter(adapter);
list.setOnDataSelectionListener(new OnDataSelectionListener() {
public void onDataSelected(AdapterView parent, View v,
int position, long id) {
RSSNewsItem curItem = (RSSNewsItem) adapter.getItem(position);
String curTitle = curItem.getTitle();
Toast.makeText(getApplicationContext(),
"Selected : " + curTitle, 1000).show();
}
});
newsItemList = new ArrayList<RSSNewsItem>();
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
mainLayout.addView(list, params);
final EditText edit01 = (EditText) findViewById(R.id.edit01);
edit01.setText(rss_url);
Button show_btn = (Button) findViewById(R.id.show_btn);
show_btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String inputStr = edit01.getText().toString();
showRSS(inputStr);
}
});
}
private void showRSS(String urlStr) {
try {
progressDialog = ProgressDialog.show(this, "RSS Refresh",
"RSS Lodeing..", true, true);
RefreshThread thread = new RefreshThread(urlStr);
thread.start();
} catch (Exception e) {
Log.e(TAG, "Error", e);
}
}
class RefreshThread extends Thread {
String urlStr;
public RefreshThread(String str) {
urlStr = str;
}
public void run() {
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
URL urlForHttp = new URL(urlStr);
InputStream instream = getInputStreamUsingHTTP(urlForHttp);
// parse
Document document = builder.parse(instream);
int countItem = processDocument(document);
Log.d(TAG, countItem + " news item processed.");
// post for the display of fetched RSS info.
handler.post(updateRSSRunnable);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public InputStream getInputStreamUsingHTTP(URL url) throws Exception {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
int resCode = conn.getResponseCode();
Log.d(TAG, "Response Code : " + resCode);
InputStream instream = conn.getInputStream();
return instream;
}
private int processDocument(Document doc) {
newsItemList.clear();
Element docEle = doc.getDocumentElement();
NodeList nodelist = docEle.getElementsByTagName("item");
int count = 0;
if ((nodelist != null) && (nodelist.getLength() > 0)) {
for (int i = 0; i < nodelist.getLength(); i++) {
RSSNewsItem newsItem = dissectNode(nodelist, i);
if (newsItem != null) {
newsItemList.add(newsItem);
count++;
}
}
}
return count;
}
private RSSNewsItem dissectNode(NodeList nodelist, int index) {
RSSNewsItem newsItem = null;
try {
Element entry = (Element) nodelist.item(index);
Element title = (Element) entry.getElementsByTagName("title").item(
0);
Element link = (Element) entry.getElementsByTagName("link").item(0);
Element description = (Element) entry.getElementsByTagName(
"description").item(0);
NodeList pubDataNode = entry.getElementsByTagName("pubDate");
if (pubDataNode == null) {
pubDataNode = entry.getElementsByTagName("dc:date");
}
Element pubDate = (Element) pubDataNode.item(0);
Element author = (Element) entry.getElementsByTagName("author")
.item(0);
Element category = (Element) entry.getElementsByTagName("category")
.item(0);
String titleValue = null;
if (title != null) {
Node firstChild = title.getFirstChild();
if (firstChild != null) {
titleValue = firstChild.getNodeValue();
}
}
String linkValue = null;
if (link != null) {
Node firstChild = link.getFirstChild();
if (firstChild != null) {
linkValue = firstChild.getNodeValue();
}
}
String descriptionValue = null;
if (description != null) {
Node firstChild = description.getFirstChild();
if (firstChild != null) {
descriptionValue = firstChild.getNodeValue();
}
}
String pubDateValue = null;
if (pubDate != null) {
Node firstChild = pubDate.getFirstChild();
if (firstChild != null) {
pubDateValue = firstChild.getNodeValue();
}
}
String authorValue = null;
if (author != null) {
Node firstChild = author.getFirstChild();
if (firstChild != null) {
authorValue = firstChild.getNodeValue();
}
}
String categoryValue = null;
if (category != null) {
Node firstChild = category.getFirstChild();
if (firstChild != null) {
categoryValue = firstChild.getNodeValue();
}
}
Log.d(TAG, "item node : " + titleValue + ", " + linkValue + ", "
+ descriptionValue + ", " + pubDateValue + ", "
+ authorValue + ", " + categoryValue);
newsItem = new RSSNewsItem(titleValue, linkValue, descriptionValue,
pubDateValue, authorValue, categoryValue);
} catch (DOMException e) {
e.printStackTrace();
}
return newsItem;
}
Runnable updateRSSRunnable = new Runnable() {
public void run() {
try {
Resources res = getResources();
Drawable rssIcon = res.getDrawable(R.drawable.rss_icon);
for (int i = 0; i < newsItemList.size(); i++) {
RSSNewsItem newsItem = (RSSNewsItem) newsItemList.get(i);
newsItem.setIcon(rssIcon);
adapter.addItem(newsItem);
}
adapter.notifyDataSetChanged();
progressDialog.dismiss();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
#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;
}
}
and in OnDataSelectionListener class:
public interface OnDataSelectionListener {
public void onDataSelected(AdapterView parent, View v, int position, long id);
}
and in RSSListAdapter:
public class RSSListAdapter extends BaseAdapter {
private Context mContext;
private List<RSSNewsItem> mItems = new ArrayList<RSSNewsItem>();
public RSSListAdapter(Context context) {
mContext = context;
}
public void addItem(RSSNewsItem it) {
mItems.add(it);
}
public void setListItems(List<RSSNewsItem> lit) {
mItems = lit;
}
public int getCount() {
return mItems.size();
}
public Object getItem(int position) {
return mItems.get(position);
}
public boolean areAllItemsSelectable() {
return false;
}
public boolean isSelectable(int position) {
return true;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
RSSNewsItemView itemView;
if (convertView == null) {
itemView = new RSSNewsItemView(mContext, mItems.get(position));
} else {
itemView = (RSSNewsItemView) convertView;
itemView.setIcon(mItems.get(position).getIcon());
itemView.setText(0, mItems.get(position).getTitle());
itemView.setText(1, mItems.get(position).getPubDate());
itemView.setText(2, mItems.get(position).getCategory());
itemView.setText(3, mItems.get(position).getDescription());
}
return itemView;
}
}
and in RSSListView class:
public class RSSListView extends ListView {
/**
* DataAdapter for this instance
*/
private RSSListAdapter adapter;
/**
* Listener for data selection
*/
private OnDataSelectionListener selectionListener;
public RSSListView(Context context) {
super(context);
init();
}
public RSSListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
/**
* set initial properties
*/
private void init() {
// set OnItemClickListener for processing OnDataSelectionListener
setOnItemClickListener(new OnItemClickAdapter());
}
/**
* set DataAdapter
*
* #param adapter
*/
public void setAdapter(BaseAdapter adapter) {
super.setAdapter(adapter);
}
/**
* get DataAdapter
*
* #return
*/
public BaseAdapter getAdapter() {
return (BaseAdapter) super.getAdapter();
}
/**
* set OnDataSelectionListener
*
* #param listener
*/
public void setOnDataSelectionListener(OnDataSelectionListener listener) {
this.selectionListener = listener;
}
/**
* get OnDataSelectionListener
*
* #return
*/
public OnDataSelectionListener getOnDataSelectionListener() {
return selectionListener;
}
class OnItemClickAdapter implements OnItemClickListener {
public OnItemClickAdapter() {
}
public void onItemClick(AdapterView parent, View v, int position,
long id) {
if (selectionListener == null) {
return;
}
// get row and column
int rowIndex = -1;
int columnIndex = -1;
// call the OnDataSelectionListener method
selectionListener.onDataSelected(parent, v, position, id);
}
}
}
and in RSSNewsItem class:
public class RSSNewsItem {
private String title;
private String link;
private String description;
private String pubDate;
private String author;
private String category;
private Drawable mIcon;
/**
* Initialize with icon and data array
*/
public RSSNewsItem() {
}
/**
* Initialize with icon and strings
*/
public RSSNewsItem(String title, String link, String description, String pubDate, String author, String category) {
this.title = title;
this.link = link;
this.description = description;
this.pubDate = pubDate;
this.author = author;
this.category = category;
}
/**
* Set icon
*
* #param icon
*/
public void setIcon(Drawable icon) {
mIcon = icon;
}
/**
* Get icon
*
* #return
*/
public Drawable getIcon() {
return mIcon;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
/**
* Compare with the input object
*
* #param other
* #return
*/
public int compareTo(RSSNewsItem other) {
if (title.equals(other.getTitle())) {
return -1;
} else if (link.equals(other.getLink())) {
return -1;
} else if (description.equals(other.getDescription())) {
return -1;
} else if (pubDate.equals(other.getPubDate())) {
return -1;
} else if (author.equals(other.getAuthor())) {
return -1;
} else if (category.equals(other.getCategory())) {
return -1;
}
return 0;
}
}
Finally, in RSSNewsItemView class:
public class RSSNewsItem {
private String title;
private String link;
private String description;
private String pubDate;
private String author;
private String category;
private Drawable mIcon;
/**
* Initialize with icon and data array
*/
public RSSNewsItem() {
}
/**
* Initialize with icon and strings
*/
public RSSNewsItem(String title, String link, String description, String pubDate, String author, String category) {
this.title = title;
this.link = link;
this.description = description;
this.pubDate = pubDate;
this.author = author;
this.category = category;
}
/**
* Set icon
*
* #param icon
*/
public void setIcon(Drawable icon) {
mIcon = icon;
}
/**
* Get icon
*
* #return
*/
public Drawable getIcon() {
return mIcon;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
/**
* Compare with the input object
*
* #param other
* #return
*/
public int compareTo(RSSNewsItem other) {
if (title.equals(other.getTitle())) {
return -1;
} else if (link.equals(other.getLink())) {
return -1;
} else if (description.equals(other.getDescription())) {
return -1;
} else if (pubDate.equals(other.getPubDate())) {
return -1;
} else if (author.equals(other.getAuthor())) {
return -1;
} else if (category.equals(other.getCategory())) {
return -1;
}
return 0;
}
}

I think you would need to call adapter.clear() and invalidate your list again using adapter.notifyDataSet() when you click the button.

Related

Save data from fragment to custom session

I am creating a project in which I am using navigation drawer and on navigation item click it opens a login page and after login it movies to my main activity. Now, I want to save my login details and all data in my custom shared preference from the fragment. After that it on app restarts and I go to navigation login items it should check if the user is already logged in then it should move to an activity otherwise it should run my login fragment
my login fragment
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
CDSMainViewModel =
ViewModelProviders.of(this).get(CDP_MainViewModel.class);
View root = inflater.inflate(R.layout.fragment_cdplogin, container, false);
context = container.getContext();
context = getActivity().getApplicationContext();
session = new Session(context);
if (session.isLoggedIn()) {
Intent itra = new Intent(getActivity().getApplicationContext(), Verification_Activity.class);
startActivity(itra);
getActivity().finish();
}
else{
login_button = root.findViewById(R.id.button_click_login);
edit1 = root.findViewById(R.id.input_username);
edit2 = root.findViewById(R.id.input_password);
layout_1 = root.findViewById(R.id.usnamelayout);
layout_2 = root.findViewById(R.id.password_layout);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
return root;
}
private void Login_data() {
String URL = "http://117.240.196.238:8080/api/cdp/getAuth";
Log.i("response", URL);
StringRequest jsonObjRequest = new StringRequest(
Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("response_login", response);
parseData1(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley", "Error: " + error.getMessage());
showServerConnectionError();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("AuthID", name);
params.put("AuthPwd", password);
return params;
}
};
RequestQueue queue = SingletonRequestQueue.getInstance(getActivity().getApplicationContext()).getRequestQueue();
queue.add(jsonObjRequest);
}
private void parseData1(String response){
try {
JSONObject json = new JSONObject(response);
int success = json.getInt("success");
String msg = json.getString("message");
if(success == 1){
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
JSONArray recData = json.getJSONArray("data");
for (int i = 0; i < recData.length(); i++) {
JSONObject c = recData.getJSONObject(i);
String uname = name;
String upass = password;
String emp_id = c.getString("emp_id");
String empname = c.getString("EmpName");
String office = c.getString("OfficeNameFull");
String desig = c.getString("DesignationName");
String mobile = c.getString("EmpMobile");
String office_code = c.getString("OfficeCode");
String OfficeType = c.getString("OfficeType");
String district = c.getString("DistrictCode");
String DistrictName = c.getString("DistrictName");
String designationCode = c.getString("designationCode");
String DesignationName1 = c.getString("DesignationName1");
String DesigShortName = c.getString("DesigShortName");
Log.i("session",district);
//Here my loginsession is not working its not saving my data in my session..
Session.getInstance(getContext()).loginsession(emp_id,uname,upass,empname,office,desig,mobile,office_code,OfficeType,district,DistrictName,designationCode,DesignationName1,DesigShortName);
// String email = SessionManager.getInstance(context).getUserEmail();
// session.loginsession(emp_id,uname,upass,empname,office,desig,mobile,office_code,OfficeType,district,DistrictName,designationCode,DesignationName1,DesigShortName);
Intent its12 = new Intent(getActivity().getApplicationContext(), Verification_Activity.class);
startActivity(its12);
getActivity().overridePendingTransition(R.anim.from_right, R.anim.slide_to_left);
getActivity().finish();
}
} else {
Toast.makeText(context,msg, Toast.LENGTH_LONG).show();
}
}catch(Exception ex){
}
}
}
//Session manager class
package com.example.agridept.domain;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import com.example.agridept.ui.CDP_login.CDP_MainFragment;
public class Session {
private static Session jInstance;
SharedPreferences preferences;
SharedPreferences.Editor editor;
Context context;
int PRIVATE_MODE = 0;
private static final String IS_LOGIN = "IsLoggedIn";
private static final String PREF_NAME = "AndroidHivePref";
String emp_id1,username1,password1 ,empname1 , office1 , desig1, mobile1, office_code1, OfficeType1 , district1 ,DistrictName1 , designationCode1, DesignationName11 , DesigShortName1;
public Session(Context context){
this.context = context;
preferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = preferences.edit();
}
public void loginsession(String emp_id,String username,String password11 ,String empname ,String office ,String desig,String mobile,String office_code,String OfficeType ,String district ,String DistrictName ,String designationCode,String DesignationName1 ,String DesigShortName){
editor.putBoolean(IS_LOGIN, true);
editor.putString(emp_id1,emp_id);
editor.putString(username1,username);
editor.putString(password1,password11);
editor.putString(empname1,empname);
editor.putString(office1,office);
editor.putString(desig1,desig);
editor.putString(mobile1,mobile);
editor.putString(office_code1,office_code);
editor.putString(OfficeType1,OfficeType);
editor.putString(district1,district);
editor.putString(DistrictName1,DistrictName);
editor.putString(designationCode1,designationCode);
editor.putString(DesignationName11,DesignationName1);
editor.putString(DesigShortName1,DesigShortName);
}
public boolean isLoggedIn() {
return preferences.getBoolean(IS_LOGIN, false);
}
public void logoutUser() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(context, CDP_MainFragment.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
context.startActivity(i);
}
public void clearinfo() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
}
public SharedPreferences getPreferences() {
return preferences;
}
public void setPreferences(SharedPreferences preferences) {
this.preferences = preferences;
}
public SharedPreferences.Editor getEditor() {
return editor;
}
public void setEditor(SharedPreferences.Editor editor) {
this.editor = editor;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public int getPRIVATE_MODE() {
return PRIVATE_MODE;
}
public void setPRIVATE_MODE(int PRIVATE_MODE) {
this.PRIVATE_MODE = PRIVATE_MODE;
}
public static String getIsLogin() {
return IS_LOGIN;
}
public static String getPrefName() {
return PREF_NAME;
}
public String getEmp_id1() {
return emp_id1;
}
public void setEmp_id1(String emp_id1) {
this.emp_id1 = emp_id1;
}
public String getPassword1() {
return password1;
}
public void setPassword1(String password1) {
this.password1 = password1;
}
public String getEmpname1() {
return empname1;
}
public void setEmpname1(String empname1) {
this.empname1 = empname1;
}
public String getOffice1() {
return office1;
}
public void setOffice1(String office1) {
this.office1 = office1;
}
public String getDesig1() {
return desig1;
}
public void setDesig1(String desig1) {
this.desig1 = desig1;
}
public String getMobile1() {
return mobile1;
}
public void setMobile1(String mobile1) {
this.mobile1 = mobile1;
}
public String getOffice_code1() {
return office_code1;
}
public void setOffice_code1(String office_code1) {
this.office_code1 = office_code1;
}
public String getOfficeType1() {
return OfficeType1;
}
public void setOfficeType1(String officeType1) {
OfficeType1 = officeType1;
}
public String getDistrict1() {
return district1;
}
public void setDistrict1(String district1) {
this.district1 = district1;
}
public String getDistrictName1() {
return DistrictName1;
}
public void setDistrictName1(String districtName1) {
DistrictName1 = districtName1;
}
public String getDesignationCode1() {
return designationCode1;
}
public void setDesignationCode1(String designationCode1) {
this.designationCode1 = designationCode1;
}
public String getDesignationName11() {
return DesignationName11;
}
public void setDesignationName11(String designationName11) {
DesignationName11 = designationName11;
}
public String getDesigShortName1() {
return DesigShortName1;
}
public void setDesigShortName1(String desigShortName1) {
DesigShortName1 = desigShortName1;
}
public static synchronized Session getInstance(Context context) {
if (jInstance != null) {
return jInstance;
} else {
jInstance = new Session(context);
return jInstance;
}
}
}

Can not read data from firebase as List in android

I read many articles but still my problem is continuing, while fetching data from firebase as list. could you please help me on this.
Error: com.google.firebase.database.DatabaseException: Can't convert
object of type java.lang.String to type SubCategoryLoad Object
Firebase database image
--> Loading data from firebase:
mSubCategoryDatabaseRef = FirebaseDatabase.getInstance().getReference("user_post_add_database_ref").child("yeswanth599").child(mCategoryNameReceive);
mSubCategoryDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
GenericTypeIndicator<Map<String,SubCategoryLoad>> genericTypeIndicator=new GenericTypeIndicator<Map<String,SubCategoryLoad>>(){};
(-->Error Showing in this Line) Map<String,SubCategoryLoad> map=(Map<String, SubCategoryLoad>)postSnapshot.getValue(genericTypeIndicator);
assert map != null;
mSubCategoryLoad=new ArrayList<>(map.values());
}
mSubCategoryAdapter = new SubCategoryDisplayAdapter(getContext(), mSubCategoryLoad);
mSubCategoryRecyclerView.setAdapter(mSubCategoryAdapter);
mSubCategoryProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mSubCategoryProgressCircle.setVisibility(View.INVISIBLE);
}
});
--> SubCategoryLoad.Class
public class SubCategoryLoad {
private String mUserPostAddress;
private String mUserPostBusinessEndTime;
private String mUserPostBusinessSelectedCity;
private String mUserPostBusinessSelectedCountry;
private String mUserPostBusinessStartTime;
private String mUserPostCategory;
private String mUserPostEmail;
private List<UserPostAdsImages> mUserPostImages;
private String mUserPostName;
private String mUserPostPhonenumber;
private List<UserPostAdsLanguages> mUserPostSupportingLanguage;
private String mUserPostWebsite;
public SubCategoryLoad() {
//empty constructor needed
}
public SubCategoryLoad(String userPostAddress, String userPostBusinessEndTime,
String userPostBusinessSelectedCity, String userPostBusinessSelectedCountry,
String userPostBusinessStartTime, String userPostCategory,
String userPostEmail, List<UserPostAdsImages> userPostImages,
String userPostName, String userPostPhonenumber,
List<UserPostAdsLanguages> userPostSupportingLanguage, String userPostWebsite
) {
mUserPostAddress = userPostAddress;
mUserPostBusinessEndTime = userPostBusinessEndTime;
mUserPostBusinessSelectedCity = userPostBusinessSelectedCity;
mUserPostBusinessSelectedCountry = userPostBusinessSelectedCountry;
mUserPostBusinessStartTime = userPostBusinessStartTime;
mUserPostCategory = userPostCategory;
mUserPostEmail = userPostEmail;
mUserPostImages = userPostImages;
mUserPostName = userPostName;
mUserPostPhonenumber = userPostPhonenumber;
mUserPostSupportingLanguage = userPostSupportingLanguage;
mUserPostWebsite = userPostWebsite;
}
public void setUserPostAddress(String userPostAddress) {
this.mUserPostAddress = userPostAddress;
}
public void setUserPostBusinessEndTime(String userPostBusinessEndTime) {
this.mUserPostBusinessEndTime = userPostBusinessEndTime;
}
public void setUserPostBusinessSelectedCity(String userPostBusinessSelectedCity) {
this.mUserPostBusinessSelectedCity = userPostBusinessSelectedCity;
}
public void setUserPostBusinessSelectedCountry(String userPostBusinessSelectedCountry) {
this.mUserPostBusinessSelectedCountry = userPostBusinessSelectedCountry;
}
public void setUserPostBusinessStartTime(String userPostBusinessStartTime) {
this.mUserPostBusinessStartTime = userPostBusinessStartTime;
}
public void setUserPostCategory(String userPostCategory) {
this.mUserPostCategory = userPostCategory;
}
public void setUserPostEmail(String userPostEmail) {
this.mUserPostEmail = userPostEmail;
}
public void setUserPostImages(List<UserPostAdsImages> userPostImages) {
this.mUserPostImages = userPostImages;
}
public void setUserPostName(String userPostName) {
this.mUserPostName = userPostName;
}
public void setUserPostPhonenumber(String userPostPhonenumber) {
this.mUserPostPhonenumber = userPostPhonenumber;
}
public void setUserPostSupportingLanguage(List<UserPostAdsLanguages> userPostSupportingLanguage) {
this.mUserPostSupportingLanguage = userPostSupportingLanguage;
}
public void setUserPostWebsite(String userPostWebsite) {
this.mUserPostWebsite = userPostWebsite;
}
public String getUserPostAddress() {
return mUserPostAddress;
}
public String getUserPostBusinessEndTime() {
return mUserPostBusinessEndTime;
}
public String getUserPostBusinessSelectedCity() {
return mUserPostBusinessSelectedCity;
}
public String getUserPostBusinessSelectedCountry() {
return mUserPostBusinessSelectedCountry;
}
public String getUserPostBusinessStartTime() {
return mUserPostBusinessStartTime;
}
public String getUserPostCategory() {
return mUserPostCategory;
}
public String getUserPostEmail() {
return mUserPostEmail;
}
public List<UserPostAdsImages> getUserPostImages() {
return mUserPostImages;
}
public String getUserPostName() {
return mUserPostName;
}
public String getUserPostPhonenumber() {
return mUserPostPhonenumber;
}
public List<UserPostAdsLanguages> getUserPostSupportingLanguage() {
return mUserPostSupportingLanguage;
}
public String getUserPostWebsite() {
return mUserPostWebsite;
}
}
--> SubCategoryDisplayAdapter.class
SubCategoryLoad subCategoryLoadCurrent = mSubCategoryLoad.get(position);
holder.mSubCategoryAdsTitle.setText(subCategoryLoadCurrent.getUserPostName());
holder.mSubCategoryAdsSupportingLanguagesList.setText("English,Japanese");
//Log.i(TAG, "message:"+subCategoryLoadCurrent.getUserPostImages().get(0).getUserPostImageList());
Glide.with(mContext)
.load(subCategoryLoadCurrent.getUserPostImages().get(0).getUserPostImageList())
.into(holder.mSubCategoryAdsImage);
Thanks & Regards,
Yeswanth.
I used to have the same issue with my parsing and the problem was instead of a list of custom objects i was supposed to be using a Map like this
private Map<String,Boolean>
That field in Firebase contains a key and a state (True or False).
Also you can check the code on the docs to see how they parse these objects.
https://firebase.google.com/docs/database/android/read-and-write?authuser=0#read_data_once

Realm Array of Strings in Android

I have been trying to store an array of strings in Realm database programmatically as given below:
Model Class:
public class Station extends RealmObject {
private String name;
// ... Generated getters and setters ...
}
Saving Data:
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Station station1 = realm.createObject(Station.class)
station1.setName(name1);
Station station2 = realm.createObject(Station.class)
station2.setName(name2);
//goes on till station8000
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
// ...
});
Is there an alternate best way for this?
Why yes of course there is
public class Station extends RealmObject {
private String name;
// ... Generated getters and setters ...
}
and
// field variable
RealmResults<Station> stations;
// field variable
RealmChangeListener<RealmResults<Station>> changeListener = new RealmChangeListener<RealmResults<Station>>() {
#Override
public void onChange(RealmResults<Station> results) {
// handle onSuccess()
}
}
and
stations = realm.where(Station.class).findAll();
stations.addChangeListener(changeListener);
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Station station = new Station();
for(String stationName : listOfStationNames) {
station.setName(stationName);
realm.insert(station);
}
}
});
EDIT: Check out this sexy spinner.
public class DropdownSpinnerAdapter
extends BaseAdapter
implements SpinnerAdapter {
private static final String TAG = "DropdownSpinnerAdapter";
private boolean isItemSelected;
RealmResults<Station> content;
public ResultDropdownSpinnerAdapter(RealmResults<Station> objects) {
this.content = objects;
}
#Override
public int getCount() {
if(content == null || !content.isValid()) {
return 1;
}
return content.size() + 1;
}
#Override
public String getItem(int position) {
if(position <= 0) {
return "";
}
return content.get(position - 1);
}
#Override
public long getItemId(int position) {
return position;
}
public int findPosition(Station selectedItem) {
for(int i = 0, s = content.size(); i < s; i++) {
Station item = content.get(i);
if(item.equals(selectedItem)) {
return i + 1;
}
}
return 0;
}
static class ViewHolder {
TextView textView;
ImageView imageView;
public ViewHolder(View convertView) {
textView = ButterKnife.findById(convertView, R.id.dropdown_textview);
imageView = ButterKnife.findById(convertView, R.id.dropdown_arrow);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView != null) {
if(!(convertView instanceof DropdownHeaderView)) {
convertView = null;
}
}
if(convertView == null) {
convertView = LayoutInflater.from(parent.getContext())
.inflate((isItemSelected) ? R.layout.dropdown_selected : R.layout.dropdown,
parent,
false);
ViewHolder viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) convertView.getTag();
viewHolder.textView.setText(getItem(position).getName());
return convertView;
}
public void setItemSelected(boolean selected) {
this.isItemSelected = selected;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if(convertView != null) {
if(!(convertView instanceof DropdownView)) {
convertView = null;
}
}
if(convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.dropdown_noarrow, parent, false);
ViewHolder viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) convertView.getTag();
viewHolder.textView.setText(getItem(position).getName());
return convertView;
}
public void updateContent(RealmResults<Station> content) {
this.content = content;
notifyDataSetChanged();
}
}

Th:each iterate specific variables from a hashSet Thymeleaf Spring MVC

So I"m using Thymeleaf and spring MVC and I have a Course object which has a TreeSet of Posts and the set of posts are similar to a reddit post. I'm trying to represent a set of Posts, on a user homepage that I created. I want the posts to come in chronological order, in a newsfeed sort of way, and I already have the user's courses that they are subscribed to on the model.
My problem is that when I try to iterate through each of the posts I can only pull up the post's id, which looks something like this [com.quizbanks.domain.Post#26], and when I try to show the title, which is the variable for the title of the post I always get a spring processor error.
So here's what my thymeleaf code looks like
<table class="table table-bordered">
<tr th:each="course : ${courses}" th:object="${course}">
<td><span th:text="${course.posts}"></span></td>
</tr>
</table>
and then I tried this, but this gives me the spring processor error
<table class="table table-bordered">
<tr th:each="course : ${courses}" th:object="${course}">
<td><span th:text="${course.posts.title}"></span></td>
</tr>
</table>
So I'm not really sure what to do, if anyone can see my issue and help me out that would be great, thanks in advance.
Also if you want to see my controller code or anything else, let me know and I'll post it.
UPDATE
User Class
package com.quizbanks.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.quizbanks.security.Authorities;
import com.quizbanks.validators.ValidEmail;
#Entity
#Table(name="users")
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class User
{
private Long id;
#ValidEmail
#NotNull
#NotEmpty
private String email;
private String username;
private String password;
private University university;
private Set<Authorities> authorities = new HashSet<>();
private Set<Course> courses = new HashSet<>();
private Set<Post> posts = new HashSet<>();
private Set<Comment> comments = new HashSet<>();
private Set<StudySet> studySet = new HashSet<>();
private Set<Course> myCourses = new HashSet<Course>();
public User ()
{
}
public User(User user)
{
this.id = user.getId();
this.email = user.getEmail();
this.username = user.getUsername();
this.password = user.getPassword();
this.university = user.getUniversity();
this.authorities = user.getAuthorities();
this.courses = user.getCourses();
this.posts = user.getPosts();
this.comments = user.getComments();
this.studySet = user.getStudySet();
this.myCourses = user.getMyCourses();
}
#Id
#GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user", orphanRemoval=true)
public Set<Course> getCourses()
{
return courses;
}
public void setCourses(Set<Course> courses)
{
this.courses = courses;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user", orphanRemoval=true)
public Set<Post> getPosts() {
return posts;
}
public void setPosts(Set<Post> posts) {
this.posts = posts;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
#ManyToOne
public University getUniversity() {
return university;
}
public void setUniversity(University university) {
this.university = university;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="user")
#JsonManagedReference
#JsonIgnoreProperties(allowGetters=true, value = "user" )
public Set<Comment> getComments() {
return comments;
}
public void setComments(Set<Comment> comments) {
this.comments = comments;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="user")
public Set<Authorities> getAuthorities()
{
return authorities;
}
public void setAuthorities(Set<Authorities> authorities)
{
this.authorities = authorities;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user", orphanRemoval=true)
public Set<StudySet> getStudySet() {
return studySet;
}
public void setStudySet(Set<StudySet> studySet) {
this.studySet = studySet;
}
#ManyToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
#JoinTable(name="user_myCourses")
public Set<Course> getMyCourses()
{
return myCourses;
}
public void setMyCourses(Set<Course> myCourses)
{
this.myCourses = myCourses;
}
}
Post Class
package com.quizbanks.domain;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class Course
{
private Long id;
#Size(min=1, max=50)
private String name;
#Size(min=1, max=50)
private String professor;
#Size(min=1, max=50)
private University university;
private Set<Post> posts = new TreeSet<>();
private User user;
#Id
#GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
#ManyToOne
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getProfessor()
{
return professor;
}
public void setProfessor(String professor)
{
this.professor = professor;
}
#ManyToOne
public University getUniversity() {
return university;
}
public void setUniversity(University university) {
this.university = university;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="course")
public Set<Post> getPosts()
{
return posts;
}
public void setPosts(Set<Post> posts)
{
this.posts = posts;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Course other = (Course) obj;
if (id == null)
{
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
Post
package com.quizbanks.domain;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#Entity
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id")
public class Post
{
private Long id;
#Size(min=1, max=140)
#NotNull
private String title;
#Size(min=1, max=1000)
private String content;
private Course course;
private Set<Comment> comments = new TreeSet<>();
private User user;
#Id
#GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#ManyToOne
public Course getCourse()
{
return course;
}
public void setCourse(Course course)
{
this.course = course;
}
#ManyToOne
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="post")
public Set<Comment> getComments() {
return comments;
}
public void setComments(Set<Comment> comments) {
this.comments = comments;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Post other = (Post) obj;
if (id == null)
{
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
Controller
#RequestMapping(value="{user}", method=RequestMethod.GET)
public String userPageGet (ModelMap model, #AuthenticationPrincipal User user)
{
List<User> usersList = userRepo.findAll();
model.addAttribute("usersList", usersList);
List<StudySet> studySets = studySetRepo.findByUser(user);
model.addAttribute("studySets", studySets);
List<Course> courses = courseRepo.findByUser(user);
model.addAttribute("courses", courses);
return "user";
}
${courses} is a list of Courses with posts set inside.
It seems that the problem is that posts is a TreeSet, so you should iterate for each element inside that set to get actual Posts and then get titles.
UPDATE:
List<Course> courses = courseRepo.findByUser(user); here you get all courses for your user. So, next step is to iterate over that list to get all posts:
Set<Post> posts = new TreeSet<>();
for (Course course : courses) {
posts.addAll(course.getPosts);
}
model.addAttribute("posts", posts);

ListView/adapter throwing IndexOutOfBound

I have a listview with a getCount() of 7. I want all 7 items to be shown regardless if any data from my database is available to populate them. If no data is available then an item should just be blank with predetermined text.
When I have not hardcoded 7 database entries beforehand to go into the 7 views then I get an indexoutofbound exception when running the app due to the 7 items not being able to be populated accordingly. This happens in ListMealsAdapter.java when method Meal currentItem = getItem(position); is called and triggers public Meal getItem(int position).
I am looking for a condition statement that I can use for my listview/adapter that can handle an empty database so that the index does not go out of bounds. Also, is the BaseAdapter suited for what I want to do?
MainActivity.java
public class MainActivity extends BaseActivity {
public static final String TAG = "MainActivity";
private ListView mListviewMeals;
private MealDAO mMealDao;
private List<Meal> mListMeals;
private ListMealsAdapter mAdapter;
private SQLiteDatabase mDatabase;
DatabaseHelper mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activateToolbar(1);
// initialize views
initViews();
// fill the dailyListView
mMealDao = new MealDAO(this);
mListMeals = mMealDao.getAllMeals();
mAdapter = new ListMealsAdapter(this, mListMeals, MainActivity.this);
mListviewMeals.setAdapter(mAdapter);
}
private void initViews() {
this.mListviewMeals = (ListView) findViewById(R.id.view_daily_list);
}
ListMealsAdapter.java
public class ListMealsAdapter extends BaseAdapter {
public static final String TAG = "ListMealsAdapter";
Activity mActivity;
private List<Meal> mItems;
private LayoutInflater mInflater;
public ListMealsAdapter(Context context, List<Meal> listMeals, Activity activity) {
super();
mActivity = activity;
this.setItems(listMeals);
this.mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return 7;
}
#Override
public Meal getItem(int position) {
return (getItems() != null && !getItems().isEmpty()) ? getItems().get(position) : null;
}
#Override
public long getItemId(int position) {
return (getItems() != null && !getItems().isEmpty()) ? getItems().get(position).getId() : position;
}
#Override
public View getView(int position, final View convertView, final ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
if (v == null) {
v = mInflater.inflate(R.layout.list_item_daily, parent, false);
holder = new ViewHolder();
holder.txtDescription = (TextView) v.findViewById(R.id.txtBreakfast);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
// fill row data
Meal currentItem = getItem(position);
if (currentItem != null) {
holder.txtDescription.setText(currentItem.getDescription());
}
return v;
}
public List<Meal> getItems() {
return mItems;
}
public void setItems(List<Meal> mItems) {
this.mItems = mItems;
}
class ViewHolder {
TextView txtDescription;
}
}
Meal.java
public class Meal implements Serializable {
public static final String TAG = "Meal";
private static final long serialVersionUID = -7406082437623008161L;
private long mId;
private int mType;
private String mDescription;
public Meal() {
}
public Meal(int type, String description) {
this.mType = type;
this.mDescription = description;
}
public long getId() {
return mId;
}
public void setId(long mId) {
this.mId = mId;
}
public int getType() {
return mType;
}
public void setType(int mType) {
this.mType = mType;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String mDescription) {
this.mDescription = mDescription;
}
}
MealDAO.java
public class MealDAO {
public static final String TAG = "MealDAO";
private SQLiteDatabase mDatabase;
private DatabaseHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = { DatabaseHelper.COLUMN_MEAL_ID,
DatabaseHelper.COLUMN_MEAL_TYPE, DatabaseHelper.COLUMN_MEAL_DESCRIPTION};
public MealDAO(Context context) {
this.mContext = context;
mDbHelper = new DatabaseHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on opening database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public List<Meal> getAllMeals() {
List<Meal> listMeals = new ArrayList<Meal>();
Cursor query = mDatabase.rawQuery("SELECT * from meal", null);
if(query.moveToFirst()) {
do {
// Cycle through all records
Meal meal = cursorToMeal(query);
listMeals.add(meal);
} while(query.moveToNext());
}
return listMeals;
}
public Meal getMealById(long id) {
Cursor cursor = mDatabase.query(DatabaseHelper.TABLE_MEALS, mAllColumns,
DatabaseHelper.COLUMN_MEAL_ID + " = ?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
Meal meal = cursorToMeal(cursor);
return meal;
}
protected Meal cursorToMeal(Cursor cursor) {
Meal meal = new Meal();
meal.setId(cursor.getLong(0));
meal.setType(cursor.getInt(1));
meal.setDescription(cursor.getString(2));
return meal;
}
}
After a LOT of trial and error I finally found an acceptable solution to my problem. What I did was to add a default row to my database for the view items that I wanted to have a predetermined database entry when no data had been entered beforehand.
I then made sure to start at index 2, making sure that index 1 would be reserved for my default value. If the index comes out of bounds then the exception is caught and the default database entry will be added to the array.
public Meal getItem(int position) {
Meal result;
try {
result = (getItems() != null && !getItems().isEmpty()) ? getItems().get(position) : null;
} catch (Exception e) {
Meal default = getItem(0);
return default;
}
return result;
}
Meal currentItem = getItem(position + 1);
if (currentItem != null) {
holder.txtDescription.setText(currentItem.getDescription());
}
With that change things have been running smooth ever since. I hope this can help someone else as well.

Resources