custom listview stucks when new item is generting and scrolling - android

I have an issue.I have custom listView which has many child and also have another custom listview in it.All data which is display in both listView is coming from database.My Problem is that When I scroll My main ListView it stucks for a while and then scroll.I uploaded My all code here.
My Main Activity class:
public class TransactionListMonthWise<DisplayYear> extends TopParentActivity {
ListView statement;
ArrayList<DisplayMonth> status;
ArrayList<DisplayYear> yearstatus;
addBankTransactionList mAdapter;
TextView tvBankName, tvBalance, tvBankAccNoForHistory;
String monthname;
String monthName;
int yearName;
String bankname, amount, accno;
Date theDate;
String currencySymbl, cur_sym;
EPreferences epref;
String TotalBalance, BankBalance, finalTotalIncome;
Toolbar toolbarTransactionListMonthWise;
boolean loadingMore = false;
int itemsPerPage = 2;
DisplayMonth monthNameInAdapter;
int month;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaction_monthwise);
bindview();
init();
addListener();
}
private void init() {
epref = EPreferences.getInstance(TransactionListMonthWise.this);
getPrefData();
Intent intent = getIntent();
bankname = intent.getStringExtra("NAME");
tvBankName.setText(bankname);
TotalBalance = String.valueOf(intent.getDoubleExtra("BALANCE", 0.0));
BankBalance = new BigDecimal(TotalBalance).toPlainString();
DecimalFormat decimalFormatIncome = new DecimalFormat("0.#");
finalTotalIncome = decimalFormatIncome.format(Double
.valueOf(TotalBalance));
tvBalance.setText(currencySymbl
+ " "
+ String.format("%,.00f",
(double) Double.parseDouble(finalTotalIncome)));
// tvBalance.setText(amount + " " + currencySymbl);
Log.i("symbol", currencySymbl);
accno = intent.getStringExtra("ACCNO");
status = new ArrayList<DisplayMonth>();
yearstatus = new ArrayList<DisplayYear>();
tvBankAccNoForHistory.setText("xxxxx"
+ intent.getStringExtra("ACC_NUMBER"));
Utils.BANK_ACC_NUM = intent.getStringExtra("ACC_NUMBER");
Utils.BANK_NAME_DISP = bankname;
setSupportActionBar(toolbarTransactionListMonthWise);
this.toolbarTransactionListMonthWise
.setNavigationIcon(R.drawable.ic_arrow_back_white100);
getSupportActionBar().setTitle(bankname + " History");
}
private void bindview() {
toolbarTransactionListMonthWise = (Toolbar) findViewById(R.id.toolbarTransactionListMonthWise);
statement = (ListView) findViewById(R.id.list_transaction_view);
tvBankName = (TextView) findViewById(R.id.tvBankNameForHistory);
tvBalance = (TextView) findViewById(R.id.tvNetBalanceForHistory);
tvBankAccNoForHistory = (TextView) findViewById(R.id.tvBankAccNoForHistory);
}
private void addListener() {
statement.setOnScrollListener(new AbsListView.OnScrollListener() {
int mLastFirstVisibleItem;
boolean mIsScrollingUp;
#Override
public void onScrollStateChanged(AbsListView view, int scrollstate) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount)) {
new MailSender().execute();
}
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(TransactionListMonthWise.this,
BankList.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private String getMonth(int month1) {
switch (month1) {
case 1:
monthname = "Jan";
break;
case 2:
monthname = "Feb";
break;
case 3:
monthname = "Mar";
break;
case 4:
monthname = "Apr";
break;
case 5:
monthname = "May";
break;
case 6:
monthname = "Jun";
break;
case 7:
monthname = "Jul";
break;
case 8:
monthname = "Aug";
break;
case 9:
monthname = "Sep";
break;
case 10:
monthname = "Oct";
break;
case 11:
monthname = "Nov";
break;
case 12:
monthname = "Dec";
break;
default:
break;
}
return monthname;
}
private int getYear(int years) {
switch (years) {
case 1:
years = 2011;
break;
case 2:
years = 2012;
break;
case 3:
years = 2013;
break;
case 4:
years = 2014;
break;
case 5:
years = 2015;
break;
case 6:
years = 2016;
break;
default:
break;
}
return years;
}
private void getPrefData() {
cur_sym = epref.getPreferencesStr(epref.KEY_CURRENCY, "India");
Log.d("vaaaaa", " == " + cur_sym);
if (cur_sym.equalsIgnoreCase("India")) {
currencySymbl = getResources().getString(R.string.India);
} else if (cur_sym.equalsIgnoreCase("US")) {
currencySymbl = getResources().getString(R.string.United_States);
} else if (cur_sym.equalsIgnoreCase("Japan")) {
currencySymbl = getResources().getString(R.string.Japan);
} else if (cur_sym.equalsIgnoreCase("England")) {
currencySymbl = getResources().getString(R.string.England_pound);
} else if (cur_sym.equalsIgnoreCase("Costa Rica")) {
currencySymbl = getResources().getString(R.string.Costa);
} else if (cur_sym.equalsIgnoreCase("UK")) {
currencySymbl = getResources().getString(R.string.United);
} else if (cur_sym.equalsIgnoreCase("Phillipines")) {
currencySymbl = getResources().getString(R.string.Philippines);
} else if (cur_sym.equalsIgnoreCase("Mangolia")) {
currencySymbl = getResources().getString(R.string.Macedonia);
} else if (cur_sym.equalsIgnoreCase("Australia")) {
currencySymbl = getResources().getString(R.string.Australia);
} else if (cur_sym.equalsIgnoreCase("Europ")) {
currencySymbl = getResources().getString(R.string.Euro);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
public class MailSender extends AsyncTask<Void, Integer, Integer> {
Dialog progress;
#SuppressLint("ResourceAsColor")
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new Dialog(TransactionListMonthWise.this,
R.style.AppDialogExit);
progress.requestWindowFeature(Window.FEATURE_NO_TITLE);
progress.show();
progress.setContentView(R.layout.custom_loading_dialog);
TextView tv = (TextView) progress.findViewById(R.id.tv);
tv.setText("Mail is sending...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
}
#Override
protected Integer doInBackground(Void... params) {
final RelativeLayout footerView = (RelativeLayout) findViewById(R.id.loadItemsLayout_recyclerView);
Calendar cal = Calendar.getInstance();
month = cal.get(Calendar.MONTH) + 1;
// int year = cal.get(Calendar.YEAR) - 10;
int currentYear = cal.get(Calendar.YEAR);
Log.d("viewMonths", "month is" + month + " " + currentYear);
for (int j = month; j > 0; j--) {
monthNameInAdapter = new DisplayMonth();
monthName = getMonth(j);
monthNameInAdapter.setMonth(monthName);
status.add(monthNameInAdapter);
}
mAdapter = new addBankTransactionList(getApplicationContext(),
month, status, bankname, accno, currentYear, amount);
return 0;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
// progress.dismiss();
if (progress != null) {
progress.dismiss();
progress = null;
}
try {
statement.setAdapter(mAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Main Xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
android:fitsSystemWindows="true"
android:gravity="center"
android:orientation="vertical" >
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbarTransactionListMonthWise"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="?colorPrimary"
android:minHeight="?actionBarSize"
android:paddingRight="10dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" >
</android.support.v7.widget.Toolbar>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true" >
<RelativeLayout
android:id="#+id/rlBankNameAndBalance"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#color/green_100"
android:clickable="true"
android:gravity="right"
android:orientation="vertical"
android:paddingLeft="#dimen/main_list_data_disp_padding_left"
android:paddingRight="#dimen/main_list_data_disp_padding_right"
android:paddingTop="#dimen/main_list_data_disp_padding_top" >
<TextView
android:id="#+id/tvBankNameForHistory"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/iconId"
android:text="#string/BankBalance"
android:textColor="#color/gray_900"
android:textSize="#dimen/main_list_data_disp_text_size" />
<TextView
android:id="#+id/tvBankAccNoForHistory"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvBankNameForHistory"
android:text="#string/BankBalance"
android:textColor="#color/gray_500"
android:textSize="14sp" />
<TextView
android:id="#+id/tvNetBalanceForHistory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textColor="#color/gray_900"
android:textSize="#dimen/main_list_data_disp_text_size" />
</RelativeLayout>
</android.support.v7.widget.CardView>
<ListView
android:id="#+id/list_transaction_view"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="2dp"
android:scrollbars="none" />
<include
android:id="#+id/loadItemsLayout_recyclerView"
android:layout_width="fill_parent"
android:layout_height="110dp"
android:layout_alignParentBottom="true"
layout="#layout/progress_layout"
android:visibility="gone" />
Main Adapter Class:
public class addBankTransactionList extends BaseAdapter {
// Activity activityCategory;
static ArrayList<DisplayMonth> monthName;
// ArrayList<DisplayYear> yearName;
ArrayList<Expense> expense;
ArrayList<Income> incomes, Arr;
#SuppressWarnings("rawtypes")
ArrayList<String> arrDateDebit, arrDateCredit;
ArrayList<Double> arrAmountDebit, arrAmountCredit;
Context contextAddBank;
int CurrentMonth;
String bankNameForMatch, months, allyear, SystemMonthInString, amount,
bankAccNoForMatch;
int monthname;
String currencySymbl, cur_sym;
String date = "", thirdYear;
String monthNameInString;
EPreferences epref;
ArrayList<Income> tempIncomeses = new ArrayList<Income>();
String dateIncome, dateExpense;
Double expenseAmount, incomeAmount;
DataBaseAdapter adapter;
// private String ;
int monthNameInStringExpense, monthNameInStringIncome;
int yr, year;
int monthsInIntIncome, dateInIntIncome, yearInIntIncome,
monthsInIntExpense;
String convertDate;
// private ArrayList<Income> tempincomes = new ArrayList<Income>();
List list;
Date date1;
String emptyExpenseAmount, emptyIncomeAmount;
FilterData data;
private String bankname, accno;
public static Boolean isScrolling = true;
public static class ViewHolder {
public TextView tvDate, tvIncomeMoney, tvExpenseMoney,
tvRecordnotFound, tvIncomeSymblIncomeDisp, tvTransactionType,
tvTransactionDate, tvTransactionAmount, tvMoneyCurrencyExpense,
tvMoneyCurrencyIncome;
ListView rvList;
}
public addBankTransactionList(Context mcontext, int month,
ArrayList<DisplayMonth> status, String bankname, String bankAccNo,
int year, String amt) {
super();
this.contextAddBank = mcontext;
monthName = status;
CurrentMonth = month;
bankNameForMatch = bankname;
bankAccNoForMatch = bankAccNo;
yr = year;
amount = amt;
}
public boolean setListViewHeightBasedOnItems(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter != null) {
int numberOfItems = listAdapter.getCount();
Log.i("TotalRecord", numberOfItems + "");
int totalItemsHeight = 0;
for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
View item = listAdapter.getView(itemPos, null, listView);
item.measure(0, 0);
totalItemsHeight += item.getMeasuredHeight();
}
int totalDividersHeight = listView.getDividerHeight()
* (numberOfItems - 1);
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalItemsHeight + totalDividersHeight;
listView.setLayoutParams(params);
listView.requestLayout();
listView.setClickable(false);
listView.setEnabled(false);
return true;
} else {
return false;
}
}
private void getPrefData() {
cur_sym = epref.getPreferencesStr(epref.KEY_CURRENCY, "India");
Log.d("vaaaaa", " == " + cur_sym);
if (cur_sym.equalsIgnoreCase("India")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.India);
} else if (cur_sym.equalsIgnoreCase("US")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.United_States);
} else if (cur_sym.equalsIgnoreCase("Japan")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Japan);
} else if (cur_sym.equalsIgnoreCase("England")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.England_pound);
} else if (cur_sym.equalsIgnoreCase("Costa Rica")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Costa);
} else if (cur_sym.equalsIgnoreCase("UK")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.United);
} else if (cur_sym.equalsIgnoreCase("Phillipines")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Philippines);
} else if (cur_sym.equalsIgnoreCase("Mangolia")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Macedonia);
} else if (cur_sym.equalsIgnoreCase("Australia")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Australia);
} else if (cur_sym.equalsIgnoreCase("Europ")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Euro);
}
}
private int getMonthName(String month1) {
switch (month1.toLowerCase().toString()) {
case "Jan":
monthname = 1;
break;
case "Feb":
monthname = 2;
break;
case "Mar":
monthname = 3;
break;
case "Apr":
monthname = 4;
break;
case "May":
monthname = 5;
break;
case "Jun":
monthname = 6;
break;
case "Jul":
monthname = 7;
break;
case "Aug":
monthname = 8;
break;
case "Sep":
monthname = 9;
break;
case "Oct":
monthname = 10;
break;
case "Nov":
monthname = 11;
break;
case "Dec":
monthname = 12;
break;
default:
break;
}
return monthname;
}
#Override
public int getCount() {
return monthName.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View conView, ViewGroup parent) {
ViewHolder vh;
if (conView == null) {
conView = LayoutInflater.from(contextAddBank).inflate(
R.layout.transaction_list, null, false);
vh = new ViewHolder();
vh.tvDate = (TextView) conView.findViewById(R.id.tvDate);
vh.rvList = (ListView) conView
.findViewById(R.id.lvDisplayExpenseList);
vh.tvIncomeMoney = (TextView) conView
.findViewById(R.id.tvIncomeMoney);
vh.tvExpenseMoney = (TextView) conView
.findViewById(R.id.tvExpenseMoney);
vh.tvRecordnotFound = (TextView) conView
.findViewById(R.id.tvrecordnotFound);
vh.tvIncomeSymblIncomeDisp = (TextView) conView
.findViewById(R.id.tvIncomeSymblIncomeDisp);
vh.tvMoneyCurrencyExpense = (TextView) conView
.findViewById(R.id.tvMoneyCurrencyExpense);
vh.tvMoneyCurrencyIncome = (TextView) conView
.findViewById(R.id.tvMoneyCurrencyIncome);
adapter = new DataBaseAdapter(contextAddBank);
arrDateDebit = new ArrayList<String>();
arrAmountDebit = new ArrayList<Double>();
arrDateCredit = new ArrayList<String>();
arrAmountCredit = new ArrayList<Double>();
epref = EPreferences.getInstance(contextAddBank);
incomes = new ArrayList<Income>();
expense = new ArrayList<Expense>();
getPrefData();
vh.tvMoneyCurrencyExpense.setText(currencySymbl);
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
adapter.open();
adapter.close();
conView.setTag(vh);
} else {
vh = (ViewHolder) conView.getTag();
}
expense.clear();
incomes.clear();
arrDateCredit.clear();
arrAmountCredit.clear();
arrDateDebit.clear();
arrAmountDebit.clear();
adapter.open();
// viewHolder.rvList.setAdapter(Adapter);
incomes = adapter.read_income();
expense = adapter.read_expense();
double totalExpense = 0.0;
double totalIncome = 0.0;
DisplayMonth month = monthName.get(position);
vh.tvDate.setText(month.getMonth() + " " + yr);
months = month.getMonth();
Log.d("tagNameAdapter",
"name is " + bankNameForMatch + ":::" + month.getMonth());
Log.d("expencesize", "size is " + expense.size());
// expense = adapter.read_expense_with_bankName(bankNameForMatch,
// bankAccNoForMatch);
if (expense.size() > 0) {
for (int l = 0; l < expense.size(); l++) {
Log.d("tagbankfil",
"" + bankNameForMatch + "=="
+ expense.get(l).getBankname() + " AND "
+ expense.get(l).getAccno() + "=="
+ bankAccNoForMatch);
if (bankNameForMatch.equals(expense.get(l).getBankname())
&& bankAccNoForMatch.substring(
bankAccNoForMatch.length() - 3)
.equalsIgnoreCase(
expense.get(l)
.getAccno()
.substring(
expense.get(l)
.getAccno()
.length() - 3))) {
dateExpense = expense.get(l).getDate();
expenseAmount = expense.get(l).getAmount();
Log.i("ExpenseAmount", expenseAmount + ":::::"
+ dateExpense);
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
StringTokenizer tokensIncome = new StringTokenizer(
dateExpense, "-");
String firstDate = tokensIncome.nextToken();
String secondMonth = tokensIncome.nextToken();
thirdYear = tokensIncome.nextToken();
monthsInIntExpense = Integer.parseInt(secondMonth);
int totalYear = Integer.parseInt(thirdYear);
Log.i("MonthNameExpense", totalYear + "");
Log.i("MonthSplitExpense", firstDate + " " + secondMonth
+ " " + thirdYear);
// for (int jmon = 0; jmon < expense.size(); jmon++) {
Log.i("loopTimes", "Check");
SimpleDateFormat sdfSource = new SimpleDateFormat(
"dd-MM-yyyy");
Date dateVal = null;
Log.i("axisbankdateval", dateVal + "");
try {
dateVal = sdfSource.parse(dateExpense);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdfDestination = new SimpleDateFormat(
"dd-MMM-yyyy");
convertDate = sdfDestination.format(dateVal);
String[] parts = convertDate.split("-");
String transactionMonth = parts[1];
String transactionYear = parts[2];
Log.i("allYear", year + " ");
monthNameInStringExpense = getMonthName(transactionMonth);
Log.i("finddate", convertDate + ":::" + transactionMonth
+ ":::" + monthNameInStringExpense + "::"
+ transactionYear);
Log.d("tagmonth", "" + month.getMonth() + " ::: "
+ transactionMonth + " ---- " + totalYear + "::::"
+ year);
if (month.getMonth().contains(transactionMonth)
&& totalYear == year) {
emptyExpenseAmount = vh.tvExpenseMoney.getText()
.toString();
Log.i("dateAmount", " " + expense.get(l).getAmount()
+ " " + expense.get(l).getDate());
arrDateDebit.add(expense.get(l).getDate());
arrAmountDebit.add(expense.get(l).getAmount());
totalExpense += expense.get(l).getAmount();
DecimalFormat decimalFormatExpense = new DecimalFormat(
"0.#");
String finalTotalExpense = decimalFormatExpense
.format(Double.valueOf(totalExpense));
String valTvExpenseAmt = new BigDecimal(
finalTotalExpense).toPlainString();
vh.tvExpenseMoney.setText(String.format("%,.00f",
(double) Double.parseDouble(valTvExpenseAmt))
+ " " + currencySymbl);
if (totalExpense == 0.0) {
vh.tvExpenseMoney.setText("0.0");
vh.tvMoneyCurrencyExpense.setText(currencySymbl);
} else {
if (vh.tvRecordnotFound.getVisibility() == View.VISIBLE) {
vh.tvRecordnotFound.setVisibility(View.GONE);
vh.tvMoneyCurrencyExpense
.setVisibility(View.INVISIBLE);
vh.tvExpenseMoney.setText(" " + totalExpense
+ " " + currencySymbl);
vh.tvMoneyCurrencyExpense
.setText(currencySymbl);
}
}
}
}
}
}
if (incomes.size() > 0) {
for (int j = 0; j < incomes.size(); j++) {
Log.d("tagbankfil",
"" + bankNameForMatch + "=="
+ incomes.get(j).getIncome_bankname() + " AND "
+ incomes.get(j).getIncome_accno() + "=="
+ bankAccNoForMatch);
if (bankNameForMatch
.equals(incomes.get(j).getIncome_bankname())
&& bankAccNoForMatch
.substring(bankAccNoForMatch.length() - 3)
.equalsIgnoreCase(
incomes.get(j)
.getIncome_accno()
.substring(
incomes.get(j)
.getIncome_accno()
.length() - 3))) {
dateIncome = incomes.get(j).getIncome_date();
incomeAmount = incomes.get(j).getIncome_amount();
Log.i("IncomeAmount", incomeAmount + ":::::" + dateIncome);
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
StringTokenizer tokensIncome = new StringTokenizer(
dateIncome, "-");
String firstDate = tokensIncome.nextToken();
String secondMonth = tokensIncome.nextToken();
thirdYear = tokensIncome.nextToken();
monthsInIntIncome = Integer.parseInt(thirdYear);
int totalYear = Integer.parseInt(thirdYear);
Log.i("MonthNameIncome", monthsInIntIncome + " " + ""
+ monthNameInStringIncome + " " + dateIncome + " "
+ incomes.size() + "" + totalYear);
Log.i("MonthSplitIncome", firstDate + " " + secondMonth
+ " " + thirdYear);
Log.i("loopTimes", "Check");
SimpleDateFormat sdfSource = new SimpleDateFormat(
"dd-MM-yyyy");
Date dateVal = null;
Log.i("axisbankdateval", dateVal + "");
try {
dateVal = sdfSource.parse(dateIncome);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdfDestination = new SimpleDateFormat(
"dd-MMM-yyyy");
convertDate = sdfDestination.format(dateVal);
String[] parts = convertDate.split("-");
String transactionMonth = parts[1];
String transactionYear = parts[2];
monthNameInStringIncome = getMonthName(transactionMonth);
Log.i("finddate", convertDate + "::" + monthname + "::"
+ monthNameInStringIncome);
if (month.getMonth().contains(transactionMonth)
&& totalYear == year) {
emptyIncomeAmount = vh.tvIncomeMoney.getText()
.toString();
arrDateCredit.add(incomes.get(j).getIncome_date());
arrAmountCredit.add(incomes.get(j).getIncome_amount());
totalIncome += incomes.get(j).getIncome_amount();
DecimalFormat decimalFormatIncome = new DecimalFormat(
"0.#");
String finalTotalIncome = decimalFormatIncome
.format(Double.valueOf(totalIncome));
String valTvIncomeAmt = new BigDecimal(finalTotalIncome)
.toPlainString();
vh.tvIncomeMoney.setText(String.format("%,.00f",
(double) Double.parseDouble(valTvIncomeAmt))
+ " ");
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
if (totalIncome == 0.0) {
vh.tvIncomeMoney.setText("0.0");
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
} else {
if (vh.tvRecordnotFound.getVisibility() == View.VISIBLE) {
vh.tvRecordnotFound.setVisibility(View.GONE);
vh.tvIncomeMoney.setText(" " + totalIncome
+ " " + currencySymbl);
}
}
}
}
}
Log.i("currentYear", year + "" + thirdYear);
}
CategoryList categoryListAdapter = new CategoryList(contextAddBank,
arrDateDebit, arrAmountDebit, arrDateCredit, arrAmountCredit);
vh.rvList.setAdapter(categoryListAdapter);
setListViewHeightBasedOnItems(vh.rvList);
vh.rvList.setScrollContainer(true);
categoryListAdapter.notifyDataSetChanged();
return conView;
}
}

Your application is sticking when you're scrolling down because you're doing all of that processing upon every move when you scroll. Every row is running through the statements of your getView method every single time it's brought back to the screen, phones don't have enough processing power for all of that. You need to separate all of that into a different class, and then load it into the adapter in a smaller data set so that all it has to do is display it. Basically, you're doing processing in the UI(Main) thread, which is bad.
Given how you also have nested listViews, changing to an expandedListView would also be a lot easier for you in the grand scheme of things, may do the job better. Here's a tutorial for it: https://www.youtube.com/watch?v=BkazaAeeW1Q

Related

How to fix Runtime Exception Unable to start Activity

06-28 17:05:23.694 13262-13262/io.hypertrack.sendeta.debug
E/AndroidRuntime: FATAL EXCEPTION: main
Process: io.hypertrack.sendeta.debug, PID: 13262
java.lang.RuntimeException: Unable to start activity ComponentInfo{io.hypertrack.sendeta.debug/io.hypertrack.sendeta.activities.MainActivity}:
android.view.InflateException: Binary XML file line #4: Error
inflating class java.lang.reflect.Constructor
io.hypertrack.sendeta.activities.MainActivity.onCreate(MainActivity.java:109)
public class MainActivity extends AppCompatActivity implements LocationListener {
protected static final int MY_PERMISSIONS_ACCESS_FINE_LOCATION = 1;
// Time in milliseconds; only reload weather if last update is longer ago than this value
private static final int NO_UPDATE_REQUIRED_THRESHOLD = 300000;
private static Map<String, Integer> speedUnits = new HashMap<>(3);
private static Map<String, Integer> pressUnits = new HashMap<>(3);
private static boolean mappingsInitialised = false;
Typeface weatherFont;
Weather todayWeather = new Weather();
TextView todayTemperature;
TextView todayDescription;
TextView todayWind;
TextView todayPressure;
TextView todayHumidity;
TextView todaySunrise;
TextView todaySunset;
TextView lastUpdate;
TextView todayIcon;
ViewPager viewPager;
TabLayout tabLayout;
View appView;
LocationManager locationManager;
ProgressDialog progressDialog;
int theme;
boolean destroyed = false;
private List<Weather> longTermWeather = new ArrayList<>();
private List<Weather> longTermTodayWeather = new ArrayList<>();
private List<Weather> longTermTomorrowWeather = new ArrayList<>();
public String recentCity = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// Initialize the associated SharedPreferences file with default values
PreferenceManager.setDefaultValues(this, R.xml.prefs, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
setTheme(theme = getTheme(prefs.getString("theme", "fresh")));
boolean darkTheme = theme == R.style.AppTheme_NoActionBar_Dark ||
theme == R.style.AppTheme_NoActionBar_Classic_Dark;
boolean blackTheme = theme == R.style.AppTheme_NoActionBar_Black ||
theme == R.style.AppTheme_NoActionBar_Classic_Black;
// Initiate activity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
appView = findViewById(R.id.viewApp);
progressDialog = new ProgressDialog(MainActivity.this);
// Load toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (darkTheme) {
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Dark);
} else if (blackTheme) {
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Black);
}
// Initialize textboxes
todayTemperature = (TextView) findViewById(R.id.todayTemperature);
todayDescription = (TextView) findViewById(R.id.todayDescription);
todayWind = (TextView) findViewById(R.id.todayWind);
todayPressure = (TextView) findViewById(R.id.todayPressure);
todayHumidity = (TextView) findViewById(R.id.todayHumidity);
todaySunrise = (TextView) findViewById(R.id.todaySunrise);
todaySunset = (TextView) findViewById(R.id.todaySunset);
lastUpdate = (TextView) findViewById(R.id.lastUpdate);
todayIcon = (TextView) findViewById(R.id.todayIcon);
weatherFont = Typeface.createFromAsset(this.getAssets(), "fonts/weather.ttf");
todayIcon.setTypeface(weatherFont);
// Initialize viewPager
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
destroyed = false;
initMappings();
// Preload data from cache
preloadWeather();
updateLastUpdateTime();
// Set autoupdater
AlarmReceiver.setRecurringAlarm(this);
}
public WeatherRecyclerAdapter getAdapter(int id) {
WeatherRecyclerAdapter weatherRecyclerAdapter;
if (id == 0) {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermTodayWeather);
} else if (id == 1) {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermTomorrowWeather);
} else {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermWeather);
}
return weatherRecyclerAdapter;
}
#Override
public void onStart() {
super.onStart();
updateTodayWeatherUI();
updateLongTermWeatherUI();
}
#Override
public void onResume() {
super.onResume();
if (getTheme(PreferenceManager.getDefaultSharedPreferences(this).getString("theme", "fresh")) != theme) {
// Restart activity to apply theme
overridePendingTransition(0, 0);
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
} else if (shouldUpdate() && isNetworkAvailable()) {
getTodayWeather();
getLongTermWeather();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
destroyed = true;
if (locationManager != null) {
try {
locationManager.removeUpdates(MainActivity.this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
private void preloadWeather() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String lastToday = sp.getString("lastToday", "");
if (!lastToday.isEmpty()) {
new TodayWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastToday);
}
String lastLongterm = sp.getString("lastLongterm", "");
if (!lastLongterm.isEmpty()) {
new LongTermWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastLongterm);
}
}
private void getTodayWeather() {
new TodayWeatherTask(this, this, progressDialog).execute();
}
private void getLongTermWeather() {
new LongTermWeatherTask(this, this, progressDialog).execute();
}
private void searchCities() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(this.getString(R.string.search_title));
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setMaxLines(1);
input.setSingleLine(true);
alert.setView(input, 32, 0, 32, 0);
alert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String result = input.getText().toString();
if (!result.isEmpty()) {
saveLocation(result);
}
}
});
alert.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Cancelled
}
});
alert.show();
}
private void saveLocation(String result) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
recentCity = preferences.getString("city", Constants.DEFAULT_CITY);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("city", result);
editor.commit();
if (!recentCity.equals(result)) {
// New location, update weather
getTodayWeather();
getLongTermWeather();
}
}
private void aboutDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Forecastie");
final WebView webView = new WebView(this);
String about = "<p>1.6.1</p>" +
"<p>A lightweight, opensource weather app.</p>" +
"<p>Developed by <a href='mailto:t.martykan#gmail.com'>Tomas Martykan</a></p>" +
"<p>Data provided by <a href='https://openweathermap.org/'>OpenWeatherMap</a>, under the <a href='http://creativecommons.org/licenses/by-sa/2.0/'>Creative Commons license</a>" +
"<p>Icons are <a href='https://erikflowers.github.io/weather-icons/'>Weather Icons</a>, by <a href='http://www.twitter.com/artill'>Lukas Bischoff</a> and <a href='http://www.twitter.com/Erik_UX'>Erik Flowers</a>, under the <a href='http://scripts.sil.org/OFL'>SIL OFL 1.1</a> licence.";
TypedArray ta = obtainStyledAttributes(new int[]{android.R.attr.textColorPrimary, R.attr.colorAccent});
String textColor = String.format("#%06X", (0xFFFFFF & ta.getColor(0, Color.BLACK)));
String accentColor = String.format("#%06X", (0xFFFFFF & ta.getColor(1, Color.BLUE)));
ta.recycle();
about = "<style media=\"screen\" type=\"text/css\">" +
"body {\n" +
" color:" + textColor + ";\n" +
"}\n" +
"a:link {color:" + accentColor + "}\n" +
"</style>" +
about;
webView.setBackgroundColor(Color.TRANSPARENT);
webView.loadData(about, "text/html", "UTF-8");
alert.setView(webView, 32, 0, 32, 0);
alert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
private String setWeatherIcon(int actualId, int hourOfDay) {
int id = actualId / 100;
String icon = "";
if (actualId == 800) {
if (hourOfDay >= 7 && hourOfDay < 20) {
icon = this.getString(R.string.weather_sunny);
} else {
icon = this.getString(R.string.weather_clear_night);
}
} else {
switch (id) {
case 2:
icon = this.getString(R.string.weather_thunder);
break;
case 3:
icon = this.getString(R.string.weather_drizzle);
break;
case 7:
icon = this.getString(R.string.weather_foggy);
break;
case 8:
icon = this.getString(R.string.weather_cloudy);
break;
case 6:
icon = this.getString(R.string.weather_snowy);
break;
case 5:
icon = this.getString(R.string.weather_rainy);
break;
}
}
return icon;
}
public static String getRainString(JSONObject rainObj) {
String rain = "0";
if (rainObj != null) {
rain = rainObj.optString("3h", "fail");
if ("fail".equals(rain)) {
rain = rainObj.optString("1h", "0");
}
}
return rain;
}
private ParseResult parseTodayJson(String result) {
try {
JSONObject reader = new JSONObject(result);
final String code = reader.optString("cod");
if ("404".equals(code)) {
return ParseResult.CITY_NOT_FOUND;
}
String city = reader.getString("name");
String country = "";
JSONObject countryObj = reader.optJSONObject("sys");
if (countryObj != null) {
country = countryObj.getString("country");
todayWeather.setSunrise(countryObj.getString("sunrise"));
todayWeather.setSunset(countryObj.getString("sunset"));
}
todayWeather.setCity(city);
todayWeather.setCountry(country);
JSONObject coordinates = reader.getJSONObject("coord");
if (coordinates != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon")).putFloat("longitude", (float) coordinates.getDouble("lat")).commit();
}
JSONObject main = reader.getJSONObject("main");
todayWeather.setTemperature(main.getString("temp"));
todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description"));
JSONObject windObj = reader.getJSONObject("wind");
todayWeather.setWind(windObj.getString("speed"));
if (windObj.has("deg")) {
todayWeather.setWindDirectionDegree(windObj.getDouble("deg"));
} else {
Log.e("parseTodayJson", "No wind direction available");
todayWeather.setWindDirectionDegree(null);
}
todayWeather.setPressure(main.getString("pressure"));
todayWeather.setHumidity(main.getString("humidity"));
JSONObject rainObj = reader.optJSONObject("rain");
String rain;
if (rainObj != null) {
rain = getRainString(rainObj);
} else {
JSONObject snowObj = reader.optJSONObject("snow");
if (snowObj != null) {
rain = getRainString(snowObj);
} else {
rain = "0";
}
}
todayWeather.setRain(rain);
final String idString = reader.getJSONArray("weather").getJSONObject(0).getString("id");
todayWeather.setId(idString);
todayWeather.setIcon(setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY)));
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("lastToday", result);
editor.commit();
} catch (JSONException e) {
Log.e("JSONException Data", result);
e.printStackTrace();
return ParseResult.JSON_EXCEPTION;
}
return ParseResult.OK;
}
private void updateTodayWeatherUI() {
try {
if (todayWeather.getCountry().isEmpty()) {
preloadWeather();
return;
}
} catch (Exception e) {
preloadWeather();
return;
}
String city = todayWeather.getCity();
String country = todayWeather.getCountry();
DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(getApplicationContext());
getSupportActionBar().setTitle(city + (country.isEmpty() ? "" : ", " + country));
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
// Temperature
float temperature = UnitConvertor.convertTemperature(Float.parseFloat(todayWeather.getTemperature()), sp);
if (sp.getBoolean("temperatureInteger", false)) {
temperature = Math.round(temperature);
}
// Rain
double rain = Double.parseDouble(todayWeather.getRain());
String rainString = UnitConvertor.getRainString(rain, sp);
// Wind
double wind;
try {
wind = Double.parseDouble(todayWeather.getWind());
} catch (Exception e) {
e.printStackTrace();
wind = 0;
}
wind = UnitConvertor.convertWind(wind, sp);
// Pressure
double pressure = UnitConvertor.convertPressure((float) Double.parseDouble(todayWeather.getPressure()), sp);
todayTemperature.setText(new DecimalFormat("0.#").format(temperature) + " " + sp.getString("unit", "°C"));
todayDescription.setText(todayWeather.getDescription().substring(0, 1).toUpperCase() +
todayWeather.getDescription().substring(1) + rainString);
if (sp.getString("speedUnit", "m/s").equals("bft")) {
todayWind.setText(getString(R.string.wind) + ": " +
UnitConvertor.getBeaufortName((int) wind) +
(todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : ""));
} else {
todayWind.setText(getString(R.string.wind) + ": " + new DecimalFormat("0.0").format(wind) + " " +
localize(sp, "speedUnit", "m/s") +
(todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : ""));
}
todayPressure.setText(getString(R.string.pressure) + ": " + new DecimalFormat("0.0").format(pressure) + " " +
localize(sp, "pressureUnit", "hPa"));
todayHumidity.setText(getString(R.string.humidity) + ": " + todayWeather.getHumidity() + " %");
todaySunrise.setText(getString(R.string.sunrise) + ": " + timeFormat.format(todayWeather.getSunrise()));
todaySunset.setText(getString(R.string.sunset) + ": " + timeFormat.format(todayWeather.getSunset()));
todayIcon.setText(todayWeather.getIcon());
}
public ParseResult parseLongTermJson(String result) {
int i;
try {
JSONObject reader = new JSONObject(result);
final String code = reader.optString("cod");
if ("404".equals(code)) {
if (longTermWeather == null) {
longTermWeather = new ArrayList<>();
longTermTodayWeather = new ArrayList<>();
longTermTomorrowWeather = new ArrayList<>();
}
return ParseResult.CITY_NOT_FOUND;
}
longTermWeather = new ArrayList<>();
longTermTodayWeather = new ArrayList<>();
longTermTomorrowWeather = new ArrayList<>();
JSONArray list = reader.getJSONArray("list");
for (i = 0; i < list.length(); i++) {
Weather weather = new Weather();
JSONObject listItem = list.getJSONObject(i);
JSONObject main = listItem.getJSONObject("main");
weather.setDate(listItem.getString("dt"));
weather.setTemperature(main.getString("temp"));
weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description"));
JSONObject windObj = listItem.optJSONObject("wind");
if (windObj != null) {
weather.setWind(windObj.getString("speed"));
weather.setWindDirectionDegree(windObj.getDouble("deg"));
}
weather.setPressure(main.getString("pressure"));
weather.setHumidity(main.getString("humidity"));
JSONObject rainObj = listItem.optJSONObject("rain");
String rain = "";
if (rainObj != null) {
rain = getRainString(rainObj);
} else {
JSONObject snowObj = listItem.optJSONObject("snow");
if (snowObj != null) {
rain = getRainString(snowObj);
} else {
rain = "0";
}
}
weather.setRain(rain);
final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id");
weather.setId(idString);
final String dateMsString = listItem.getString("dt") + "000";
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Long.parseLong(dateMsString));
weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY)));
Calendar today = Calendar.getInstance();
if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
longTermTodayWeather.add(weather);
} else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) {
longTermTomorrowWeather.add(weather);
} else {
longTermWeather.add(weather);
}
}
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("lastLongterm", result);
editor.commit();
} catch (JSONException e) {
Log.e("JSONException Data", result);
e.printStackTrace();
return ParseResult.JSON_EXCEPTION;
}
return ParseResult.OK;
}
private void updateLongTermWeatherUI() {
if (destroyed) {
return;
}
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
Bundle bundleToday = new Bundle();
bundleToday.putInt("day", 0);
RecyclerViewFragment recyclerViewFragmentToday = new RecyclerViewFragment();
recyclerViewFragmentToday.setArguments(bundleToday);
viewPagerAdapter.addFragment(recyclerViewFragmentToday, getString(R.string.today));
Bundle bundleTomorrow = new Bundle();
bundleTomorrow.putInt("day", 1);
RecyclerViewFragment recyclerViewFragmentTomorrow = new RecyclerViewFragment();
recyclerViewFragmentTomorrow.setArguments(bundleTomorrow);
viewPagerAdapter.addFragment(recyclerViewFragmentTomorrow, getString(R.string.tomorrow));
Bundle bundle = new Bundle();
bundle.putInt("day", 2);
RecyclerViewFragment recyclerViewFragment = new RecyclerViewFragment();
recyclerViewFragment.setArguments(bundle);
viewPagerAdapter.addFragment(recyclerViewFragment, getString(R.string.later));
int currentPage = viewPager.getCurrentItem();
viewPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
if (currentPage == 0 && longTermTodayWeather.isEmpty()) {
currentPage = 1;
}
viewPager.setCurrentItem(currentPage, false);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private boolean shouldUpdate() {
long lastUpdate = PreferenceManager.getDefaultSharedPreferences(this).getLong("lastUpdate", -1);
boolean cityChanged = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("cityChanged", false);
// Update if never checked or last update is longer ago than specified threshold
return cityChanged || lastUpdate < 0 || (Calendar.getInstance().getTimeInMillis() - lastUpdate) > NO_UPDATE_REQUIRED_THRESHOLD;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}

Error in getting list position in Android

View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.img_smc_add:
int addPos = Integer.parseInt("" + v.getTag());
int addQty = Integer.parseInt("" + mArrListMyCart.get(addPos).getmStrQty());
addQty++;
mArrListMyCart.get(addPos).setmStrQty("" + addQty);
myCartAdapter.notifyDataSetChanged();
mJsonObject = new JSONObject();
JSONObject option = new JSONObject();
try {
mJsonObject.put("productid", mArrListMyCart.get(addPos).getmStrProductId());
mJsonObject.put("itemid", mArrListMyCart.get(addPos).getmStrItemId());
mJsonObject.put("qty", mArrListMyCart.get(addPos).getmStrQty());
mJsonObject.put("shoppingcartid", shoppingcartid);
mJsonObject.put("customerid", "" + SessionClass.getUserId(getActivity()));
// option.put("options", "");
mJsonObject.put("options", "" + option);
} catch (JSONException e) {
e.printStackTrace();
}
editCartDetail();
myCartAdapter.notifyDataSetChanged();
//calculateGrandTotal();
break;
case R.id.img_smc_remove:
int removePos = Integer.parseInt("" + v.getTag());
int removeQty = Integer.parseInt("" + mArrListMyCart.get(removePos).getmStrQty());
if (removeQty > 1) {
removeQty--;
mArrListMyCart.get(removePos).setmStrQty("" + removeQty);
myCartAdapter.notifyDataSetChanged();
} else {
removeQty = 1;
mArrListMyCart.get(removePos).setmStrQty("" + removeQty);
myCartAdapter.notifyDataSetChanged();
}
myCartAdapter.notifyDataSetChanged();
mJsonObject = new JSONObject();
option = new JSONObject();
try {
mJsonObject.put("productid", mArrListMyCart.get(removePos).getmStrProductId());
mJsonObject.put("itemid", mArrListMyCart.get(removePos).getmStrItemId());
mJsonObject.put("qty", mArrListMyCart.get(removePos).getmStrQty());
mJsonObject.put("shoppingcartid", "" + shoppingcartid);
mJsonObject.put("customerid", "" + SessionClass.getUserId(getActivity()));
Log.e("customerid", "" + SessionClass.getUserId(getActivity()));
// option.put("options", "");
mJsonObject.put("options", "" + option);
} catch (JSONException e) {
e.printStackTrace();
}
editCartDetail();
//getMyCartItems();
myCartAdapter.notifyDataSetChanged();
// calculateGrandTotal();
break;
case R.id.iv_edit_cart_item:
FragmentManager fm=getActivity().getSupportFragmentManager();
Fragment fragment = new ProductDetailActivity();
int updatePos = v.getTag() != null ? Integer.parseInt("" + v.getTag()):0;
Toast.makeText(getActivity(),"updatePos:"+ updatePos,Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString("key","update");
bundle.putString("product_id", mArrListMyCart.get(updatePos).getmStrProductId());
bundle.putString("item_id", mArrListMyCart.get(updatePos).getmStrItemId());
fragment.setArguments(bundle);
// showAlert("Product id-->" + mArrListMyCart.get(Integer.parseInt(""+v.getTag())).getmStrProductId(), -1);
fm.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack("").commit();
break;
case R.id.iv_remove_cart_item:
int cartPos = Integer.parseInt("" + v.getTag());
int cartQty = Integer.parseInt("" + mArrListMyCart.get(cartPos).getmStrQty());
item_id = mArrListMyCart.get(cartPos).getmStrItemId();
product_id = mArrListMyCart.get(cartPos).getmStrProductId();
getDeleteCartItems();
mArrListMyCart.remove(cartPos);
//getMyCartItems();
myCartAdapter.notifyDataSetChanged();
if (cartQty > 1) {
mArrListMyCart.remove(cartPos);
myCartAdapter.notifyDataSetChanged();
} else {
removeQty = 1;
}
//calculateGrandTotal();
break;
case R.id.tv_show_details:
int pos = Integer.parseInt("" + v.getTag());
item_id = mArrListMyCart.get(pos).getmStrItemId();
product_id = mArrListMyCart.get(pos).getmStrProductId();
Toast.makeText(getActivity(),"updatePos:"+ pos,Toast.LENGTH_SHORT).show();
getCartItemDetail();
break;
}
}
};
i created listview based upon list of products.when i'm using below line,
`int updatePos = v.getTag() != null ? Integer.parseInt("" + v.getTag()):0;`
the updatepos always null.so if i select e.g a[3] product but it show always a[0] product details.how to solve it?.the updatePos is not update based upon selecting item in list.always the updatePos is 0.what can i do?

android studio app case insensitive search from sqlite

I am working on a android application with sqlite database that store lots of standard english texts that have uppercase and lowercase words and it shows on the app, we have a search that right now is case sensitive and scroll between them with cursor
How I can return search string case insensitive from sqlite
this is my code on database
public List<String> getSearchedParagraph(String p) {
String sectionId = "";
List<String> result = new ArrayList<String>();
String query = "SELECT Distinct(sectionId) FROM paragraph where txt Like '%"
+p+ "%'";
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
result.add(cursor.getString(0));
cursor.moveToNext();
}
}
return result;
}
i tested String query = "SELECT Distinct(sectionId) FROM paragraph where txt Like '%" +p+ "%' COLLATE NOCASE"; but still no change
UPDATE1 this is setWordSearch function:
public void setWordSearch(String str) {
wordSearch = str;
for (FragmentPage page : fragments) {
page.wordSearch = str;
}
notifyDataSetChanged();
}
UPDATE2 This is the FragmentPage:
public class FragmentPage extends Fragment {
VasiatClass v;
public String SectionId;
public List<VasiatClass> paragraph;
public String wordSearch;
private ScrollView sv;
static MediaPlayer player = new MediaPlayer();
View view;
private List<RelativeLayout> jtxtvwList = new ArrayList<RelativeLayout>();
RelativeLayout rl = null;
float position_x = 0, position_y = 0;
private int playingParagraphPosition;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.SectionId = String.valueOf(getArguments().getInt("sectionId"));
this.wordSearch = getArguments().getString("wordSearch");
Log.i("FRAGMENTPAGE",
"sectionId is :"
+ String.valueOf(getArguments().getInt("sectionId")));
DataBaseHelper myDbHelper = new DataBaseHelper(this.getActivity());
myDbHelper = new DataBaseHelper(this.getActivity());
wordSearch = getArguments().getString("wordSearch");
try {
myDbHelper.createDataBase();
myDbHelper.openDataBase();
this.paragraph = myDbHelper.getParagraph(SectionId);
myDbHelper.close();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
};
public String getSection() {
return SectionId;
}
public FragmentPage() {
// TODO Auto-generated constructor stub
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_vasiatpage, container,
false);
this.view = view;
LinearLayout ll = (LinearLayout) view.findViewById(R.id.llId);
ll.setPadding(20, 20, 20, 20);
LinearLayout.LayoutParams linLayoutParam = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
linLayoutParam.setMargins(20, 20, 20, 20);
sv = (ScrollView) view.findViewById(R.id.scrollView1);
for (int i = 0; i <= paragraph.size() - 1; i++) {
final int j = i;
final RelativeLayout rel = new RelativeLayout(getActivity());
// Button b = new Button(getActivity());
// b.setBackgroundColor(Color.TRANSPARENT);
// b.setTextColor(Color.TRANSPARENT);
JustifiedTextView textView = new JustifiedTextView(getActivity());
/************************************/
textView.setOnTouchListener(new OnTouchListener() {
public final static int FINGER_RELEASED = 0;
public final static int FINGER_TOUCHED = 1;
public final static int FINGER_DRAGGING = 2;
public final static int FINGER_UNDEFINED = 3;
private int fingerState = FINGER_RELEASED;
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
int action = arg1.getAction();
boolean check = true;
switch (action) {
case MotionEvent.ACTION_DOWN:
position_x = arg1.getX();
position_y = arg1.getY();
Log.i("ACTIONS", "Ation down -- position_x:"
+ position_x + " ,position_Y" + position_y);
check = true;
if (fingerState == FINGER_RELEASED)
fingerState = FINGER_TOUCHED;
else
fingerState = FINGER_UNDEFINED;
break;
case MotionEvent.ACTION_MOVE:
if (fingerState == FINGER_TOUCHED
|| fingerState == FINGER_DRAGGING)
fingerState = FINGER_DRAGGING;
else
fingerState = FINGER_UNDEFINED;
check = false;
break;
case MotionEvent.ACTION_UP:
Log.i("ACTIONS",
"Ation up -- position_x:" + arg1.getX()
+ " ,position_Y" + arg1.getY());
if (Math.abs((arg1.getX() - position_x)) < 10
&& Math.abs((arg1.getY() - position_y)) < 10) {
List<String> audioList = new ArrayList<String>();
playingParagraphPosition = j;
((VasiatText) getActivity())
.playParagraph(paragraph.get(j)
.getFilename() + "_MP3.mp3", j,
FragmentPage.this);
if (rl != null) {
rl.setBackgroundColor(Color.TRANSPARENT);
}
rel.setBackgroundColor(Color.LTGRAY);
rl = rel;
}
break;
default:
fingerState = FINGER_UNDEFINED;
break;
}
return false;
}
});
/********************************************/
// textView.getSettings().setFixedFontFamily("Swissra Light.otf");
String str = paragraph.get(i).getTxt().toString();
int subStringStart = 0;
int startIndex = 0;
StringBuilder sb = new StringBuilder();
if (wordSearch != null && !wordSearch.equals("")) {
startIndex = str.indexOf(wordSearch);
while (startIndex != -1) {
sb.append(str.substring(subStringStart, startIndex)
+ "<span style=\"background-color:#ffff00\">"
+ str.substring(startIndex,
startIndex + wordSearch.length())
+ "</span>");
subStringStart = startIndex + wordSearch.length();
startIndex = str.indexOf(wordSearch, subStringStart);
}
sb.append(str.substring(subStringStart));
}
if (!sb.toString().equals("")) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
textView.setText(sb.toString());
} else
textView.setTextNoJustify(sb.toString());
// b.setText(sb.toString());
} else {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
textView.setText(str);
} else
textView.setTextNoJustify(str);
// b.setText(str);
}
textView.setId(i);
textView.setTag(Integer.valueOf(paragraph.get(i).getId()));
rel.addView(textView);
jtxtvwList.add(rel);
ll.addView(rel);
}
return view;
}
thanks
as #CL mentioned, you can use Patterns,
just replace this code:
if (wordSearch != null && !wordSearch.equals("")) {
startIndex = str.indexOf(wordSearch);
while (startIndex != -1) {
sb.append(str.substring(subStringStart, startIndex)
+ "<span style=\"background-color:#ffff00\">"
+ str.substring(startIndex,
startIndex + wordSearch.length())
+ "</span>");
subStringStart = startIndex + wordSearch.length();
startIndex = str.indexOf(wordSearch, subStringStart);
}
sb.append(str.substring(subStringStart));
}
whit this:
Boolean wasFound;
if (wordSearch != null && !wordSearch.equals("")) {
Matcher subMatcher = Pattern.compile(Pattern.quote(wordSearch), Pattern.CASE_INSENSITIVE).matcher(str);
wasFound = subMatcher.find();
while (wasFound) {
startIndex = subMatcher.start();
sb.append(str.substring(subStringStart, startIndex)
+ "<span style=\"background-color:#ffff00\">"
+ str.substring(startIndex,
startIndex + wordSearch.length())
+ "</span>");
subStringStart = startIndex + wordSearch.length();
wasFound = subMatcher.find();
}
sb.append(str.substring(subStringStart));
}
I hope that this help you #n3tg33k ;)
You are using String.indexOf for searching. This function is case sensitive.
You need to search for the substring while ignoring case.
you can achieve it in this way....
public List<String> getSearchedParagraph(String p) {
p=p.toLowerCase();
String sectionId = "";
List<String> result = new ArrayList<String>();
String query = "SELECT Distinct(sectionId) FROM paragraph where LOWER(txt) Like '%"
+p+ "%'";
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
result.add(cursor.getString(0));
cursor.moveToNext();
}
}
return result;
}

getting duplicate objects in json in android

I am putting objects in Json but I want only 1 key to be update.Right now it is creating new object every time function is called I want only quantity should get updated if it is already there in json. Please help
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private List<ProductBean> productList ;
static int qtyValues;
static int itemRem = -1;
static int addItem = 1;
static boolean isSKU1;
static boolean isSKU2;
static boolean isSKU;
static int value;
static int totalAmount = 0;
static int totalItems = 0;
SharedPreferences myPrefs;
SharedPreferences.Editor editor;
private final Activity context;
private AQuery aq;
JSONObject jsonObject = new JSONObject();
JSONArray obj = new JSONArray();
ArrayList list = new ArrayList();
public ProductAdapter(Activity context,List<ProductBean> productList){
this.productList = productList;
this.context = context;
isSKU = true;
}
#Override
public int getItemCount() {
return productList.size();
}
#Override
public void onBindViewHolder(final ProductViewHolder holder, final int position) {
myPrefs = context.getSharedPreferences("qty", Context.MODE_PRIVATE);
editor = myPrefs.edit();
aq = new AQuery(context.getApplicationContext());
final ProductBean productBean = productList.get(position);
holder.extratxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.extratxt.setTextColor(Color.BLACK);
holder.extratxt2.setTextColor(Color.GRAY);
holder.extratxt3.setTextColor(Color.GRAY);
holder.extratxt1.setText(productBean.getProductPrice() + "");
isSKU = true;
isSKU1 = false;
isSKU2 = false;
holder.qtyCounter.setText(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId1(),0)+"");
}
});
holder.extratxt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.extratxt.setTextColor(Color.GRAY);
holder.extratxt2.setTextColor(Color.BLACK);
holder.extratxt3.setTextColor(Color.GRAY);
holder.extratxt1.setText(productBean.getProductPrice2() + "");
isSKU1 = true;
isSKU = false;
isSKU2 = false;
holder.qtyCounter.setText(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId2(),0)+"");
}
});
holder.extratxt3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.extratxt.setTextColor(Color.GRAY);
holder.extratxt2.setTextColor(Color.GRAY);
holder.extratxt3.setTextColor(Color.BLACK);
holder.extratxt1.setText(productBean.getProductPrice3() + "");
isSKU2 = true;
isSKU = false;
isSKU1 = false;
holder.qtyCounter.setText(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId3(),0)+"");
}
});
holder.decreaseQty.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if(isSKU1 == true) {
if(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId2(),0)>0) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0);
qtyValues = qtyValues - 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId2(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0) + "");
value = 0 - productBean.getProductPrice2();
add(itemRem);
amount(value);
}
}
else if (isSKU2 == true){
if(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId3(),0)>0) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0);
qtyValues = qtyValues - 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId3(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0) + "");
value = 0 - productBean.getProductPrice3();
add(itemRem);
amount(value);
}
}
else{
if(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId1(),0)>0) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0);
qtyValues = qtyValues - 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId1(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0) + "");
value = 0 - productBean.getProductPrice();
add(itemRem);
amount(value);
}
}
}
});
holder.increaseQty.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if(isSKU1 == true) {
if(myPrefs.getInt("product"+productBean.getProductId() + productBean.getSkuId2(),0)<10) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0);
qtyValues = qtyValues + 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId2(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0) + "");
value = productBean.getProductPrice2();
add(addItem);
amount(value);
setCartItem(productBean.getSkuId2(),myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId2(), 0),productBean.getProductId(),productBean.getDescription() , productBean.getProductName() , productBean.getProductPrice2());
}
}
else if (isSKU2 == true){
if(myPrefs.getInt("product"+productBean.getProductId() + productBean.getSkuId3(),0)<10) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0);
qtyValues = qtyValues + 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId3(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0) + "");
value = productBean.getProductPrice3();
add(addItem);
amount(value);
setCartItem(productBean.getSkuId3(),myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId3(), 0),productBean.getProductId(),productBean.getDescription() , productBean.getProductName() , productBean.getProductPrice3());
}
}
else{
if(myPrefs.getInt("product"+productBean.getProductId() + productBean.getSkuId1(),0)<10) {
qtyValues = myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0);
qtyValues = qtyValues + 1;
editor.putInt("product" + productBean.getProductId() + productBean.getSkuId1(), qtyValues);
editor.commit();
holder.qtyCounter.setText(myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0) + "");
value = productBean.getProductPrice();
add(addItem);
amount(value);
setCartItem(productBean.getSkuId1(),myPrefs.getInt("product" + productBean.getProductId() + productBean.getSkuId1(), 0),productBean.getProductId(),productBean.getDescription() , productBean.getProductName() , productBean.getProductPrice());
}
}
}
});
holder.txtTitle.setText(productBean.getProductName());
holder.extratxt.setText(productBean.getSkuId1() + "");
holder.extratxt2.setText(productBean.getSkuId2() + "");
holder.extratxt3.setText(productBean.getSkuId3() + "");
holder.extratxt1.setText(productBean.getProductPrice() + "");
holder.imageView1.setImageResource(R.drawable.rupee);
if(myPrefs.getInt("totalItems", 0)>0){
BeveragesMainActivity.cartTotal.setVisibility(View.VISIBLE);
BeveragesMainActivity.totalPrice.setText("Rs " + myPrefs.getInt("totalAmount", 0) + "");
}
BeveragesMainActivity.cartTotal.setText(myPrefs.getInt("totalItems", 0) + "");
holder.qtyCounter.setText(myPrefs.getInt("product"+productBean.getProductId()+productBean.getSkuId1(),0) + "");
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.list_beverages_item, viewGroup, false);
return new ProductViewHolder(itemView);
}
public class ProductViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView extratxt;
TextView extratxt2;
TextView extratxt3;
ImageView imageView1;
TextView extratxt1;
TextView qtyCounter;
ImageView decreaseQty;
ImageView increaseQty;
/**
* Instantiates a new card view holder.
*
* #param v the v
*/
public ProductViewHolder(View v) {
super(v);
imageView = (ImageView) v.findViewById(R.id.drinks);
txtTitle = (TextView) v.findViewById(R.id.drinkTitle);
extratxt = (TextView) v.findViewById(R.id.drinkQuantity);
extratxt2 = (TextView) v.findViewById(R.id.drinkQuantity1);
extratxt3 = (TextView) v.findViewById(R.id.drinkQuantity2);
imageView1 = (ImageView) v.findViewById(R.id.rupee);
extratxt1 = (TextView) v.findViewById(R.id.drinkPrice);
qtyCounter = (TextView) v.findViewById(R.id.drinkCounter);
decreaseQty = (ImageView) v.findViewById(R.id.decreaseCounter);
increaseQty = (ImageView) v.findViewById(R.id.increaseCounter);
extratxt.setTextColor(Color.BLACK);
}
}
public void setCartItem(final int skuId ,final int qty , final long productId , String description , String productName , int price) {
try {
jsonObject.put("skuId",skuId);
jsonObject.put("quantity",qty);
jsonObject.put("productId",productId);
jsonObject.put("price",price);
jsonObject.put("productName",productName);
jsonObject.put("description",description);
obj.put(jsonObject);
editor.putString("data",obj.toString());
editor.commit();
}catch (JSONException e){
e.printStackTrace();
}
}
public void add(int items){
totalItems = totalItems + items;
editor.putInt("totalItems",totalItems);
editor.commit();
if(myPrefs.getInt("totalItems", 0)>0){
BeveragesMainActivity.cartTotal.setVisibility(View.VISIBLE);
}
else{
BeveragesMainActivity.cartTotal.setVisibility(View.INVISIBLE);
}
BeveragesMainActivity.cartTotal.setText(myPrefs.getInt("totalItems", 0) + "");
}
public void amount(int price){
totalAmount = totalAmount+price;
editor.putInt("totalAmount", totalAmount);
editor.commit();
BeveragesMainActivity.totalPrice.setText("Rs " + myPrefs.getInt("totalAmount", 0) + "");
}
}
Use this code inside setCartItem(...) method
// loop through each object
for (int i = 0; i < obj.length(); i++) {
try {
JSONObject item = obj.getJSONObject(i);
int itemId = item.getInt("skuId ");
if (itemId == skuId) {// object already exists update quantity
item.put("quantity", qty);
// update other keys if you want to
// do other stuff
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject jsonObject = new JSONObject();
// If skudId does not exits in the array list add new one
try {
jsonObject.put("skuId", skuId);
jsonObject.put("quantity", qty);
jsonObject.put("productId", productId);
jsonObject.put("price", price);
jsonObject.put("productName", productName);
jsonObject.put("description", description);
obj.put(jsonObject);
editor.putString("data", obj.toString());
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}

Pie Chart Using Achartengine in Android

when i can call this method on different different situation the graph will be plotted, but the problem is that it overlap the previous one. I have tried lot to clear the previous graph but not able to do that. please any one help me to achieve the same.
As I have attach the screenshot also with the entire code in this, on the click of button from date section i want to plot the graph for that particular date.
but you can see in the attached imaged the data will be overlap on previous one only.
thnks.
//imports here
public class NutrientDailyTrackerActivity extends Fragment {
private static int[] COLORS = new int[] { Color.parseColor("#4CC1D2"),Color.parseColor("#FE2E2E"), Color.parseColor("#298A08") };*
private static String[] NAME_LIST = new String[] { "Fat", "Carbs", "Protein"};
private CategorySeries mSeries = new CategorySeries("");
private DefaultRenderer mRenderer = new DefaultRenderer();
private GraphicalView mChartView;
private String formattedDate;
private TextView currentDate;
private ImageView prevMonth;
private ImageView nextMonth;
private TextView dailyfat;
private TextView dailycarbs;
private String checkingdate;
Calendar c;
Calendar d;
SimpleDateFormat df;
Date date1;
Date date2;
DatabaseHandler db ;
private String uniquecaloriestring ;
private String uniquefat;
private String uniquecarbohydrate ;
private String uniqueprotein;
LinearLayout layout=null;
private static final String DATABASE_NAME = "ndietguru.db";
private double ddcalorie ;
private double ddcalorieconsumed ;
private double ddcalorieburned ;
private double ddfatgoal ;
private double ddproteingoal ;
private double ddcarbohydrategoal;
private double dFat;
private double dCarbs;
private double dProteins;
private double dunical ;
private double dunifat ;
private double dunicarbs ;
private double duniprotein;
private int dbtotalfat;
private int dbtotalcarbs;
private int dbtotalproteins;
private int dbcalorie;
private int dbcalorieburned;
View rootView=null;
private double calorie;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_nutrient_details, container, false);
currentDate = (TextView)rootView.findViewById(R.id.currentMonth);
prevMonth = (ImageView)rootView.findViewById(R.id.prevMonth);
nextMonth = (ImageView)rootView.findViewById(R.id.nextMonth);
db = new DatabaseHandler(getActivity());
HashMap<String, String> user = new HashMap<String, String>();
user = db.getUserCalDetails();
uniquefat = (String) user.get("fat");
uniquecarbohydrate = (String) user.get("carbohydrate");
uniqueprotein = (String) user.get("protein");
if(formattedDate == null){
c = Calendar.getInstance();
df = new SimpleDateFormat("yyyy-MM-dd",java.util.Locale.getDefault());
formattedDate = df.format(c.getTime());
try {
date1 = df.parse(formattedDate);
c.setTime(date1);
} catch (ParseException e) {
e.printStackTrace();
}
}
else{
System.out.println("date in fragment" + formattedDate);
c = Calendar.getInstance();
df = new SimpleDateFormat("yyyy-MM-dd",java.util.Locale.getDefault());
System.out.println("inside else");
try {
date1 = df.parse(formattedDate);
c.setTime(date1);
} catch (ParseException e) {
e.printStackTrace();
}
}
//calendar for checking date
d = Calendar.getInstance();
checkingdate = df.format(d.getTime());
try {
date2 = df.parse(checkingdate);
d.setTime(date2);
} catch (ParseException e) {
e.printStackTrace();
}
if(date1.equals(date2))
{
nextMonth.setVisibility(View.GONE);
}
else
{
nextMonth.setVisibility(View.VISIBLE);
}
selectdata();
dbtotalfat = Math.round(dbtotalfat);
dbtotalcarbs = Math.round(dbtotalcarbs);
dbtotalproteins = Math.round(dbtotalproteins);
int[] VALUES = new int[] {dbtotalfat, dbtotalcarbs, dbtotalproteins };
currentDate.setText(formattedDate);
drawGraph(VALUES);
prevMonth.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
c.add(Calendar.DATE, -1);
formattedDate = df.format(c.getTime());
currentDate.setText(formattedDate);
d = Calendar.getInstance();
checkingdate = df.format(d.getTime());
if(formattedDate.equals(checkingdate))
{
nextMonth.setVisibility(View.GONE);
}
else
{
nextMonth.setVisibility(View.VISIBLE);
}
selectprevdata();
dbtotalfat = Math.round(dbtotalfat);
dbtotalcarbs = Math.round(dbtotalcarbs);
dbtotalproteins = Math.round(dbtotalproteins);
System.out.println("on prev fat"+dbtotalfat);
System.out.println("on prev carbs"+dbtotalcarbs);
System.out.println("on prev Pro"+dbtotalproteins);
int[] VALUES = new int[] {dbtotalfat, dbtotalcarbs, dbtotalproteins };
currentDate.setText(formattedDate);
drawGraph(VALUES);
System.out.println("From outside Block");
System.out.println("This is formated date"+formattedDate);
}
});
//Next Button For Date
nextMonth.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v){
c.add(Calendar.DATE, 1);
formattedDate = df.format(c.getTime());
currentDate.setText(formattedDate);
final Calendar d = Calendar.getInstance();
checkingdate = df.format(d.getTime());
if(formattedDate.equals(checkingdate))
{
nextMonth.setVisibility(View.GONE);
}
else
{
nextMonth.setVisibility(View.VISIBLE);
}
selectnextdata();
dbtotalfat = Math.round(dbtotalfat);
dbtotalcarbs = Math.round(dbtotalcarbs);
dbtotalproteins = Math.round(dbtotalproteins);
int[] VALUES = new int[] {dbtotalfat, dbtotalcarbs, dbtotalproteins };
currentDate.setText(formattedDate);
drawGraph(VALUES);
}
});
return rootView;
}
private void selectdata() {
DatabaseHandler helper = new DatabaseHandler(getActivity());
SQLiteDatabase db = helper.getReadableDatabase();
String calorieConsumedQuery = "SELECT SUM(calorie) AS dbcalorie,SUM(fat) AS dbtotalfat,SUM(carbohydrate) AS dbtotalcarbs,SUM(protein)AS Totalprotein FROM Meal WHERE createddate = ('"+formattedDate+"')";
String caloriBurnedQuery = "SELECT SUM(calorieburned) AS dbcalorieburned FROM ExerciseData WHERE createddate = ('"+formattedDate+"')";
String calorieDetailsQuery = "SELECT caloriegoal, calorieconsumed,calorieburned, fatgoal, proteingoal,carbohydrategoal FROM dailyDetails WHERE createddate = (SELECT MAX(createddate) FROM dailyDetails WHERE createddate <= ('"+formattedDate+"'))";
Cursor calorieConsumedQueryCursor = db.rawQuery(calorieConsumedQuery,null);
Cursor calorieBurnedQueryCursor = db.rawQuery(caloriBurnedQuery,null);
Cursor calorieDetailsQueryCursor = db.rawQuery(calorieDetailsQuery,null);
if (!calorieConsumedQueryCursor.isAfterLast()) {
calorieConsumedQueryCursor.moveToFirst();
while (!calorieConsumedQueryCursor.isAfterLast()) {
dbcalorie= (int) Math.round(calorieConsumedQueryCursor.getDouble(0));
dbtotalfat = (int) Math.round(calorieConsumedQueryCursor.getDouble(1));
dbtotalcarbs = (int) Math.round(calorieConsumedQueryCursor.getDouble(2));
dbtotalproteins = (int) Math.round(calorieConsumedQueryCursor.getDouble(3));
calorieConsumedQueryCursor.moveToNext();
}
}
if (!calorieBurnedQueryCursor.isAfterLast()) {
calorieBurnedQueryCursor.moveToFirst();
while (!calorieBurnedQueryCursor.isAfterLast()) {
dbcalorieburned = (int) Math.round(calorieBurnedQueryCursor.getDouble(0));
Log.e("calorie info"," dbcalorieburned: " + dbcalorieburned);
calorieBurnedQueryCursor.moveToNext();
}
}
if (!calorieDetailsQueryCursor.isAfterLast()) {
calorieDetailsQueryCursor.moveToFirst();
while (!calorieDetailsQueryCursor.isAfterLast()) {
calorie = (int) Math.round(calorieDetailsQueryCursor.getDouble(0));
ddcalorieconsumed = (int) Math.round(calorieDetailsQueryCursor.getDouble(1));
ddcalorieburned = (int) Math.round(calorieDetailsQueryCursor.getDouble(2));
dFat = (int) Math.round(calorieDetailsQueryCursor.getDouble(3));
dProteins = (int) Math.round(calorieDetailsQueryCursor.getDouble(4));
dCarbs = (int) Math.round(calorieDetailsQueryCursor.getDouble(5));
Log.e("Daily info"," ddcalorie: " + calorie);
Log.e("Daily info"," ddcalorieconsumed: " + ddcalorieconsumed);
Log.e("Daily info"," ddcalorieburned: " + ddcalorieburned);
Log.e("Daily info"," ddfatgoal: " + dFat);
Log.e("Daily info"," ddproteingoal: " + dProteins);
Log.e("Daily info"," ddcarbohydrategoal: " + dCarbs);
calorieDetailsQueryCursor.moveToNext();
}
}
calorieConsumedQueryCursor.close();
calorieBurnedQueryCursor.close();
calorieDetailsQueryCursor.close();
db.close();
}
private void selectprevdata() {
DatabaseHandler helper = new DatabaseHandler(getActivity());
SQLiteDatabase db = helper.getReadableDatabase();
String calorieConsumedQuery = "SELECT SUM(calorie) AS dbcalorie,SUM(fat) AS dbtotalfat,SUM(carbohydrate) AS dbtotalcarbs,SUM(protein)AS Totalprotein FROM Meal WHERE createddate = ('"+formattedDate+"')";
String caloriBurnedQuery = "SELECT SUM(calorieburned) AS dbcalorieburned FROM ExerciseData WHERE createddate = ('"+formattedDate+"')";
String calorieDetailsQuery = "SELECT caloriegoal, calorieconsumed,calorieburned, fatgoal, proteingoal,carbohydrategoal FROM dailyDetails WHERE createddate = (SELECT MAX(createddate) FROM dailyDetails WHERE createddate <= ('"+formattedDate+"'))";
Cursor calorieConsumedQueryCursor = db.rawQuery(calorieConsumedQuery,null);
Cursor calorieBurnedQueryCursor = db.rawQuery(caloriBurnedQuery,null);
Cursor calorieDetailsQueryCursor = db.rawQuery(calorieDetailsQuery,null);
if (!calorieConsumedQueryCursor.isAfterLast()) {
calorieConsumedQueryCursor.moveToFirst();
while (!calorieConsumedQueryCursor.isAfterLast()) {
dbcalorie= (int) Math.round(calorieConsumedQueryCursor.getDouble(0));
dbtotalfat = (int) Math.round(calorieConsumedQueryCursor.getDouble(1));
dbtotalcarbs = (int) Math.round(calorieConsumedQueryCursor.getDouble(2));
dbtotalproteins = (int) Math.round(calorieConsumedQueryCursor.getDouble(3));
calorieConsumedQueryCursor.moveToNext();
}
}
if (!calorieBurnedQueryCursor.isAfterLast()) {
calorieBurnedQueryCursor.moveToFirst();
while (!calorieBurnedQueryCursor.isAfterLast()) {
dbcalorieburned = (int) Math.round(calorieBurnedQueryCursor.getDouble(0));
Log.e("calorie info"," dbcalorieburned: " + dbcalorieburned);
calorieBurnedQueryCursor.moveToNext();
}
}
if (!calorieDetailsQueryCursor.isAfterLast()) {
calorieDetailsQueryCursor.moveToFirst();
while (!calorieDetailsQueryCursor.isAfterLast()) {
calorie = (int) Math.round(calorieDetailsQueryCursor.getDouble(0));
ddcalorieconsumed = (int) Math.round(calorieDetailsQueryCursor.getDouble(1));
ddcalorieburned = (int) Math.round(calorieDetailsQueryCursor.getDouble(2));
dFat = (int) Math.round(calorieDetailsQueryCursor.getDouble(3));
dProteins = (int) Math.round(calorieDetailsQueryCursor.getDouble(4));
dCarbs = (int) Math.round(calorieDetailsQueryCursor.getDouble(5));
Log.e("Daily info"," ddcalorie: " + calorie);
Log.e("Daily info"," ddcalorieconsumed: " + ddcalorieconsumed);
Log.e("Daily info"," ddcalorieburned: " + ddcalorieburned);
Log.e("Daily info"," ddfatgoal: " + dFat);
Log.e("Daily info"," ddproteingoal: " + dProteins);
Log.e("Daily info"," ddcarbohydrategoal: " + dCarbs);
calorieDetailsQueryCursor.moveToNext();
}
}
calorieConsumedQueryCursor.close();
calorieBurnedQueryCursor.close();
calorieDetailsQueryCursor.close();
db.close();
}
private void selectnextdata() {
DatabaseHandler helper = new DatabaseHandler(getActivity());
SQLiteDatabase db = helper.getReadableDatabase();
String calorieConsumedQuery = "SELECT SUM(calorie) AS dbcalorie,SUM(fat) AS dbtotalfat,SUM(carbohydrate) AS dbtotalcarbs,SUM(protein)AS Totalprotein FROM Meal WHERE createddate = ('"+formattedDate+"')";
String caloriBurnedQuery = "SELECT SUM(calorieburned) AS dbcalorieburned FROM ExerciseData WHERE createddate = ('"+formattedDate+"')";
String calorieDetailsQuery = "SELECT caloriegoal, calorieconsumed,calorieburned, fatgoal, proteingoal,carbohydrategoal FROM dailyDetails WHERE createddate = (SELECT MAX(createddate) FROM dailyDetails WHERE createddate <= ('"+formattedDate+"'))";
Cursor calorieConsumedQueryCursor = db.rawQuery(calorieConsumedQuery,null);
Cursor calorieBurnedQueryCursor = db.rawQuery(caloriBurnedQuery,null);
Cursor calorieDetailsQueryCursor = db.rawQuery(calorieDetailsQuery,null);
if (!calorieConsumedQueryCursor.isAfterLast()) {
calorieConsumedQueryCursor.moveToFirst();
while (!calorieConsumedQueryCursor.isAfterLast()) {
dbcalorie= (int) Math.round(calorieConsumedQueryCursor.getDouble(0));
dbtotalfat = (int) Math.round(calorieConsumedQueryCursor.getDouble(1));
dbtotalcarbs = (int) Math.round(calorieConsumedQueryCursor.getDouble(2));
dbtotalproteins = (int) Math.round(calorieConsumedQueryCursor.getDouble(3));
calorieConsumedQueryCursor.moveToNext();
}
}
if (!calorieBurnedQueryCursor.isAfterLast()) {
calorieBurnedQueryCursor.moveToFirst();
while (!calorieBurnedQueryCursor.isAfterLast()) {
dbcalorieburned = (int) Math.round(calorieBurnedQueryCursor.getDouble(0));
Log.e("calorie info"," dbcalorieburned: " + dbcalorieburned);
calorieBurnedQueryCursor.moveToNext();
}
}
if (!calorieDetailsQueryCursor.isAfterLast()) {
calorieDetailsQueryCursor.moveToFirst();
while (!calorieDetailsQueryCursor.isAfterLast()) {
calorie = (int) Math.round(calorieDetailsQueryCursor.getDouble(0));
ddcalorieconsumed = (int) Math.round(calorieDetailsQueryCursor.getDouble(1));
ddcalorieburned = (int) Math.round(calorieDetailsQueryCursor.getDouble(2));
dFat = (int) Math.round(calorieDetailsQueryCursor.getDouble(3));
dProteins = (int) Math.round(calorieDetailsQueryCursor.getDouble(4));
dCarbs = (int) Math.round(calorieDetailsQueryCursor.getDouble(5));
Log.e("Daily info"," ddcalorie: " + calorie);
Log.e("Daily info"," ddcalorieconsumed: " + ddcalorieconsumed);
Log.e("Daily info"," ddcalorieburned: " + ddcalorieburned);
Log.e("Daily info"," ddfatgoal: " + dFat);
Log.e("Daily info"," ddproteingoal: " + dProteins);
Log.e("Daily info"," ddcarbohydrategoal: " + dCarbs);
calorieDetailsQueryCursor.moveToNext();
}
}
calorieConsumedQueryCursor.close();
calorieBurnedQueryCursor.close();
calorieDetailsQueryCursor.close();
db.close();
}
void drawGraph(int VALUES[]){
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.WHITE);
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(20);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setStartAngle(90);
mRenderer.setPanEnabled(false);
mRenderer.setLabelsColor(Color.BLACK);
mRenderer.setLabelsTextSize(26);
for (int i = 0; i < VALUES.length; i++) {
mSeries.add(NAME_LIST[i] + " " + VALUES[i], VALUES[i]);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
if (mChartView != null) {
mChartView.repaint();
}
else if (mChartView == null) {
LinearLayout layout = (LinearLayout) rootView.findViewById(R.id.chart);
layout.setBackgroundColor(Color.WHITE);
mChartView = ChartFactory.getPieChartView(getActivity(), mSeries, mRenderer);
mChartView.setBackgroundColor(Color.DKGRAY);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);
mChartView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(getActivity(),"YOu have Clicked",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(),"Chart element data point index "+ (seriesSelection.getPointIndex()+1) + " was clicked" + " point value="+ seriesSelection.getValue(), Toast.LENGTH_SHORT).show();
}
}
});
mChartView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(getActivity(),"No chart element was long pressed", Toast.LENGTH_SHORT).show();;
return false;
} else {
Toast.makeText(getActivity(),"Chart element data point index "+ seriesSelection.getPointIndex()+ " was long pressed",Toast.LENGTH_SHORT).show();
return true;
}
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
else {
mChartView.repaint();
}
}
}
Add these lines inside drawGraph api
DefaultRenderer mRenderer = new DefaultRenderer(); //move the line
mSeries.clear()

Categories

Resources