I am creating an android application in which having one listview, inside that listview having expandable listview. When I run the application I'm getting the uncaught remote exception in logcat. Can any one tell me why this error occurs, what I have done wrong in following code?
ListAdapter:
public class Daybook_adapter extends BaseAdapter {
Context context;
private ArrayList<Daybook> entriesdaybook;
private ArrayList<Daybooklist> daybooklists = new ArrayList<Daybooklist>();
private boolean isListScrolling;
private LayoutInflater inflater;
public Daybook_adapter(Context context, ArrayList<Daybook> entriesdaybook) {
this.context = context;
this.entriesdaybook = entriesdaybook;
}
#Override
public int getCount() {
return entriesdaybook.size();
}
#Override
public Object getItem(int i) {
return entriesdaybook.get(i);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.model_daybook, null);
final TextView tv_date = (TextView) convertView.findViewById(R.id.tv_daybook_date);
final TextView tv_cashin = (TextView) convertView.findViewById(R.id.tv_daybook_cashin);
final TextView tv_cashout = (TextView) convertView.findViewById(R.id.tv_daybook_cashout);
final TextView tv_totalamt = (TextView) convertView.findViewById(R.id.daybook_total_amt);
final ImageView img_pdf = (ImageView) convertView.findViewById(R.id.img_printpdf);
LinearLayout emptyy = (LinearLayout) convertView.findViewById(R.id.empty);
ExpandableHeightListView daybookdetailviewlist = (ExpandableHeightListView) convertView.findViewById(R.id.detaillist_daybook);
final Daybook m = entriesdaybook.get(position);
String s = m.getDate();
String[] spiliter = s.split("-");
String year = spiliter[0];
String month = spiliter[1];
String date = spiliter[2];
if (month.startsWith("01")) {
tv_date.setText(date + "Jan" + year);
} else if (month.startsWith("02")) {
tv_date.setText(date + "Feb" + year);
} else if (month.startsWith("03")) {
tv_date.setText(date + "Mar" + year);
} else if (month.startsWith("04")) {
tv_date.setText(date + "Apr" + year);
} else if (month.startsWith("05")) {
tv_date.setText(date + "May" + year);
} else if (month.startsWith("06")) {
tv_date.setText(date + "Jun" + year);
} else if (month.startsWith("07")) {
tv_date.setText(date + "Jul" + year);
} else if (month.startsWith("08")) {
tv_date.setText(date + "Aug" + year);
} else if (month.startsWith("09")) {
tv_date.setText(date + "Sep" + year);
} else if (month.startsWith("10")) {
tv_date.setText(date + "Oct" + year);
} else if (month.startsWith("11")) {
tv_date.setText(date + "Nov" + year);
} else if (month.startsWith("12")) {
tv_date.setText(date + "Dec" + year);
}
tv_cashin.setText("\u20B9" + m.getCashin());
tv_cashout.setText("\u20B9" + m.getCashout());
double one = Double.parseDouble(m.getCashin());
double two = Double.parseDouble(m.getCashout());
double three = one + two;
tv_totalamt.setText("\u20B9" + String.valueOf(three));
DatabaseHandler databaseHandler = new DatabaseHandler(context);
daybooklists = databaseHandler.getAllDaywisedaybookdetails(s);
for (int i = 0; i < daybooklists.size(); i++) {
try {
Daybooklist_adapter adapter = new Daybooklist_adapter(context, daybooklists);
if (adapter != null) {
if (adapter.getCount() > 0) {
emptyy.setVisibility(View.GONE);
daybookdetailviewlist.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
} else {
daybookdetailviewlist.setEmptyView(emptyy);
}
daybookdetailviewlist.setExpanded(true);
daybookdetailviewlist.setFastScrollEnabled(true);
if (!isListScrolling) {
img_pdf.setEnabled(false);
adapter.isScrolling(true);
} else {
img_pdf.setEnabled(true);
adapter.isScrolling(false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
img_pdf.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle(R.string.app_name);
// set dialog message
alertDialogBuilder
.setMessage("Click yes to Print Report for : " + m.getDate())
.setCancelable(true)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
Intent pdfreport = new Intent(context, Activity_Daybookpdf.class);
pdfreport.putExtra("date", m.getDate());
context.startActivity(pdfreport);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
Button nbutton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setTextColor(context.getResources().getColor(R.color.colorAccent));
Button pbutton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
pbutton.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));
pbutton.setPadding(0, 10, 10, 0);
pbutton.setTextColor(Color.WHITE);
return false;
}
});
return convertView;
}
public void setTransactionList(ArrayList<Daybook> newList) {
entriesdaybook = newList;
notifyDataSetChanged();
}
public void isScrolling(boolean isScroll) {
isListScrolling = isScroll;
Log.e("scrollcheck", String.valueOf(isListScrolling));
}
}
Expandable ListAdapter:
public class Daybooklist_adapter extends BaseAdapter {
Context context;
private LayoutInflater inflater;
private ArrayList<Daybooklist> daybooklists;
DatabaseHandler databaseHandler;
boolean isListScrolling;
public Daybooklist_adapter(Context context, ArrayList<Daybooklist> daybooklists) {
this.context = context;
this.daybooklists = daybooklists;
}
#Override
public int getCount() {
return daybooklists.size();
}
#Override
public Object getItem(int i) {
return daybooklists.get(i);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertview == null)
convertview = inflater.inflate(R.layout.model_daybook_listentry, null);
final TextView day_name = (TextView) convertview.findViewById(R.id.tv_daybook_name);
final TextView day_description = (TextView) convertview.findViewById(R.id.tv_daybook_description);
final TextView day_type = (TextView) convertview.findViewById(R.id.tv_daybook_type);
final TextView day_amount = (TextView) convertview.findViewById(R.id.tv_daybook_amount);
final TextView day_usertype = (TextView) convertview.findViewById(R.id.tv_usertype);
final TextView day_time = (TextView) convertview.findViewById(R.id.tv_daybook_time);
final ImageView day_check = (ImageView) convertview.findViewById(R.id.img_doneall);
final TextView daybook_location = (TextView) convertview.findViewById(R.id.tv_daybook_location);
databaseHandler = new DatabaseHandler(context);
final Daybooklist m = daybooklists.get(position);
if (m.getUsertype() != null && !m.getUsertype().isEmpty()) {
if (m.getUsertype().startsWith("farmer") | m.getUsertype().startsWith("singleworker") | m.getUsertype().startsWith("groupworker") | m.getUsertype().startsWith("payvehicle")) {
if (m.getUsertype().startsWith("farmer")) {
day_name.setText(m.getName());
day_description.setText(m.getDescription());
String locat = String.valueOf(databaseHandler.getfarmerlocation(m.getMobileno()));
locat = locat.replaceAll("\\[", "").replaceAll("\\]", "");
Log.e("farmerlocation", locat);
daybook_location.setText(locat);
day_type.setText(m.getType());
if (m.getName() != null && m.getName().startsWith("no")) {
day_name.setText(" ");
} else if (m.getDescription() != null && m.getDescription().startsWith("no")) {
day_description.setText(" ");
}
day_amount.setText("\u20B9" + m.getExtraamt());
if (m.getAmountout().startsWith("0.0") | m.getAmountout().startsWith("0")) {
// day_amount.setTextColor(activity.getResources().getColor(R.color.green));
Log.e("Amountout", m.getAmountout());
day_check.setVisibility(View.INVISIBLE);
} else {
// day_amount.setTextColor(activity.getResources().getColor(R.color.album_title));
Log.e("Amountout", m.getAmountout());
day_check.setVisibility(View.VISIBLE);
}
day_time.setText(m.getCtime());
} else {
day_name.setText(m.getName());
day_description.setText(m.getDescription());
daybook_location.setText(m.getType());
day_type.setText(m.getType());
if (m.getName() != null && m.getName().startsWith("no")) {
day_name.setText(" ");
} else if (m.getDescription() != null && m.getDescription().startsWith("no")) {
day_description.setText(" ");
}
day_amount.setText("\u20B9" + m.getExtraamt());
if (m.getAmountout().startsWith("0.0") | m.getAmountout().startsWith("0")) {
// day_amount.setTextColor(activity.getResources().getColor(R.color.green));
Log.e("Amountout", m.getAmountout());
day_check.setVisibility(View.INVISIBLE);
} else {
// day_amount.setTextColor(activity.getResources().getColor(R.color.album_title));
Log.e("Amountout", m.getAmountout());
day_check.setVisibility(View.VISIBLE);
}
day_time.setText(m.getCtime());
}
} else if (m.getUsertype().startsWith("advancefarmer") | m.getUsertype().startsWith("workeradvance") | m.getUsertype().startsWith("kgroupadvance") | m.getUsertype().startsWith("otherexpense") | m.getUsertype().startsWith("vehicle")) {
if (m.getUsertype().startsWith("advancefarmer")) {
day_name.setText(m.getName());
day_description.setText(m.getDescription());
day_type.setText(m.getType());
String locat = String.valueOf(databaseHandler.getfarmerlocation(m.getMobileno()));
locat = locat.replaceAll("\\[", "").replaceAll("\\]", "");
Log.e("farmerlocation", locat);
daybook_location.setText(locat);
if (m.getName() != null && m.getName().startsWith("no")) {
day_name.setText(" ");
} else if (m.getDescription() != null && m.getDescription().startsWith("no")) {
day_description.setText(" ");
}
Log.e("amountout", m.getAmountout());
day_amount.setText("\u20B9" + m.getAmountout());
day_time.setText(m.getCtime());
} else {
day_name.setText(m.getName());
day_description.setText(m.getType());
day_type.setText(m.getType());
daybook_location.setText(m.getDescription());
if (m.getName() != null && m.getName().startsWith("no")) {
day_name.setText(" ");
} else if (m.getDescription() != null && m.getDescription().startsWith("no")) {
day_description.setText(" ");
}
Log.e("amountout", m.getAmountout());
day_amount.setText("\u20B9" + m.getAmountout());
day_time.setText(m.getCtime());
}
} else if (m.getUsertype().startsWith("buyer")) {
day_name.setText(m.getName());
day_description.setText(m.getDescription());
day_amount.setText("\u20B9" + m.getAmountin());
day_type.setText(" ");
day_time.setText(m.getCtime());
daybook_location.setText(m.getType());
}
if (m.getUsertype().startsWith("farmer")) {
day_usertype.setText("F");
day_usertype.setBackgroundResource(R.drawable.textview_farmer);
} else if (m.getUsertype().startsWith("advancefarmer")) {
day_usertype.setText("FA");
day_usertype.setBackgroundResource(R.drawable.textview_farmer);
} else if (m.getUsertype().startsWith("singleworker")) {
day_usertype.setText("W");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("workeradvance")) {
day_usertype.setText("WA");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("groupworker")) {
day_usertype.setText("G");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("kgroupadvance")) {
day_usertype.setText("GA");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("otherexpense")) {
day_usertype.setText("E");
day_usertype.setBackgroundResource(R.drawable.textview_otherexpense);
} else if (m.getUsertype().startsWith("vehicle")) {
day_usertype.setText("V");
day_usertype.setBackgroundResource(R.drawable.textview_vehicle);
} else if (m.getUsertype().startsWith("gsalary")) {
day_usertype.setText("GS");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("isalary")) {
day_usertype.setText("WS");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("payvehicle")) {
day_usertype.setText("VP");
day_usertype.setBackgroundResource(R.drawable.textview_vehicle);
} else if (m.getUsertype().startsWith("buyer")) {
day_usertype.setText("B");
day_usertype.setBackgroundResource(R.drawable.textview_buyer);
}
}
return convertview;
}
public void isScrolling(boolean isScroll) {
isListScrolling = isScroll;
Log.e("Innerscrollcheck", String.valueOf(isListScrolling));
}
}
Exception:
Uncaught remote exception! (Exceptions are not yet supported across
processes.)
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
at com.android.internal.os.BatteryStatsImpl.updateAllPhoneStateLocked(BatteryStatsImpl.java:3321)
at com.android.internal.os.BatteryStatsImpl.notePhoneSignalStrengthLocked(BatteryStatsImpl.java:3351)
at com.android.server.am.BatteryStatsService.notePhoneSignalStrength(BatteryStatsService.java:395)
at com.android.server.TelephonyRegistry.broadcastSignalStrengthChanged(TelephonyRegistry.java:1448)
at com.android.server.TelephonyRegistry.notifySignalStrengthForSubscriber(TelephonyRegistry.java:869)
at com.android.internal.telephony.ITelephonyRegistry$Stub.onTransact(ITelephonyRegistry.java:184)
at android.os.Binder.execTransact(Binder.java:451)
Thanks in advance.
Related
Intro:
My client require some components across the application like navigationDrawer, toolbar. So I have a MainActivity having two toolbar(top/bottom) and two navigation drawer(left/right). All other screens consist of fragments that I change in MainActivity. I have a little problem that is some of the action are being duplicated.
Cases:
In some fragments when user perform an action i.e.
1: User press "Add To Cart" button and press home button that is in toolbar Bottom, the code of "Add To Cart" button run twice (once clicking button, once going to home screen) so my item is being added to cart twice.
2: In another fragment I have "apply coupon" checkbox when user check that checkbox an AlertDialog appear and when user go to home screen the AlertDialog again appear in the home screen.
I'm simply recreating the main activity on home button press with recreate();
I check the code but can't understand why those actions duplicate. If someone faced the same or a bit similar problem please guide me how to tackle that. Any help would be appreciated.
If I need to show code tell me which part?
Edit:
inside onCreateView of fragment Cart Detail
useCoupon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
createAndShowCustomAlertDialog();
}
}
});
Sequence of this code is Main Activity(Main Fragment)=>Product Frag=>Cart Detail Frag.
Edit 2: MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
this.utils = new Utils(this);
utils.changeLanguage("en");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
this.context = this;
setupToolbar(this);
utils.switchFragment(new MainFrag());
setOnClickListener();
initRightMenuData();
initLeftMenuData();
listAdapter = new ExpandableListAdapter(headerListLeft, hashMapLeft,
false, loggedInIconList);
listViewExpLeft.setAdapter(listAdapter);
if (isLoggedIn()) {
listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
loggedInIconList);
} else {
listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
NotLoggedInIconList);
}
listViewExpRight.setAdapter(listAdapterRight);
enableSingleSelection();
setExpandableListViewClickListener();
setExpandableListViewChildClickListener();
}
private void setOnClickListener() {
myAccountTV.setOnClickListener(this);
checkoutTV.setOnClickListener(this);
discountTV.setOnClickListener(this);
homeTV.setOnClickListener(this);
searchIcon.setOnClickListener(this);
cartLayout.setOnClickListener(this);
}
private void setExpandableListViewClickListener() {
listViewExpRight.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition,
long id) {
utils.printLog("GroupClicked", " Id = " + id);
int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
if (!isLoggedIn()) {
if (childCount < 1) {
if (groupPosition == 0) {
utils.switchFragment(new FragLogin());
} else if (groupPosition == 1) {
utils.switchFragment(new FragRegister());
} else if (groupPosition == 2) {
utils.switchFragment(new FragContactUs());
} else {
recreate();
}
drawer.closeDrawer(GravityCompat.END);
}
} else {
if (childCount < 1) {
changeFragment(103 + groupPosition);
drawer.closeDrawer(GravityCompat.END);
}
}
return false;
}
});
listViewExpLeft.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
if (childCount < 1) {
MenuCategory textChild = (MenuCategory) parent.getExpandableListAdapter()
.getGroup(groupPosition);
moveToProductFragment(textChild.getMenuCategoryId());
utils.printLog("InsideChildClick", "" + textChild.getMenuCategoryId());
}
return false;
}
});
}
private void setExpandableListViewChildClickListener() {
listViewExpLeft.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
MenuSubCategory subCategory = (MenuSubCategory) parent.getExpandableListAdapter()
.getChild(groupPosition, childPosition);
moveToProductFragment(subCategory.getMenuSubCategoryId());
utils.printLog("InsideChildClick", "" + subCategory.getMenuSubCategoryId());
return true;
}
});
listViewExpRight.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
String str = parent.getExpandableListAdapter().getGroup(groupPosition).toString();
UserSubMenu userSubMenu = (UserSubMenu) parent.getExpandableListAdapter()
.getChild(groupPosition, childPosition);
if (str.contains("Information") || str.contains("معلومات")) {
Bundle bundle = new Bundle();
bundle.putString("id", userSubMenu.getUserSubMenuCode());
utils.switchFragment(new FragShowText(), bundle);
} else if (str.contains("اللغة") || str.contains("Language")) {
recreate();
} else if (str.contains("دقة") || str.contains("Currency")) {
makeDefaultCurrencyCall(userSubMenu.getUserSubMenuCode());
}
utils.printLog("InsideChildClick", "" + userSubMenu.getUserSubMenuCode());
drawer.closeDrawer(GravityCompat.END);
return false;
}
});
}
private void setupToolbar(Context context) {
ViewCompat.setLayoutDirection(appbarBottom, ViewCompat.LAYOUT_DIRECTION_RTL);
ViewCompat.setLayoutDirection(appbarTop, ViewCompat.LAYOUT_DIRECTION_RTL);
String imgPath = Preferences
.getSharedPreferenceString(appContext, LOGO_KEY, DEFAULT_STRING_VAL);
utils.printLog("Product Image = " + imgPath);
if (!imgPath.isEmpty()) {
Picasso.with(getApplicationContext()).load(imgPath)
.into(logoIcon);
}
logoIcon.setOnClickListener(this);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
actionbarToggle();
drawer.addDrawerListener(mDrawerToggle);
drawerIconLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
drawerIconLeft.setScaleX(1);
drawerIconLeft.setImageResource(R.drawable.ic_arrow_back_black);
}
}
});
drawerIconRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
drawer.openDrawer(GravityCompat.END);
}
}
});
}
private void initViews() {
drawerIconLeft = findViewById(R.id.drawer_icon_left);
drawerIconRight = findViewById(R.id.drawer_icon_right);
logoIcon = findViewById(R.id.logo_icon);
searchIcon = findViewById(R.id.search_icon);
cartLayout = findViewById(R.id.cart_layout);
counterTV = findViewById(R.id.actionbar_notification_tv);
drawer = findViewById(R.id.drawer_layout);
listViewExpLeft = findViewById(R.id.expandable_lv_left);
listViewExpRight = findViewById(R.id.expandable_lv_right);
appbarBottom = findViewById(R.id.appbar_bottom);
appbarTop = findViewById(R.id.appbar_top);
myAccountTV = findViewById(R.id.my_account_tv);
discountTV = findViewById(R.id.disc_tv);
checkoutTV = findViewById(R.id.checkout_tv);
homeTV = findViewById(R.id.home_tv);
searchView = findViewById(R.id.search_view);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
super.onBackPressed();
}
}
private void initRightMenuData() {
headerListRight = new ArrayList<>();
hashMapRight = new HashMap<>();
String[] notLoggedInMenu = {findStringByName("login_text"),
findStringByName("action_register_text"),
findStringByName("contact_us_text")};
String[] loggedInMenu = {findStringByName("account"), findStringByName("edit_account_text"),
findStringByName("action_change_pass_text"),
findStringByName("order_history_text"),
findStringByName("logout"), findStringByName("contact_us_text")};
List<UserSubMenu> userSubMenusList = new ArrayList<>();
if (isLoggedIn()) {
for (int i = 0; i < loggedInMenu.length; i++) {
headerListRight.add(loggedInMenu[i]);
hashMapRight.put(headerListRight.get(i), userSubMenusList);
}
} else {
for (int i = 0; i < notLoggedInMenu.length; i++) {
headerListRight.add(notLoggedInMenu[i]);
hashMapRight.put(headerListRight.get(i), userSubMenusList);
}
}
String responseStr = "";
if (getIntent().hasExtra(KEY_EXTRA)) {
responseStr = getIntent().getStringExtra(KEY_EXTRA);
utils.printLog("ResponseInInitData", responseStr);
try {
JSONObject responseObject = new JSONObject(responseStr);
boolean success = responseObject.optBoolean("success");
if (success) {
try {
JSONObject homeObject = responseObject.getJSONObject("home");
JSONArray slideshow = homeObject.optJSONArray("slideshow");
AppConstants.setSlideshowExtra(slideshow.toString());
JSONArray menuRight = homeObject.optJSONArray("usermenu");
for (int z = 0; z < menuRight.length(); z++) {
List<UserSubMenu> userSubMenuList = new ArrayList<>();
JSONObject object = menuRight.getJSONObject(z);
headerListRight.add(object.optString("name"));
JSONArray childArray = object.optJSONArray("children");
for (int y = 0; y < childArray.length(); y++) {
JSONObject obj = childArray.optJSONObject(y);
userSubMenuList.add(new UserSubMenu(obj.optString("code"),
obj.optString("title"), obj.optString("symbol_left"),
obj.optString("symbol_right")));
}
hashMapRight.put(headerListRight.get(headerListRight.size() - 1), userSubMenuList);
utils.printLog("AfterHashMap", "" + hashMapRight.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
utils.showErrorDialog("Error Getting Data From Server");
utils.printLog("SuccessFalse", "Within getCategories");
}
} catch (JSONException e) {
e.printStackTrace();
utils.printLog("JSONObjEx_MainAct", responseStr);
}
} else {
utils.printLog("ResponseExMainActivity", responseStr);
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
}
private void initLeftMenuData() {
headerListLeft = new ArrayList<>();
hashMapLeft = new HashMap<>();
String responseStr = "";
if (getIntent().hasExtra(KEY_EXTRA)) {
responseStr = getIntent().getStringExtra(KEY_EXTRA);
utils.printLog("ResponseInMainActivity", responseStr);
try {
JSONObject responseObject = new JSONObject(responseStr);
utils.printLog("JSON_Response", "" + responseObject);
boolean success = responseObject.optBoolean("success");
if (success) {
try {
JSONObject homeObject = responseObject.getJSONObject("home");
JSONArray menuCategories = homeObject.optJSONArray("categoryMenu");
utils.printLog("Categories", menuCategories.toString());
for (int i = 0; i < menuCategories.length(); i++) {
JSONObject menuCategoryObj = menuCategories.getJSONObject(i);
JSONArray menuSubCategoryArray = menuCategoryObj.optJSONArray(
"children");
List<MenuSubCategory> childMenuList = new ArrayList<>();
for (int j = 0; j < menuSubCategoryArray.length(); j++) {
JSONObject menuSubCategoryObj = menuSubCategoryArray.getJSONObject(j);
MenuSubCategory menuSubCategory = new MenuSubCategory(
menuSubCategoryObj.optString("child_id"),
menuSubCategoryObj.optString("name"));
childMenuList.add(menuSubCategory);
}
MenuCategory menuCategory = new MenuCategory(menuCategoryObj.optString(
"category_id"), menuCategoryObj.optString("name"),
menuCategoryObj.optString("icon"), childMenuList);
headerListLeft.add(menuCategory);
hashMapLeft.put(headerListLeft.get(i), menuCategory.getMenuSubCategory());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
utils.printLog("ResponseExMainActivity", responseStr);
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
}
private void actionbarToggle() {
mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawer,
R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
drawerIconLeft.setImageResource(R.drawable.ic_list_black);
drawerIconLeft.setScaleX(-1);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.logo_icon) {
recreate();
} else if (id == R.id.my_account_tv) {
utils.switchFragment(new Dashboard());
} else if (id == R.id.disc_tv) {
utils.printLog("From = Main Act");
Bundle bundle = new Bundle();
bundle.putString("from", "mainActivity");
utils.switchFragment(new FragProduct(), bundle);
} else if (id == R.id.checkout_tv) {
if (isLoggedIn()) {
utils.switchFragment(new FragCheckout());
} else {
AlertDialog alertDialog = utils.showAlertDialogReturnDialog("Continue As",
"Select the appropriate option");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
"As Guest", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragCheckout());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"Login", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragLogin());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
"Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragRegister());
}
});
alertDialog.show();
}
} else if (id == R.id.home_tv) {
recreate();
} else if (id == R.id.search_icon) {
startActivityForResult(new Intent(context, SearchActivity.class), SEARCH_REQUEST_CODE);
} else if (id == R.id.cart_layout) {
Bundle bundle = new Bundle();
bundle.putString("midFix", "cartProducts");
utils.switchFragment(new FragCartDetail(), bundle);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SEARCH_REQUEST_CODE || requestCode == CURRENCY_REQUEST_CODE
|| requestCode == LANGUAGE_REQUEST_CODE) {
if (data != null) {
String responseStr = data.getStringExtra("result");
utils.printLog("ResponseIs = " + responseStr);
if (responseStr != null) {
if (resultCode == Activity.RESULT_OK) {
JSONObject response;
if (!isJSONString(responseStr)) {
try {
response = new JSONObject(responseStr);
if (requestCode == CURRENCY_REQUEST_CODE) {
JSONObject object = response.optJSONObject("currency");
Preferences.setSharedPreferenceString(appContext
, CURRENCY_SYMBOL_KEY
, object.optString("symbol_left")
+ object.optString("symbol_right")
);
recreate();
} else if (requestCode == LANGUAGE_REQUEST_CODE) {
JSONObject object = response.optJSONObject("language");
Preferences.setSharedPreferenceString(appContext
, LANGUAGE_KEY
, object.optString("code")
);
recreate();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (requestCode == SEARCH_REQUEST_CODE) {
if (responseStr.isEmpty())
return;
Bundle bundle = new Bundle();
bundle.putString("id", responseStr);
bundle.putString("from", "fromSearch");
utils.switchFragment(new FragProduct(), bundle);
} else {
utils.showAlertDialog("Alert", responseStr);
}
}
} else if (resultCode == FORCED_CANCEL) {
utils.printLog("WithinSearchResult", "If Success False" + responseStr);
} else if (resultCode == Activity.RESULT_CANCELED) {
utils.printLog("WithinSearchResult", "Result Cancel" + responseStr);
}
}
}
}
}
}
MainFragment
public class MainFrag extends MyBaseFragment {
public MainFrag() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_main, container, false);
initUtils();
initViews(view);
utils.setupSlider(mPager, indicator, pb, true, true);
RecyclerView.LayoutManager mLayoutManager =
new LinearLayoutManager(getActivity()
, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
List<String> keysList = prepareData();
if (keysList.size() > 0 && !keysList.isEmpty()) {
mRecyclerView.setAdapter(new MainFragmentAdapter(keysList));
}
return view;
}
private void initViews(View view) {
mRecyclerView = view.findViewById(R.id.parent_recycler_view);
mPager = view.findViewById(R.id.pager);
indicator = view.findViewById(R.id.indicator);
pb = view.findViewById(R.id.loading);
}
private List<String> prepareData() {
String responseStr = getHomeExtra();
List<String> keysStr = new ArrayList<>();
try {
JSONObject responseObject = new JSONObject(responseStr);
utils.printLog("JSON_Response", "" + responseObject);
boolean success = responseObject.optBoolean("success");
if (success) {
JSONObject homeObject = responseObject.optJSONObject("home");
JSONObject modules = homeObject.optJSONObject("modules");
Iterator<?> keys = modules.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
keysStr.add(key);
utils.printLog("KeyStr", key);
}
utils.printLog("ModuleSize", modules.toString());
} else {
utils.printLog("SuccessFalse", "Within getCategories");
}
} catch (JSONException e) {
e.printStackTrace();
utils.printLog("JSONEx_MainFragTest", responseStr);
}
return keysStr;
}
}
I removed global variables and some method because of length.
You should not use recreate() method here, as it forces the activity to reload everything. Just use intent to call your Home activity, that should solve this issue.
From the hint of #Akash Khatri I use to switch to mainFragment and its fine now. Actually #Akash is right recreate(); everything at present But as I was setting main fragment in OnCreate of MainActivity. So, It was hard to notice that Android first recreate everything and in no time It call the main Fragment.
I do not using Intent to start the same activity again Because Switching fragment is more convenient. And also I pass Some extras to it that I will loose With new Intent.
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 5 years ago.
In my android app, I am using recycler view to show items.
(Note: This is not a duplicate question because I tried many answers from stackoverflow but no solution.)
My Problem
The recycler view showing repeated items. A single item is repeating many times even though it occurs only single time in the source DB.
I checked for the reason and note that the List object in Adapter class returning same values in all iterations. But the Fragment that sends List object to adapter class having unique values.
But only the adapter class after receiving the List object contains duplicate items
Solutions I tried
I checked Stackoverflow and added getItemId(int position) and getItemViewType(int position) in adaptor class but no solution
I checked the DB and also List view sending class both dont have duplicate items.
My Code:
InboxHostFragment.java = This class sends List object to adaptor class of recycler view:
public class HostInboxFragment extends Fragment {
View hostinbox;
Toolbar toolbar;
ImageView archive, alert, search;
TextView blank;
Bundle args = new Bundle();
private static final String TAG = "Listinbox_host";
private InboxHostAdapter adapter;
String Liveurl = "";
RelativeLayout layout, host_inbox;
String country_symbol;
String userid;
String login_status, login_status1;
ImageButton back;
String roomid;
RecyclerView listView;
String name = "ramesh";
private int start = 1;
private List < ListFeed > movieList = new ArrayList < > ();
String currency1;
// RecyclerView recyclerView;
public HostInboxFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.M)
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
hostinbox = inflater.inflate(R.layout.fragment_host_inbox, container, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), getString(R.string.app_font));
fontChanger.replaceFonts((ViewGroup) hostinbox);
SharedPreferences prefs = getActivity().getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE);
userid = prefs.getString("userid", null);
currency1 = prefs.getString("currenycode", null);
toolbar = (Toolbar) hostinbox.findViewById(R.id.toolbar);
archive = (ImageView) hostinbox.findViewById(R.id.archive);
alert = (ImageView) hostinbox.findViewById(R.id.alert);
search = (ImageView) hostinbox.findViewById(R.id.search);
blank = (TextView) hostinbox.findViewById(R.id.blank);
host_inbox = (RelativeLayout) hostinbox.findViewById(R.id.host_inbox);
layout.setVisibility(View.INVISIBLE);
start = 1;
final String url = Constants.DETAIL_PAGE_URL + "payment/host_reservation_inbox?userto=" + userid + "&start=" + start + "&common_currency=" + currency1;
//*******************************************ListView code start*****************************************************
System.out.println("url in Inbox page===" + url);
movieList.clear();
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#SuppressWarnings("deprecation")
#Override
public void onResponse(JSONObject response) {
// progressBar.setVisibility(View.GONE);
// Parsing json
// for (int i = 0; i < response.length(); i++) {
try {
JSONArray contact = response.getJSONArray("contact");
obj_contact = contact.optJSONObject(0);
login_status1 = obj_contact.getString("Status");
// progressBar.setVisibility(View.VISIBLE);
layout.setVisibility(View.INVISIBLE);
listView.setVisibility(View.VISIBLE);
host_inbox.setBackgroundColor(Color.parseColor("#FFFFFF"));
ListFeed movie = new ListFeed();
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique values
adapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
// progressBar.setVisibility(View.GONE);
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
stopAnim();
//progressBar.setVisibility(View.GONE);
if (error instanceof NoConnectionError) {
Toast.makeText(getActivity(),
"Check your Internet Connection",
Toast.LENGTH_LONG).show();
}
//progressBar.setVisibility(View.GONE);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
movieReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return hostinbox;
}
#Override
public void onStop() {
Log.w(TAG, "App stopped");
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
In the above code , System.out.println(movieList.get(i).message()); returning unique values without any problem.
Inboxhostadapter.java = This is the adapter for recycleview
public class InboxHostAdapter extends RecyclerView.Adapter < InboxHostAdapter.CustomViewHolder > {
private List < ListFeed > feedItemList;
private ListFeed listFeed = new ListFeed();
String userid = "",
tag,
str_currency;
String reservation_id,
Liveurl,
india2 = "0";
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
String currency1;
String status1;
//private Activity activity;
public Context activity;
public InboxHostAdapter(Context activity, List < ListFeed > feedItemList, String tag) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
Liveurl = sharedPreferences.getString("liveurl", null);
userid = sharedPreferences.getString("userid", null);
currency1 = sharedPreferences.getString("currenycode", null);
this.feedItemList = feedItemList; // returning duplicate items
this.activity = activity;
listFeed = new ListFeed();
this.tag = tag;
SharedPreferences prefs1 = activity.getSharedPreferences(Constants.MY_PREFS_LANGUAGE, MODE_PRIVATE);
str_currency = prefs1.getString("currencysymbol", null);
if (str_currency == null) {
str_currency = "$";
}
}
#Override
public InboxHostAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hostinbox, parent, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(activity.getAssets(), activity.getString(R.string.app_font_light));
fontChanger.replaceFonts((ViewGroup) view);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(InboxHostAdapter.CustomViewHolder holder, int position) {
// This block returning duplicate items
listFeed = feedItemList.get(position); // This list feedItemList returning duplicate items
reservation_id = listFeed.getid();
System.out.println("reservation id after getting in inbox adapter" + reservation_id);
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("message after getting in inbox adapter" + listFeed.getTitle());
System.out.println("symbol after getting" + listFeed.getsymbol());
System.out.println("username after getting" + listFeed.getaddress());
System.out.println("price after getting" + listFeed.getprice());
System.out.println("status after getting" + listFeed.getstatus());
System.out.println("check in after getting" + listFeed.getcheckin());
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("userby after getting====" + listFeed.getuserby());
System.out.println("message after getting====" + listFeed.message());
String msg;
msg = listFeed.message();
holder.name.setText(listFeed.userbyname());
holder.time.setText(listFeed.getcreated());
holder.date1.setText(listFeed.getcheckin());
holder.date2.setText(listFeed.getcheckout());
if (listFeed.guest().equals("1")) {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
if (tag.equals("Listinbox_service_host")) {
holder.guest.setText("");
holder.ttt.setVisibility(View.INVISIBLE);
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
// holder.status.setText(listFeed.getstatus());
holder.title.setText(listFeed.getTitle());
status1 = listFeed.getstatus();
if (status1.equals("Accepted")) {
holder.status.setText(activity.getResources().getString(R.string.accepted_details));
}
} else if (status1.equals("Contact Host")) {
holder.status.setText(activity.getResources().getString(R.string.Contact_Host));
holder.guestmsg.setText(listFeed.message());
} else {
holder.status.setText(status1);
}
if (currency1 == null) {
currency1 = "$";
}
if (listFeed.getprice() != null && !listFeed.getprice().equals("null")) {
DecimalFormat money = new DecimalFormat("00.00");
money.setRoundingMode(RoundingMode.UP);
india2 = money.format(new Double(listFeed.getprice()));
holder.currency.setText(listFeed.getsymbol() + " " + india2);
holder.currency.addTextChangedListener(new NumberTextWatcher(holder.currency));
}
//view.imgViewFlag.setImageResource(listFlag.get(position));
System.out.println("listview price" + listFeed.getprice());
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
//holder.bucket.setTag(position);
System.out.println("Activity name" + tag);
holder.inbox.setTag(position);
holder.inbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) v.getTag();
Intent search = new Intent(activity, Inbox_detailshost.class);
search.putExtra("userid", userid);
search.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(search);
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
}
});
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemCount() {
System.out.println("list item size" + feedItemList.size());
return (null != feedItemList ? feedItemList.size() : 0);
}
#Override
public int getItemViewType(int position) {
return position;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView thumbNail;
TextView name, time, date1, date2, currency, guest, status, title, ttt, guestmsg;
RelativeLayout inbox;
CustomViewHolder(View view) {
super(view);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
this.thumbNail = (ImageView) view.findViewById(R.id.list_image);
this.name = (TextView) view.findViewById(R.id.title2);
this.time = (TextView) view.findViewById(R.id.TextView4);
this.date1 = (TextView) view.findViewById(R.id.TextView2);
this.date2 = (TextView) view.findViewById(R.id.TextView22);
this.currency = (TextView) view.findViewById(R.id.TextView23);
this.guest = (TextView) view.findViewById(R.id.TextView25);
this.ttt = (TextView) view.findViewById(R.id.TextView24);
this.status = (TextView) view.findViewById(R.id.TextView26);
this.title = (TextView) view.findViewById(R.id.TextView28);
this.inbox = (RelativeLayout) view.findViewById(R.id.inbox);
this.guestmsg = (TextView) view.findViewById(R.id.guestmessage);
}
}
public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private TextView et;
public NumberTextWatcher(TextView et) {
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###.##");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelected(true);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) {
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}
}
In the above code , feedItemList returning duplicate values eventhogh the movieList list from source clas Inboxfragment.java contains unique values.
Kindly please help me with this issue. I tried many answers in Stackoverflow but I can't get solutions. I can't figure out the problem.
Use this code
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
ListFeed movie = new ListFeed();
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique value
}
Declare ListFeed movie = new ListFeed(); into the for Loop
And remove the adapter.notifyDataSetChanged(); from for Loop.
I think this help you.
I am trying to display entire Downloads directory inside a ListView in an Activity. However, the app works sometime, other time crashes with a log :
E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 420)
java.lang.RuntimeException: Adding window failed
at android.view.ViewRootImpl.setView(ViewRootImpl.java:543)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3169)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2481)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.os.DeadObjectException: Transaction failed on small parcel; remote process probably died
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:503)
at android.view.IWindowSession$Stub$Proxy.addToDisplay(IWindowSession.java:746)
at android.view.ViewRootImpl.setView(ViewRootImpl.java:531)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3169)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2481)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Here's the source code to the same Activity:
public class DownloadsActivity extends AppCompatActivity
{
private ListView listView = null;
//private EditText editText;
private DbAdapter_Files db;
private SimpleCursorAdapter adapter;
private SharedPreferences sharedPref;
//private TextView listBar;
private class_CustomViewPager viewPager;
private int top;
private int index;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_downloads);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sharedPref.edit().putString("files_startFolder",
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()).apply();
//editText = (EditText) getActivity().findViewById(R.id.editText);
//listBar = (TextView)findViewById(R.id.listBar);
listView = (ListView)findViewById(R.id.listDownloads);
//viewPager = (class_CustomViewPager) getActivity().findViewById(R.id.viewpager);
//calling Notes_DbAdapter
db = new DbAdapter_Files(this);
db.open();
setFilesList();
}
private void setTitle () {
/*if (sharedPref.getString("sortDBF", "title").equals("title")) {
listBar.setText(getString(R.string.app_title_downloads) + " | " + getString(R.string.sort_title));
} else if (sharedPref.getString("sortDBF", "title").equals("file_date")) {
listBar.setText(getString(R.string.app_title_downloads) + " | " + getString(R.string.sort_date));
} else {
listBar.setText(getString(R.string.app_title_downloads) + " | " + getString(R.string.sort_extension));
}*/
Log.e("title","method called");
}
private void isEdited () {
index = listView.getFirstVisiblePosition();
View v = listView.getChildAt(0);
top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());
}
private void setFilesList() {
deleteDatabase("files_DB_v01.db");
String path = sharedPref.getString("files_startFolder",
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
File f = new File(path);
final File[] files = f.listFiles();
// looping through all items <item>
if (files.length == 0) {
Snackbar.make(listView, R.string.toast_files, Snackbar.LENGTH_LONG).show();
}
for (File file : files) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String file_Name = file.getName();
String file_Size = getReadableFileSize(file.length());
String file_date = formatter.format(new Date(file.lastModified()));
String file_path = file.getAbsolutePath();
String file_ext;
if (file.isDirectory()) {
file_ext = ".";
} else {
try {
file_ext = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("."));
} catch (Exception e)
{
Log.e("Crash","1");
file_ext = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("/"));
}
}
db.open();
if(db.isExist(helper_main.secString(file_Name))) {
Log.i(TAG, "Entry exists" + file_Name);
} else {
db.insert(helper_main.secString(file_Name), file_Size, helper_main.secString(file_ext), helper_main.secString(file_path), file_date);
}
}
try {
db.insert("...", "", "", "", "");
} catch (Exception e)
{
Log.e("Crash","2");
Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show();
}
//display data
final int layoutstyle=R.layout.list_item;
int[] xml_id = new int[] {
R.id.textView_title_notes,
R.id.textView_des_notes,
R.id.textView_create_notes
};
String[] column = new String[] {
"files_title",
"files_content",
"files_creation"
};
final Cursor row = db.fetchAllData(DownloadsActivity.this);
adapter = new SimpleCursorAdapter(DownloadsActivity.this, layoutstyle,row,column, xml_id, 0) {
#Override
public View getView (final int position, View convertView, ViewGroup parent) {
Cursor row = (Cursor) listView.getItemAtPosition(position);
final String files_icon = row.getString(row.getColumnIndexOrThrow("files_icon"));
final String files_attachment = row.getString(row.getColumnIndexOrThrow("files_attachment"));
View v = super.getView(position, convertView, parent);
final ImageView iv = (ImageView) v.findViewById(R.id.icon_notes);
final ImageView iv2 = (ImageView) v.findViewById(R.id.icon_notes2);
iv.setVisibility(View.VISIBLE);
Uri uri = Uri.fromFile(new File(files_attachment));
if (files_icon.matches("")) {
iv.setVisibility(View.INVISIBLE);
iv2.setVisibility(View.VISIBLE);
iv.setImageResource(R.drawable.arrow_up_dark);
} else if (files_icon.matches("(.)")) {
iv.setImageResource(R.drawable.folder);
} else if (files_icon.matches("(.m3u8|.mp3|.wma|.midi|.wav|.aac|.aif|.amp3|.weba|.ogg)")) {
iv.setImageResource(R.drawable.file_music);
} else if (files_icon.matches("(.mpeg|.mp4|.webm|.qt|.3gp|.3g2|.avi|.flv|.h261|.h263|.h264|.asf|.wmv)")) {
iv.setImageResource(R.drawable.file_video);
} else if(files_icon.matches("(.gif|.bmp|.tiff|.svg|.png|.jpg|.JPG|.jpeg)")) {
try {
iv2.setVisibility(View.INVISIBLE);
Picasso.with(DownloadsActivity.this).load(uri).resize(76, 76).centerCrop().memoryPolicy(MemoryPolicy.NO_CACHE).into(iv);
} catch (Exception e)
{
Log.e("Crash","3");
Log.w("Browser", "Error load thumbnail", e);
iv.setImageResource(R.drawable.file_image);
}
} else if (files_icon.matches("(.vcs|.vcf|.css|.ics|.conf|.config|.java|.html)")) {
iv.setImageResource(R.drawable.file_xml);
} else if (files_icon.matches("(.apk)")) {
iv.setImageResource(R.drawable.android);
} else if (files_icon.matches("(.pdf)")) {
iv.setImageResource(R.drawable.file_pdf);
} else if (files_icon.matches("(.rtf|.csv|.txt|.doc|.xls|.ppt|.docx|.pptx|.xlsx|.odt|.ods|.odp)")) {
iv.setImageResource(R.drawable.file_document);
} else if (files_icon.matches("(.zip|.rar)")) {
iv.setImageResource(R.drawable.zip_box);
} else {
iv.setImageResource(R.drawable.file);
}
return v;
}
};
//display data by filter
final String note_search = sharedPref.getString("filter_filesBY", "files_title");
sharedPref.edit().putString("filter_filesBY", "files_title").apply();
/* editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
});*/
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return db.fetchDataByFilter(constraint.toString(),note_search);
}
});
listView.setAdapter(adapter);
listView.setSelectionFromTop(index, top);
//onClick function
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {
Cursor row2 = (Cursor) listView.getItemAtPosition(position);
final String files_icon = row2.getString(row2.getColumnIndexOrThrow("files_icon"));
final String files_attachment = row2.getString(row2.getColumnIndexOrThrow("files_attachment"));
final File pathFile = new File(files_attachment);
if(pathFile.isDirectory()) {
try {
sharedPref.edit().putString("files_startFolder", files_attachment).apply();
setFilesList();
} catch (Exception e)
{
Log.e("Crash","4");
Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show();
}
} else if(files_attachment.equals("")) {
try {
final File pathActual = new File(sharedPref.getString("files_startFolder",
Environment.getExternalStorageDirectory().getPath()));
sharedPref.edit().putString("files_startFolder", pathActual.getParent()).apply();
setFilesList();
} catch (Exception e)
{
Log.e("Crash","5");
Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show();
}
} else {
helper_main.open(files_icon, DownloadsActivity.this, pathFile, listView);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
isEdited();
Cursor row2 = (Cursor) listView.getItemAtPosition(position);
final String files_title = row2.getString(row2.getColumnIndexOrThrow("files_title"));
final String files_attachment = row2.getString(row2.getColumnIndexOrThrow("files_attachment"));
final File pathFile = new File(files_attachment);
if (pathFile.isDirectory()) {
Snackbar snackbar = Snackbar
.make(listView, R.string.bookmark_remove_confirmation, Snackbar.LENGTH_LONG)
.setAction(R.string.toast_yes, new View.OnClickListener() {
#Override
public void onClick(View view) {
sharedPref.edit().putString("files_startFolder", pathFile.getParent()).apply();
deleteRecursive(pathFile);
setFilesList();
}
});
snackbar.show();
} else {
final CharSequence[] options = {
getString(R.string.choose_menu_2),
getString(R.string.choose_menu_3),
getString(R.string.choose_menu_4)};
final AlertDialog.Builder dialog = new AlertDialog.Builder(DownloadsActivity.this);
dialog.setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
dialog.setItems(options, new DialogInterface.OnClickListener() {
#SuppressWarnings("ResultOfMethodCallIgnored")
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals(getString(R.string.choose_menu_2))) {
if (pathFile.exists()) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, files_title);
sharingIntent.putExtra(Intent.EXTRA_TEXT, files_title);
Uri bmpUri = Uri.fromFile(pathFile);
sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
startActivity(Intent.createChooser(sharingIntent, (getString(R.string.app_share_file))));
}
}
if (options[item].equals(getString(R.string.choose_menu_4))) {
Snackbar snackbar = Snackbar
.make(listView, R.string.bookmark_remove_confirmation, Snackbar.LENGTH_LONG)
.setAction(R.string.toast_yes, new View.OnClickListener() {
#Override
public void onClick(View view) {
pathFile.delete();
setFilesList();
}
});
snackbar.show();
}
if (options[item].equals(getString(R.string.choose_menu_3))) {
sharedPref.edit().putString("pathFile", files_attachment).apply();
//editText.setVisibility(View.VISIBLE);
//helper_editText.showKeyboard(getActivity(), editText, 2, files_title, getString(R.string.bookmark_edit_title));
}
}
});
dialog.show();
}
return true;
}
});
}
#SuppressWarnings("ResultOfMethodCallIgnored")
private void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
deleteRecursive(child);
}
}
fileOrDirectory.delete();
}
private static String getReadableFileSize(long size) {
final int BYTES_IN_KILOBYTES = 1024;
final DecimalFormat dec = new DecimalFormat("###.#");
final String KILOBYTES = " KB";
final String MEGABYTES = " MB";
final String GIGABYTES = " GB";
float fileSize = 0;
String suffix = KILOBYTES;
if (size > BYTES_IN_KILOBYTES) {
fileSize = size / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
suffix = GIGABYTES;
} else {
suffix = MEGABYTES;
}
}
}
return valueOf(dec.format(fileSize) + suffix);
}
public void doBack() {
//BackPressed in activity will call this;
Snackbar snackbar = Snackbar
.make(listView, getString(R.string.toast_exit), Snackbar.LENGTH_SHORT)
.setAction(getString(R.string.toast_yes), new View.OnClickListener() {
#Override
public void onClick(View view) {
DownloadsActivity.this.finish();
}
});
snackbar.show();
}
public void fragmentAction () {
setTitle();
setFilesList();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.filter_title:
sharedPref.edit().putString("filter_filesBY", "files_title").apply();
setFilesList();
//editText.setVisibility(View.VISIBLE);
//helper_editText.showKeyboard(getActivity(), editText, 1, "", getString(R.string.action_filter_title));
return true;
case R.id.filter_url:
sharedPref.edit().putString("filter_filesBY", "files_icon").apply();
setFilesList();
//editText.setVisibility(View.VISIBLE);
//helper_editText.showKeyboard(getActivity(), editText, 1, "", getString(R.string.action_filter_url));
return true;
case R.id.filter_today:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Calendar cal = Calendar.getInstance();
final String search = dateFormat.format(cal.getTime());
sharedPref.edit().putString("filter_filesBY", "files_creation").apply();
setFilesList();
//editText.setText(search);
//listBar.setText(getString(R.string.app_title_bookmarks) + " | " + getString(R.string.filter_today));
return true;
case R.id.filter_yesterday:
DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.DATE, -1);
final String search2 = dateFormat2.format(cal2.getTime());
sharedPref.edit().putString("filter_filesBY", "files_creation").apply();
setFilesList();
//editText.setText(search2);
//listBar.setText(getString(R.string.app_title_bookmarks) + " | " + getString(R.string.filter_yesterday));
return true;
case R.id.filter_before:
DateFormat dateFormat3 = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Calendar cal3 = Calendar.getInstance();
cal3.add(Calendar.DATE, -2);
final String search3 = dateFormat3.format(cal3.getTime());
sharedPref.edit().putString("filter_filesBY", "files_creation").apply();
setFilesList();
//editText.setText(search3);
//listBar.setText(getString(R.string.app_title_bookmarks) + " | " + getString(R.string.filter_before));
return true;
case R.id.filter_month:
DateFormat dateFormat4 = new SimpleDateFormat("yyyy-MM", Locale.getDefault());
Calendar cal4 = Calendar.getInstance();
final String search4 = dateFormat4.format(cal4.getTime());
sharedPref.edit().putString("filter_filesBY", "files_creation").apply();
setFilesList();
//editText.setText(search4);
//listBar.setText(getString(R.string.app_title_bookmarks) + " | " + getString(R.string.filter_month));
return true;
case R.id.filter_own:
sharedPref.edit().putString("filter_filesBY", "files_creation").apply();
setFilesList();
//editText.setVisibility(View.VISIBLE);
//helper_editText.showKeyboard(getActivity(), editText, 1, "", getString(R.string.action_filter_create));
return true;
case R.id.filter_clear:
//editText.setVisibility(View.GONE);
setTitle();
//helper_editText.hideKeyboard(getActivity(), editText, 0, getString(R.string.app_title_history), getString(R.string.app_search_hint));
setFilesList();
return true;
case R.id.action_save_bookmark:
final File pathFile = new File(sharedPref.getString("pathFile", ""));
String inputTag = "";
File dir = pathFile.getParentFile();
File to = new File(dir,inputTag);
if(db.isExist(helper_main.secString(inputTag))){
Snackbar.make(listView, getString(R.string.toast_newTitle), Snackbar.LENGTH_LONG).show();
} else {
pathFile.renameTo(to);
pathFile.delete();
Snackbar.make(listView, R.string.bookmark_added, Snackbar.LENGTH_SHORT).show();
//editText.setVisibility(View.GONE);
setTitle();
//helper_editText.hideKeyboard(getActivity(), editText, 0, getString(R.string.app_title_bookmarks), getString(R.string.app_search_hint));
setFilesList();
}
return true;
case R.id.action_cancel:
//editText.setVisibility(View.GONE);
setTitle();
//helper_editText.hideKeyboard(getActivity(), editText, 0, getString(R.string.app_title_bookmarks), getString(R.string.app_search_hint));
setFilesList();
return true;
case R.id.sort_title:
sharedPref.edit().putString("sortDBF", "title").apply();
setFilesList();
setTitle();
return true;
case R.id.sort_extension:
sharedPref.edit().putString("sortDBF", "file_ext").apply();
setFilesList();
setTitle();
return true;
case R.id.sort_date:
sharedPref.edit().putString("sortDBF", "file_date").apply();
setFilesList();
setTitle();
return true;
case android.R.id.home:
viewPager.setCurrentItem(sharedPref.getInt("tab", 0));
return true;
}
return super.onOptionsItemSelected(item);
}
}
What could possibly be causing this exception, and what's the effective way to resolve this issue?
I am trying to handle multiple checkboxes in order to delete or edit elements from a list, the list has custom adapter with its custom layout, inside this layout I am creating the checkbox, however I am getting a IndexOutOfBounds exception when I am trying to evaluate a boolean array even if it has been initialized.
public MeasureTableAdapter(Activity context, ArrayList<MeasureEvi> myMeasureEvi)
{
super(context, R.layout.adapter_tablamedida_item, myMeasureEvi);
this.context = context;
this.myMeasureEvi = myMeasureEvi;
checked= new boolean[myMeasureEvi.size()]; //this is where I initialize the array
}
and this where i am getting the exception at:
in the adapter
public View getView
this
if (checked[position]) {
holder.checkBox.setChecked(true);
} else {
holder.checkBox.setChecked(false);
}
the log in debug window
checked[position]= java.lang.IndexOutOfBoundsException : Invalid array range: 0 to 0
the log in android monitor
03-22 17:18:03.121 2024-3372/com.google.android.gms.persistent W/GLSUser: [AppCertManager] IOException while requesting key:
java.io.IOException: Invalid device key response.
at evk.a(:com.google.android.gms:274)
at evk.a(:com.google.android.gms:4238)
at evj.a(:com.google.android.gms:45)
at evd.a(:com.google.android.gms:50)
at evc.a(:com.google.android.gms:104)
at com.google.android.gms.auth.account.be.legacy.AuthCronChimeraService.b(:com.google.android.gms:4049)
at ecm.call(:com.google.android.gms:2041)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at llt.run(:com.google.android.gms:450)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at lqc.run(:com.google.android.gms:17)
at java.lang.Thread.run(Thread.java:761)
I put a breakpoint and I can see that the size of myMeasureEvi is not 0, but for some reason, checked is always 0
Any hints on this? if you need more information please let me know
EDIT: Complete adapter code
public class MeasureTableAdapter extends ArrayAdapter<MeasureEvi> {
private final Activity context;
ArrayList<MeasureEvi> myMeasureEvi;
boolean[] checked;
public OnHeadlineSelectedListener mCallback;
public interface OnHeadlineSelectedListener { public void onMeasureInDrawActiom(int position, boolean delete); }
public void setCallback(OnHeadlineSelectedListener mCallback){ this.mCallback = mCallback; }
public MeasureTableAdapter(Activity context, ArrayList<MeasureEvi> myMeasureEvi) {
super(context, R.layout.adapter_tablamedida_item, myMeasureEvi);
this.context = context;
this.myMeasureEvi = myMeasureEvi;
checked= new boolean[myMeasureEvi.size()];
}
private class ViewHolder {
TextView txtIndex;
EditText txtCoordX;
EditText txtCoordY;
ImageView imgEvidence;
TextView txtEvidence;
TextView txtName;
TextView txtDescription;
CheckBox checkBox;
}
#Override
public View getView(final int position, View rowView, ViewGroup parent){
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if(rowView == null) {
rowView = inflater.inflate(R.layout.adapter_tablamedida_item, null, true);
holder = new ViewHolder();
holder.txtIndex = (TextView) rowView.findViewById(R.id.TxtIndex);
holder.txtCoordX = (EditText) rowView.findViewById(R.id.TxtCoordX);
holder.txtCoordY = (EditText) rowView.findViewById(R.id.TxtCoordY);
holder.imgEvidence = (ImageView) rowView.findViewById(R.id.ImgIcon);
holder.txtEvidence = (TextView) rowView.findViewById(R.id.TxtEvidenciaId);
holder.txtName = (TextView) rowView.findViewById(R.id.TxtCategory);
holder.txtDescription = (TextView) rowView.findViewById(R.id.TxtDescription);
holder.checkBox= (CheckBox) rowView.findViewById(R.id.checkBox);
rowView.setTag(holder);
} else {
holder= (ViewHolder) rowView.getTag();
}
MeasureEvi currentItem = getItem(position);
if (currentItem != null) {
int suma = currentItem.getmOrderIndex()+1;
Evidence myEvidence = DataIpat.evidencetArray.get(currentItem.geteIndex());
holder.checkBox.setChecked(false);
if (holder.txtIndex != null) holder.txtIndex.setText("" + suma );
if (holder.imgEvidence != null) holder.imgEvidence.setImageDrawable(myEvidence.geteImage().getDrawable());
if (holder.txtEvidence != null) holder.txtEvidence.setText("" + myEvidence.geteId());
if (holder.txtName != null) holder.txtName.setText(myEvidence.geteCategory() + " " + (myEvidence.getcIndex() + 1));
if (holder.txtDescription != null) holder.txtDescription.setText(currentItem.getmDescription() + " - " + currentItem.getmObservation());
if (holder.txtCoordX != null) {
holder.txtCoordX.setSelectAllOnFocus(true);
holder.txtCoordX.setText("" + currentItem.getmCoordenate().x);
holder.txtCoordX.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus)
if(!(setPosition(holder.txtCoordX.getText().toString(), holder.txtCoordY.getText().toString(), position))){
PointF coord = DataIpat.measureEviArray.get(position).getmCoordenate();
holder.txtCoordX.setText("" + coord.x);
}
}
});
}
if (holder.txtCoordY != null){
holder.txtCoordY.setSelectAllOnFocus(true);
holder.txtCoordY.setText("" + currentItem.getmCoordenate().y);
holder.txtCoordY.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus)
if(!(setPosition(holder.txtCoordX.getText().toString(), holder.txtCoordY.getText().toString(), position))){
PointF coord = DataIpat.measureEviArray.get(position).getmCoordenate();
holder.txtCoordY.setText("" + coord.y);
}
}
});
}
}
if (checked[position]) {
holder.checkBox.setChecked(true);
} else {
holder.checkBox.setChecked(false);
}
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.checkBox.isChecked())
checked[position] = true;
else
checked[position] = false;
}
});
return rowView;
}
private boolean setPosition(String coordX, String coordY, int position){
try {
float X = Float.parseFloat(coordX);
float Y = Float.parseFloat(coordY);
PointF coord = DataIpat.measureEviArray.get(position).getmCoordenate();
if (X != 0 && Y != 0 ) { // Valido que los x y y sean diferentes de cero
if(X != coord.x || Y != coord.y) { // valida que el dato alla cambiado
for(MeasureEvi myMeasure: DataIpat.measureEviArray){ //
if (myMeasure.geteIndex() == DataIpat.measureEviArray.get(position).geteIndex()
&& myMeasure.getmIndex() != DataIpat.measureEviArray.get(position).getmIndex()){
if(X == myMeasure.getmCoordenate().x && Y == myMeasure.getmCoordenate().y) {
Toast.makeText(getContext(), "Error no se permiten coordenadas iguales.", Toast.LENGTH_SHORT).show();
return false;
}
}
}
DataIpat.measureEviArray.get(position).setmCoordenate(new PointF(X, Y));
mCallback.onMeasureInDrawActiom(position, false); // true for delete
}
}
return true;
} catch (Exception ex) {
return false;
}
}
}
By doing a deeper debug at my app, I noticed that the adapter is being initialized way before, so it won´t go trhough the constructor anymore, unless is initialized again, therefore the size of the array will always be 0.
SOLUTION:
As the array ask for the size of itself, I decided to use an ArrayList
create variable to store the checked boxes:
public static ArrayList<MeasureEvi> myChecked = new ArrayList<MeasureEvi>();
create a listener event to store your choices:
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.checkBox.isChecked()) {
myChecked.add(DataIpat.measureEviArray.get(position));
}
else {
myChecked.remove(DataIpat.measureEviArray.get(position));
}
for (int i=0; i<myChecked.size(); i++){
MeasureEvi e= myChecked.get(i);
Log.d("mOrder", String.valueOf(e.getmOrderIndex()));
}
}
});
and KABOOM, now I have the objets from where I checked!
I trying to add admob native ads in recyclerview that uses resourcecursoradapter adapter .. the issues is
1 - it makes app crash
2 - it replaces recyclerview data item with admob ads
that is my code
public class EntriesCursorAdapter extends ResourceCursorAdapter {
private final Uri mUri;
private final boolean mShowFeedInfo;
private int mIdPos, mTitlePos, mMainImgPos, mDatePos, mIsReadPos, mFavoritePos, mFeedIdPos, mFeedNamePos;
public static final int Ads_view_type = 11;
public EntriesCursorAdapter(Context context, Uri uri, Cursor cursor, boolean showFeedInfo) {
super(context, PrefUtils.getInt(PrefUtils.NEWS_FORMAT_int,R.layout.item_entry_list2), cursor, 0);
mUri = uri;
mShowFeedInfo = showFeedInfo;
reinit(cursor);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final int position = cursor.getPosition();
final int viewtype = getItemViewType(position);
View itemView ;
if(viewtype == Ads_view_type) {
final LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(R.layout.native_ads, parent, false);
if (itemView.getTag(R.id.holder) == null) {
AdsHolder ads_holder = new AdsHolder();
ads_holder.adView = (NativeExpressAdView) itemView.findViewById(R.id.adView2);
itemView.setTag(R.id.holder, ads_holder);
} return itemView;
}
else {
final LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(PrefUtils.getInt(PrefUtils.NEWS_FORMAT_int, R.layout.item_entry_list2), parent, false);
if (itemView.getTag(R.id.holder) == null) {
ViewHolder holder = new ViewHolder();
holder.titleTextView = (TextView) itemView.findViewById(android.R.id.text1);
holder.dateTextView = (TextView) itemView.findViewById(android.R.id.text2);
holder.mainImgView = (ImageView) itemView.findViewById(R.id.main_icon);
holder.starImgView = (ImageView) itemView.findViewById(R.id.favorite_icon);
itemView.setTag(R.id.holder, holder);
}
return itemView;
}
}
#Override
public int getItemViewType(int position) {
if(position % 6 ==0)
{return Ads_view_type;}
else {
return super.getItemViewType(position);
}
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
final int position = cursor.getPosition();
final int viewtype = getItemViewType(position);
if (viewtype == Ads_view_type) {
try {
AdsHolder adsHolder = (AdsHolder) view.getTag(R.id.holder);
AdRequest request = new AdRequest.Builder()
.addTestDevice("ca-app-pub-5647351014779121/8591922893")
.build();
adsHolder.adView.loadAd(request);
} catch (Exception e) {
}
} else {
try {
ViewHolder holder = (ViewHolder) view.getTag(R.id.holder);
String titleText = cursor.getString(mTitlePos);
holder.titleTextView.setText(titleText);
final long feedId = cursor.getLong(mFeedIdPos);
String feedName = cursor.getString(mFeedNamePos);
String mainImgUrl = cursor.getString(mMainImgPos);
mainImgUrl = TextUtils.isEmpty(mainImgUrl) ? null : NetworkUtils.getDownloadedOrDistantImageUrl(cursor.getLong(mIdPos), mainImgUrl);
ColorGenerator generator = ColorGenerator.DEFAULT;
int color = generator.getColor(feedId); // The color is specific to the feedId (which shouldn't change)
String lettersForName = feedName != null ? (feedName.length() < 2 ? feedName.toUpperCase() : feedName.substring(0, 2).toUpperCase()) : "";
TextDrawable letterDrawable = TextDrawable.builder().buildRect(lettersForName, color);
if (mainImgUrl != null) {
Glide.with(context).load(mainImgUrl).centerCrop().placeholder(letterDrawable).error(letterDrawable).into(holder.mainImgView);
} else {
Glide.clear(holder.mainImgView);
holder.mainImgView.setImageDrawable(letterDrawable);
}
holder.isFavorite = cursor.getInt(mFavoritePos) == 1;
holder.starImgView.setVisibility(holder.isFavorite ? View.VISIBLE : View.INVISIBLE);
if (mShowFeedInfo && mFeedNamePos > -1) {
if (feedName != null) {
holder.dateTextView.setText(Html.fromHtml("<font color='#247ab0'>" + feedName + "</font>" + Constants.COMMA_SPACE + StringUtils.getDateTimeString(cursor.getLong(mDatePos))));
} else {
holder.dateTextView.setText(StringUtils.getDateTimeString(cursor.getLong(mDatePos)));
}
} else {
holder.dateTextView.setText(StringUtils.getDateTimeString(cursor.getLong(mDatePos)));
}
if (cursor.isNull(mIsReadPos)) {
holder.titleTextView.setEnabled(true);
holder.dateTextView.setEnabled(true);
holder.isRead = false;
} else {
holder.titleTextView.setEnabled(false);
holder.dateTextView.setEnabled(false);
holder.isRead = true;
}
} catch (Exception e) {}
}
}
public void toggleReadState(final long id, View view) {
final ViewHolder holder = (ViewHolder) view.getTag(R.id.holder);
if (holder != null) { // should not happen, but I had a crash with this on PlayStore...
holder.isRead = !holder.isRead;
if (holder.isRead) {
holder.titleTextView.setEnabled(false);
holder.dateTextView.setEnabled(false);
} else {
holder.titleTextView.setEnabled(true);
holder.dateTextView.setEnabled(true);
}
new Thread() {
#Override
public void run() {
ContentResolver cr = MainApplication.getContext().getContentResolver();
Uri entryUri = ContentUris.withAppendedId(mUri, id);
cr.update(entryUri, holder.isRead ? FeedData.getReadContentValues() : FeedData.getUnreadContentValues(), null, null);
}
}.start();
}
}
public void toggleFavoriteState(final long id, View view) {
final ViewHolder holder = (ViewHolder) view.getTag(R.id.holder);
if (holder != null) { // should not happen, but I had a crash with this on PlayStore...
holder.isFavorite = !holder.isFavorite;
if (holder.isFavorite) {
holder.starImgView.setVisibility(View.VISIBLE);
} else {
holder.starImgView.setVisibility(View.INVISIBLE);
}
new Thread() {
#Override
public void run() {
ContentValues values = new ContentValues();
values.put(EntryColumns.IS_FAVORITE, holder.isFavorite ? 1 : 0);
ContentResolver cr = MainApplication.getContext().getContentResolver();
Uri entryUri = ContentUris.withAppendedId(mUri, id);
cr.update(entryUri, values, null, null);
}
}.start();
}
}
#Override
public void changeCursor(Cursor cursor) {
reinit(cursor);
super.changeCursor(cursor);
}
#Override
public Cursor swapCursor(Cursor newCursor) {
reinit(newCursor);
return super.swapCursor(newCursor);
}
#Override
public void notifyDataSetChanged() {
reinit(null);
super.notifyDataSetChanged();
}
#Override
public void notifyDataSetInvalidated() {
reinit(null);
super.notifyDataSetInvalidated();
}
private void reinit(Cursor cursor) {
if (cursor != null && cursor.getCount() > 0) {
mIdPos = cursor.getColumnIndex(EntryColumns._ID);
mTitlePos = cursor.getColumnIndex(EntryColumns.TITLE);
mMainImgPos = cursor.getColumnIndex(EntryColumns.IMAGE_URL);
mDatePos = cursor.getColumnIndex(EntryColumns.DATE);
mIsReadPos = cursor.getColumnIndex(EntryColumns.IS_READ);
mFavoritePos = cursor.getColumnIndex(EntryColumns.IS_FAVORITE);
mFeedNamePos = cursor.getColumnIndex(FeedColumns.NAME);
mFeedIdPos = cursor.getColumnIndex(EntryColumns.FEED_ID);
}
}
private static class ViewHolder {
public TextView titleTextView;
public TextView dateTextView;
public ImageView mainImgView;
public ImageView starImgView;
public boolean isRead, isFavorite;
}
private static class AdsHolder {
NativeExpressAdView adView;
}
}