Getting ArrayIndexOutofBoundsException in android listview - android

I am using listview to load data from sqlite when i open the app i could see the following error can anyone tell me what i am doing wrong in the adapter.Even when the app gets started it shows the following error
Database:
public ArrayList<Daybook> getAlldaybookentriesdatewise(int s) {
ArrayList<Daybook> daybookDetails = new ArrayList<Daybook>();
String selectquery = "SELECT date,IFNULL(SUM(amountin),0) as amountin,IFNULL(SUM(amountout),0) as amountout,daybookusertype FROM daybookdetails GROUP BY strftime('%Y-%m-%d',date) ORDER BY strftime('%Y-%m-%d',date) DESC LIMIT " + s + "";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectquery, null);
if (cursor.moveToFirst()) {
do {
Daybook daybookentries = new Daybook();
daybookentries.setDate(cursor.getString(0));
daybookentries.setCashin(cursor.getString(1));
daybookentries.setCashout(cursor.getString(2));
daybookDetails.add(daybookentries);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return daybookDetails;
}
Activity:
public class NewDaybook_Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ListView listview;
FloatingActionButton fabaddnew;
LinearLayout emptyy;
DatabaseHandler databasehandler;
ArrayList<Daybook> daybookcashentries;
Daybook_adapter dadapter;
LoginSession loginSession;
boolean loadingMore = false;
String totaldaybookcount;
int olimit = 2;
int totalcount;
String s;
private Locale mLocale;
private final String[] language = {"en", "ta"};
LinearLayout li_farmer, li_worker, li_vehicle, li_otherexpense, li_buyer, li_general;
RadioGroup rg_filtering;
RadioButton rbtn_farmertrade, rbtn_farmeradvance, rbtn_work, rbtn_workadvance, rbtn_groupwork, rbtn_groupadvance, rbtn_vehicle, rbtn_otherexpense;
AlertDialog alert;
ImageView img_farm, img_buy, img_work, img_veh, img_expense;
TextView tv_farm, tv_buy, tv_work, tv_veh, tv_expense;
public static final int progress_bar_type = 0;
private ProgressDialog pDialog;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_daybooks);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.daybook);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
TextView tv_balanceamt = (TextView) header.findViewById(R.id.nav_name);
TextView tv_timedate = (TextView) header.findViewById(R.id.tv_dateandtime);
tv_balanceamt.setTextSize(22);
long date = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy ");
String dateString = sdf.format(date);
tv_timedate.setText(dateString);
databasehandler = new DatabaseHandler(getApplicationContext());
String balanceamount = String.valueOf(databasehandler.getdaybookbalanceamt());
Log.e("daybookbalanceamt", String.valueOf(balanceamount));
balanceamount = balanceamount.replaceAll("[\\[\\](){}]", "");
tv_balanceamt.setText("\u20B9" + balanceamount);
initalize();
}
private void initalize() {
loginSession = new LoginSession(getApplicationContext());
loginSession.checkLogin();
databasehandler = new DatabaseHandler(getApplicationContext());
listview = (ListView) findViewById(R.id.list_daybook);
li_general = (LinearLayout) findViewById(R.id.linearLayout2);
li_farmer = (LinearLayout) findViewById(R.id.linear_farmer);
li_worker = (LinearLayout) findViewById(R.id.linear_worker);
li_vehicle = (LinearLayout) findViewById(R.id.linear_vehicle);
li_otherexpense = (LinearLayout) findViewById(R.id.linear_otherexpense);
li_buyer = (LinearLayout) findViewById(R.id.linear_buyers);
fabaddnew = (FloatingActionButton) findViewById(R.id.addnewtransaction);
emptyy = (LinearLayout) findViewById(R.id.empty);
rg_filtering = (RadioGroup) findViewById(R.id.rg_sortdata);
rbtn_farmertrade = (RadioButton) findViewById(R.id.rbtn_farmers);
rbtn_farmeradvance = (RadioButton) findViewById(R.id.rbtn_fadvance);
rbtn_work = (RadioButton) findViewById(R.id.rbtn_work);
rbtn_workadvance = (RadioButton) findViewById(R.id.rbtn_workadvance);
rbtn_groupwork = (RadioButton) findViewById(R.id.rbtn_groupwork);
rbtn_groupadvance = (RadioButton) findViewById(R.id.rbtn_groupadvance);
rbtn_vehicle = (RadioButton) findViewById(R.id.rbtn_vehicle);
rbtn_otherexpense = (RadioButton) findViewById(R.id.rbtn_otherexpense);
img_farm = (ImageView) findViewById(R.id.img_farmer);
img_buy = (ImageView) findViewById(R.id.img_buyer);
img_work = (ImageView) findViewById(R.id.img_worker);
img_veh = (ImageView) findViewById(R.id.img_vehicle);
img_expense = (ImageView) findViewById(R.id.img_otherexpense);
tv_farm = (TextView) findViewById(R.id.tv_farmer);
tv_buy = (TextView) findViewById(R.id.tv_buyer);
tv_work = (TextView) findViewById(R.id.tv_worker);
tv_veh = (TextView) findViewById(R.id.tv_vehicle);
tv_expense = (TextView) findViewById(R.id.tv_otherexpense);
listview.setFastScrollEnabled(true);
new Daybooklistloader().execute();
li_buyer.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
// When you Touch Down
// U can change Text and Image As per your Functionality
li_buyer.setBackgroundColor(Color.parseColor("#FF4081"));
tv_buy.setTextColor(Color.parseColor("#FFFFFF"));
img_buy.setColorFilter(ContextCompat.getColor(NewDaybook_Activity.this, R.color.white));
break;
case MotionEvent.ACTION_UP:
//When you Release the touch
// U can change Text and Image As per your Functionality
startActivity(new Intent(NewDaybook_Activity.this, Activity_BuyerTransaction.class));
NewDaybook_Activity.this.finish();
break;
}
return true;
}
});
li_farmer.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
// When you Touch Down
// U can change Text and Image As per your Functionality
li_farmer.setBackgroundColor(Color.parseColor("#FF4081"));
tv_farm.setTextColor(Color.parseColor("#FFFFFF"));
img_farm.setColorFilter(ContextCompat.getColor(NewDaybook_Activity.this, R.color.white));
startActivity(new Intent(NewDaybook_Activity.this, Farmertrade_Activity.class));
NewDaybook_Activity.this.finish();
break;
case MotionEvent.ACTION_UP:
//When you Release the touch
// U can change Text and Image As per your Functionality
startActivity(new Intent(NewDaybook_Activity.this, Farmertrade_Activity.class));
NewDaybook_Activity.this.finish();
break;
}
return true;
}
});
fabaddnew.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
fabaddnew.setRippleColor(R.drawable.ripple_effect);
startActivity(new Intent(NewDaybook_Activity.this, Activity_AddFastEntryDaybook.class));
NewDaybook_Activity.this.finish();
return true;
}
});
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
startActivity(new Intent(NewDaybook_Activity.this, NewDaybook_Activity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_dashboard) {
startActivity(new Intent(NewDaybook_Activity.this, DashboardActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_buyer) {
startActivity(new Intent(NewDaybook_Activity.this, BuyerListActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_farmer) {
startActivity(new Intent(NewDaybook_Activity.this, FarmerlistActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_workers) {
startActivity(new Intent(NewDaybook_Activity.this, WorkerListActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_vehicles) {
startActivity(new Intent(NewDaybook_Activity.this, VehicleList_activity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_otherexpense) {
startActivity(new Intent(NewDaybook_Activity.this, OtherExpenseList.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_report) {
startActivity(new Intent(NewDaybook_Activity.this, BillBookActivity.class));
NewDaybook_Activity.this.finish();
} else if (id == R.id.nav_settings) {
// startActivity(new Intent(NewDaybook_Activity.this, SettingsActivity.class));
// NewDaybook_Activity.this.finish();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.language)
.setItems(R.array.language, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
setLocale(language[i]);
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else if (id == R.id.nav_logout) {
loginSession.logoutUser();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setLocale(String lang) {
Log.d("Selected Language is ", lang);
SharedPreferences preferences = getSharedPreferences(MyApplication.PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(MyApplication.PREF_USER_LANGUAGE_KEY, lang).apply();
mLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLocale(mLocale);
}
res.updateConfiguration(conf, dm);
recreate();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Processing...");
pDialog.setIndeterminate(true);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setProgressNumberFormat(null);
pDialog.setProgressPercentFormat(null);
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
private class Daybooklistloader extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... strings) {
daybookcashentries = new ArrayList<Daybook>();
daybookcashentries = databasehandler.getAlldaybookentriesdatewise(olimit);
return null;
}
#Override
protected void onPostExecute(String j) {
dismissDialog(progress_bar_type);
View footerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.activity_footer, null, false);
listview.addFooterView(footerView);
dadapter = new Daybook_adapter(NewDaybook_Activity.this, daybookcashentries);
if (dadapter != null) {
if (dadapter.getCount() > 0) {
emptyy.setVisibility(View.INVISIBLE);
listview.setAdapter(dadapter);
}
} else {
emptyy.setVisibility(View.VISIBLE);
}
final List<String> labels = databasehandler.getTotaldaybookrecord();
for (String s : labels) {
totaldaybookcount = s;
}
totalcount = Integer.parseInt(totaldaybookcount);
listview.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int btn_initPosY = fabaddnew.getScrollY();
int li_initPosY = li_general.getScrollY();
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
dadapter.isScrolling(true);
fabaddnew.animate().cancel();
li_general.animate().cancel();
fabaddnew.animate().translationYBy(150);
li_general.animate().translationYBy(150);
} else {
dadapter.isScrolling(false);
fabaddnew.animate().cancel();
li_general.animate().cancel();
fabaddnew.animate().translationY(btn_initPosY);
li_general.animate().translationY(li_initPosY);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
dadapter.isScrolling(true);
//what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already? Load more!
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
new LoadDataTask().execute();
}
}
});
}
}
private class LoadDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingMore = true;
// showDialog(progress_bar_type);
}
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
Log.e("test2", "reached");
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
Log.e("test3", "starting");
databasehandler = new DatabaseHandler(getApplicationContext());
if (olimit > totalcount) {
// olimit = 1;
// olimit = 2;
} else {
olimit = olimit + 1;
}
daybookcashentries = new ArrayList<Daybook>();
databasehandler = new DatabaseHandler(getApplicationContext());
daybookcashentries = new ArrayList<Daybook>();
String selectquery = "SELECT date,IFNULL(SUM(amountin),0) as amountin,IFNULL(SUM(amountout),0),daybookusertype as amountout FROM daybookdetails GROUP BY strftime('%Y-%m-%d',date) ORDER BY strftime('%Y-%m-%d',date) DESC LIMIT '" + olimit + "'";
SQLiteDatabase db = databasehandler.getReadableDatabase();
Cursor cursor = db.rawQuery(selectquery, null);
if (cursor.moveToFirst()) {
do {
Daybook daybookentries = new Daybook();
daybookentries.setDate(cursor.getString(0));
daybookentries.setCashin(cursor.getString(1));
daybookentries.setCashout(cursor.getString(2));
daybookcashentries.add(daybookentries);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return null;
}
#Override
protected void onPostExecute(Void result) {
dadapter.setTransactionList(daybookcashentries);
loadingMore = false;
// dismissDialog(progress_bar_type);
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
loadingMore = false;
}
}
}
Adapter:
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));
}
Error:
*** 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)

The crash logs doesn't seems to be the reason for the crash.
Try cleaning the project and run.
If the issue still exists do disable instant run from the settings and run.
Hope this should get fixes and start running.

Related

How to update the Expandable listview when new item is added to it

I have created an expandable listview which loads data from sqlite when the listview reaches bottom.It again loads another set of data from sqlite using async task.In this the header gets updated with the new datas but the child view for the latest data is empty can anyone tell me how to update/refresh the expandable list adapter when new data's get loaded.
Adapter:
public class DaybookExpandableAdapter extends BaseExpandableListAdapter {
String updatedate = "";
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<Daybooklist>> _listDataChild;
private DatabaseHandler databaseHandler;
boolean isListScrolling;
public DaybookExpandableAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<Daybooklist>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
/*final String childText = (String) getChild(groupPosition, childPosition);
final String childtime = (String) getChild(groupPosition,childPosition);*/
Daybooklist daybooklist = (Daybooklist) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.model_daybook_listitem, null);
}
TextView txtname = (TextView) convertView.findViewById(R.id.tv_daybook_name);
TextView txttime = (TextView) convertView.findViewById(R.id.tv_daybook_time);
TextView day_name = (TextView) convertView.findViewById(R.id.tv_daybook_name);
TextView day_description = (TextView) convertView.findViewById(R.id.tv_daybook_description);
TextView day_type = (TextView) convertView.findViewById(R.id.tv_daybook_type);
TextView day_amount = (TextView) convertView.findViewById(R.id.tv_daybook_amount);
TextView day_usertype = (TextView) convertView.findViewById(R.id.tv_usertype);
TextView day_time = (TextView) convertView.findViewById(R.id.tv_daybook_time);
ImageView day_check = (ImageView) convertView.findViewById(R.id.img_doneall);
TextView daybook_location = (TextView) convertView.findViewById(R.id.tv_daybook_location);
txtname.setText(daybooklist.getName());
txttime.setText(daybooklist.getCtime());
databaseHandler = new DatabaseHandler(_context);
if (daybooklist.getUsertype() != null && !daybooklist.getUsertype().isEmpty()) {
if (daybooklist.getUsertype().startsWith("farmer") | daybooklist.getUsertype().startsWith("singleworker") | daybooklist.getUsertype().startsWith("groupworker") | daybooklist.getUsertype().startsWith("payvehicle")) {
if (daybooklist.getUsertype().startsWith("farmer")) {
day_name.setText(daybooklist.getName());
day_description.setText(daybooklist.getDescription());
String mobno = daybooklist.getMobileno();
Log.e("mobno", mobno);
String locat = String.valueOf(databaseHandler.getfarmerlocation(mobno));
locat = locat.replaceAll("\\[", "").replaceAll("\\]", "");
Log.e("farmerlocation", locat);
daybook_location.setText(locat);
day_type.setText(daybooklist.getType());
if (daybooklist.getName() != null && daybooklist.getName().startsWith("no")) {
day_name.setText(" ");
} else if (daybooklist.getDescription() != null && daybooklist.getDescription().startsWith("no")) {
day_description.setText(" ");
}
day_amount.setText("\u20B9" + daybooklist.getExtraamt());
if (daybooklist.getAmountout().startsWith("0.0") | daybooklist.getAmountout().startsWith("0")) {
// day_amount.setTextColor(activity.getResources().getColor(R.color.green));
Log.e("Amountout", daybooklist.getAmountout());
day_check.setVisibility(View.INVISIBLE);
} else {
// day_amount.setTextColor(activity.getResources().getColor(R.color.album_title));
Log.e("Amountout", daybooklist.getAmountout());
day_check.setVisibility(View.VISIBLE);
}
day_time.setText(daybooklist.getCtime());
} else {
day_name.setText(daybooklist.getName());
day_description.setText(daybooklist.getDescription());
daybook_location.setText(daybooklist.getType());
day_type.setText(daybooklist.getType());
if (daybooklist.getName() != null && daybooklist.getName().startsWith("no")) {
day_name.setText(" ");
} else if (daybooklist.getDescription() != null && daybooklist.getDescription().startsWith("no")) {
day_description.setText(" ");
}
day_amount.setText("\u20B9" + daybooklist.getExtraamt());
if (daybooklist.getAmountout().startsWith("0.0") | daybooklist.getAmountout().startsWith("0")) {
// day_amount.setTextColor(activity.getResources().getColor(R.color.green));
Log.e("Amountout", daybooklist.getAmountout());
day_check.setVisibility(View.INVISIBLE);
} else {
// day_amount.setTextColor(activity.getResources().getColor(R.color.album_title));
Log.e("Amountout", daybooklist.getAmountout());
day_check.setVisibility(View.VISIBLE);
}
day_time.setText(daybooklist.getCtime());
}
} else if (daybooklist.getUsertype().startsWith("advancefarmer") | daybooklist.getUsertype().startsWith("workeradvance") | daybooklist.getUsertype().startsWith("kgroupadvance") | daybooklist.getUsertype().startsWith("otherexpense") | daybooklist.getUsertype().startsWith("vehicle")) {
if (daybooklist.getUsertype().startsWith("advancefarmer")) {
day_name.setText(daybooklist.getName());
day_description.setText(daybooklist.getDescription());
day_type.setText(daybooklist.getType());
String mobno = daybooklist.getMobileno();
Log.e("mobno", mobno);
String locat = String.valueOf(databaseHandler.getfarmerlocation(mobno));
locat = locat.replaceAll("\\[", "").replaceAll("\\]", "");
Log.e("farmerlocation", locat);
daybook_location.setText(locat);
if (daybooklist.getName() != null && daybooklist.getName().startsWith("no")) {
day_name.setText(" ");
} else if (daybooklist.getDescription() != null && daybooklist.getDescription().startsWith("no")) {
day_description.setText(" ");
}
Log.e("amountout", daybooklist.getAmountout());
day_amount.setText("\u20B9" + daybooklist.getAmountout());
day_time.setText(daybooklist.getCtime());
} else {
day_name.setText(daybooklist.getName());
day_description.setText(daybooklist.getType());
day_type.setText(daybooklist.getType());
daybook_location.setText(daybooklist.getDescription());
if (daybooklist.getName() != null && daybooklist.getName().startsWith("no")) {
day_name.setText(" ");
} else if (daybooklist.getDescription() != null && daybooklist.getDescription().startsWith("no")) {
day_description.setText(" ");
}
Log.e("amountout", daybooklist.getAmountout());
day_amount.setText("\u20B9" + daybooklist.getAmountout());
day_time.setText(daybooklist.getCtime());
}
} else if (daybooklist.getUsertype().startsWith("buyer")) {
day_name.setText(daybooklist.getName());
day_description.setText(daybooklist.getDescription());
day_amount.setText("\u20B9" + daybooklist.getAmountin());
day_type.setText(" ");
day_time.setText(daybooklist.getCtime());
daybook_location.setText(daybooklist.getType());
}
if (daybooklist.getUsertype().startsWith("farmer")) {
day_usertype.setText("F");
day_usertype.setBackgroundResource(R.drawable.textview_farmer);
} else if (daybooklist.getUsertype().startsWith("advancefarmer")) {
day_usertype.setText("FA");
day_usertype.setBackgroundResource(R.drawable.textview_farmer);
} else if (daybooklist.getUsertype().startsWith("singleworker")) {
day_usertype.setText("W");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (daybooklist.getUsertype().startsWith("workeradvance")) {
day_usertype.setText("WA");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (daybooklist.getUsertype().startsWith("groupworker")) {
day_usertype.setText("G");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (daybooklist.getUsertype().startsWith("kgroupadvance")) {
day_usertype.setText("GA");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (daybooklist.getUsertype().startsWith("otherexpense")) {
day_usertype.setText("E");
day_usertype.setBackgroundResource(R.drawable.textview_otherexpense);
} else if (daybooklist.getUsertype().startsWith("vehicle")) {
day_usertype.setText("V");
day_usertype.setBackgroundResource(R.drawable.textview_vehicle);
} else if (daybooklist.getUsertype().startsWith("gsalary")) {
day_usertype.setText("GS");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (daybooklist.getUsertype().startsWith("isalary")) {
day_usertype.setText("WS");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (daybooklist.getUsertype().startsWith("payvehicle")) {
day_usertype.setText("VP");
day_usertype.setBackgroundResource(R.drawable.textview_vehicle);
} else if (daybooklist.getUsertype().startsWith("buyer")) {
day_usertype.setText("B");
day_usertype.setBackgroundResource(R.drawable.textview_buyer);
}
}
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
final String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.model_daybook_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.tv_daybook_date);
final ImageView img_pdg = (ImageView) convertView.findViewById(R.id.img_printpdf);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
String strDate = headerTitle;
SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMMyyyy");
try {
Date varDate = dateFormat.parse(strDate);
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
updatedate = dateFormat.format(varDate);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
img_pdg.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
img_pdg.setColorFilter(ContextCompat.getColor(_context, R.color.colorAccent));
break;
case MotionEvent.ACTION_UP:
img_pdg.clearColorFilter();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
_context);
// set title
alertDialogBuilder.setTitle(R.string.app_name);
// set dialog message
alertDialogBuilder
.setMessage(_context.getResources().getString(R.string.daybookreport) + headerTitle)
.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", updatedate);
_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
img_pdg.clearColorFilter();
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);
break;
}
return true;
}
});
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
img_pdg.setColorFilter(ContextCompat.getColor(_context, R.color.colorAccent));
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
_context);
// set title
alertDialogBuilder.setTitle(R.string.app_name);
// set dialog message
alertDialogBuilder
.setMessage(_context.getResources().getString(R.string.daybookreport) + headerTitle)
.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", updatedate);
_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
img_pdg.clearColorFilter();
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 convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void setTransactionList(List<String> newList, HashMap<String, List<Daybooklist>> childlist) {
_listDataHeader.clear();
_listDataChild.clear();
_listDataHeader = newList;
_listDataChild = childlist;
notifyDataSetChanged();
}
public void setVTransactionList(List<String> newList) {
_listDataHeader = newList;
notifyDataSetChanged();
}
public void isScrolling(boolean isScroll) {
isListScrolling = isScroll;
Log.e("scrollcheck", String.valueOf(isListScrolling));
}
}
Async task:
class LoadDataTask extends AsyncTask<String, Void, String> {
Daybooklist daybooklist = new Daybooklist();
#Override
protected String doInBackground(String... olimits) {
String limits = null;
kickstart = 2;
olimit=20;
Log.e("kickcheck", String.valueOf(kickstart));
loadingMore = true;
try {
limits = olimits[0];
Log.e("limitscheck",limits);
daybooks = new ArrayList<Daybook>();
daybooks = databaseHandler.getAlldaybookentriesdatewise(olimit);
daybooklists = new ArrayList<Daybooklist>();
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<Daybooklist>>();
for (int i = 0; i < daybooks.size(); i++) {
String date = daybooks.get(i).getDate();
if (date != null) {
String s = date;
String[] spiliter = s.split("-");
String year = spiliter[0];
String month = spiliter[1];
String dates = spiliter[2];
if (month.startsWith("01")) {
disorderedlist = dates + "Jan" + year;
disorderedlist = disorderedlist.replaceAll("\\s+", "");
} else if (month.startsWith("02")) {
disorderedlist = dates + "Feb" + year;
disorderedlist = disorderedlist.replaceAll("\\s+", "");
} else if (month.startsWith("03")) {
disorderedlist = dates + "Mar" + year;
disorderedlist = disorderedlist.replaceAll("\\s+", "");
} else if (month.startsWith("04")) {
disorderedlist = dates + "Apr" + year;
disorderedlist = disorderedlist.replaceAll("\\s+", "");
} else if (month.startsWith("05")) {
disorderedlist = dates + "May" + year;
disorderedlist = disorderedlist.replaceAll("\\s+", "");
} else if (month.startsWith("06")) {
disorderedlist = dates + "Jun" + year;
disorderedlist = disorderedlist.replaceAll("\\s+", "");
} else if (month.startsWith("07")) {
disorderedlist = dates + "Jul" + year;
disorderedlist = disorderedlist.replaceAll("\\s+", "");
} else if (month.startsWith("08")) {
disorderedlist = dates + "Aug" + year;
disorderedlist = disorderedlist.replaceAll("\\s+", "");
} else if (month.startsWith("09")) {
disorderedlist = dates + "Sep" + year;
disorderedlist = disorderedlist.replaceAll("\\s+", "");
} else if (month.startsWith("10")) {
disorderedlist = dates + "Oct" + year;
disorderedlist = disorderedlist.replaceAll("\\s+", "");
} else if (month.startsWith("11")) {
disorderedlist = dates + "Nov" + year;
disorderedlist = disorderedlist.replaceAll("\\s+", "");
} else if (month.startsWith("12")) {
disorderedlist = dates + "Dec" + year;
disorderedlist = disorderedlist.replaceAll("\\s+", "");
}
listDataHeader.add(disorderedlist);
}
chid = new ArrayList<Daybooklist>();
daybooklists = databaseHandler.getAllDaywisedaybookdetails(date);
for (int j = 0; j < daybooklists.size(); j++) {
String name = daybooklists.get(j).getName();
String desc = daybooklists.get(j).getDescription();
String type = daybooklists.get(j).getType();
String usertype = daybooklists.get(j).getUsertype();
String amtin = daybooklists.get(j).getAmountin();
String amtout = daybooklists.get(j).getAmountout();
String extamt = daybooklists.get(j).getExtraamt();
String mobno = daybooklists.get(j).getMobileno();
String dates = daybooklists.get(j).getSdate();
String time = daybooklists.get(j).getCtime();
if (name != null) {
chid.add(new Daybooklist(name, desc, type, usertype, amtin, amtout, extamt, mobno, dates, time));
}
}
listDataChild.put(listDataHeader.get(i), chid);
}
} catch (Exception e) {
e.printStackTrace();
}
return disorderedlist;
}
#Override
protected void onPostExecute(String disorderedlist) {
// listAdapter = new DaybookExpandableAdapter(getApplicationContext(), listDataHeader, listDataChild);
listAdapter.setTransactionList(listDataHeader,listDataChild);
loadingMore = false;
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
loadingMore = false;
}
}
Adapter notify:
public void setTransactionList(List<String> newList, HashMap<String, List<Daybooklist>> childlist) {
_listDataHeader.clear();
_listDataChild.clear();
_listDataHeader = newList;
_listDataChild = childlist;
notifyDataSetChanged();
}
Database:
public ArrayList<Daybook> getAlldaybookentriesdatewise(int s) {
ArrayList<Daybook> daybookDetails = new ArrayList<Daybook>();
String selectquery = "SELECT date,IFNULL(SUM(amountin),0) as amountin,IFNULL(SUM(amountout),0) as amountout,daybookusertype FROM daybookdetails GROUP BY strftime('%Y-%m-%d',date) ORDER BY strftime('%Y-%m-%d',date) DESC LIMIT " + s + "";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectquery, null);
if (cursor.moveToFirst()) {
do {
Daybook daybookentries = new Daybook();
daybookentries.setDate(cursor.getString(0));
daybookentries.setCashin(cursor.getString(1));
daybookentries.setCashout(cursor.getString(2));
daybookDetails.add(daybookentries);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return daybookDetails;
}
I have already tried using notifydatasetchanged but it didn't works.
You need to set the adapter in the View, inside the onPostExecute() method:
protected void onPostExecute(String disorderedlist) {
listAdapter = new DaybookExpandableAdapter(getApplicationContext(), listDataHeader, listDataChild);
listView.setAdapter(listAdapter);
listAdapter.setTransactionList(listDataHeader,listDataChild);
loadingMore = false;
}

Using AlertDialog.Builder to build custom AlertDialog class

I have a Class FoodDialog that extends AlertDialog that I have customized to how I would like it to look.
I am now wanting to edit the positive/negative buttons using an AlertDialog.Builder, however, when I attempt to build an instance of FoodDialog using a builder, I am facing an 'Incompatible types' error where the builder is asking for AlertDialog instead I am providing it with an extension of AlertDialog - is there a way around this?
If not, is there a way I can edit the positive/negative buttons of my custom AlertDialog class FoodDialog?
Below is my FoodDialog class. The yes/no buttons I have there are ones I have created myself, but I would like the ones that are part of the AlertDialog.Builder to appear instead as these buttons get pushed out of sight when the soft keyboard appears:
public class FoodDialog extends AlertDialog implements OnClickListener {
private TextView foodNameTextView, foodDescTextView, foodPortionTextView, catTextView, qtyText, cal, fat, sFat, carb, sug, prot, salt, imageTxt,
measureText;
private EditText foodQty;
private ImageView foodImage;
private ImageButton yesBtn, noBtn;
private int foodID, totalCal;
private Bitmap image;
private String user, portionType, foodName, foodDesc, cat, totalCalString, totalFatString,
totalSFatString, totalCarbString, totalSugString, totalProtString, totalSaltString, portionBaseString;
private double totalFat, totalSFat, totalCarb, totalSug, totalProt, totalSalt, portionBase;
private Food food;
private Portion portion;
private Nutrients nutrients;
private PortionType pType;
private DBHandler db;
public FoodDialog(Context context){
super(context);
}
public FoodDialog(Context context, int foodID, String imgLocation, final String user) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
this.setTitle("Confirm?");
setContentView(R.layout.dialog_layout);
this.foodID = foodID;
this.user = user;
db = new DBHandler(context);
food = db.getFoodByID(foodID, user);
portion = db.getPortionByFoodID(foodID);
nutrients = db.getNutrientsByFoodIDAndPortionType(foodID, portion.getPortionType());
pType = db.getPortionTypeByName(portion.getPortionType());
//getting object attributes
portionType = portion.getPortionType();
portionBase = portion.getPortionBase();
//food
foodName = food.getName();
foodDesc = food.getDesc();
cat = food.getCat();
//nutrients
totalCal = nutrients.getCal();
totalFat = nutrients.getFat();
totalSFat = nutrients.getSFat();
totalCarb = nutrients.getCarb();
totalSug = nutrients.getSug();
totalProt = nutrients.getProt();
totalSalt = nutrients.getSalt();
//converting to string
totalCalString = String.valueOf(totalCal);
if (totalFat % 1 == 0) {
totalFatString = String.format("%.0f", totalFat);
} else {
totalFatString = String.valueOf(totalFat);
}
if (totalSFat % 1 == 0) {
totalSFatString = String.format("%.0f", totalSFat);
} else {
totalSFatString = String.valueOf(totalSFat);
}
if (totalCarb % 1 == 0) {
totalCarbString = String.format("%.0f", totalCarb);
} else {
totalCarbString = String.valueOf(totalCarb);
}
if (totalSug % 1 == 0) {
totalSugString = String.format("%.0f", totalSug);
} else {
totalSugString = String.valueOf(totalSug);
}
if (totalProt % 1 == 0) {
totalProtString = String.format("%.0f", totalProt);
} else {
totalProtString = String.valueOf(totalProt);
}
if (totalSalt % 1 == 0) {
totalSaltString = String.format("%.0f", totalSalt);
} else {
totalSaltString = String.valueOf(totalSalt);
}
if (portionBase % 1 == 0) {
portionBaseString = String.format("%.0f", portionBase);
} else {
portionBaseString = String.valueOf(portionBase);
}
//textviews
foodNameTextView = (TextView) findViewById(R.id.dialogName);
foodNameTextView.setText(foodName);
foodDescTextView = (TextView) findViewById(R.id.dialogDesc);
foodDescTextView.setText(foodDesc);
foodPortionTextView = (TextView) findViewById(R.id.dialogPortion);
foodPortionTextView.setText("Values based per " + portionBase + " " + portionType);
catTextView = (TextView) findViewById(R.id.dialogCat);
catTextView.setText(cat);
measureText = (TextView) findViewById(R.id.dialogMeasure);
measureText.setText(portionType);
qtyText = (TextView) findViewById(R.id.dialogQtyText);
imageTxt = (TextView) findViewById(R.id.dialogImageText);
cal = (TextView) findViewById(R.id.dialogCal);
cal.setText(totalCalString);
fat = (TextView) findViewById(R.id.dialogFat);
fat.setText(totalFatString + "g");
sFat = (TextView) findViewById(R.id.dialogSFat);
sFat.setText(totalSFatString + "g");
carb = (TextView) findViewById(R.id.dialogCarb);
carb.setText(totalCarbString + "g");
sug = (TextView) findViewById(R.id.dialogSug);
sug.setText(totalSugString + "g");
prot = (TextView) findViewById(R.id.dialogProt);
prot.setText(totalProtString + "g");
salt = (TextView) findViewById(R.id.dialogSalt);
salt.setText(totalSaltString + "g");
//img
foodImage = (ImageView) findViewById(R.id.dialogImage);
imgLocation = food.getImgURL();
image = BitmapFactory.decodeFile(imgLocation);
foodImage.setImageBitmap(image);
if (imgLocation.equals("nourl")) {
imageTxt.setText("No Image");
}
//edit tex
foodQty = (EditText) findViewById(R.id.dialogQty);
//adjusting edittext
foodQty.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
foodQty.setFilters(new InputFilter[]{
new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 4, afterDecimal = 3;
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String temp = foodQty.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
});
foodQty.setText(portionBaseString);
//btns
yesBtn = (ImageButton) findViewById(R.id.yesBtn);
noBtn = (ImageButton) findViewById(R.id.noBtn);
Bitmap tick = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_tick);
Bitmap cross = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_cross);
yesBtn.setImageBitmap(tick);
noBtn.setImageBitmap(cross);
yesBtn.setOnClickListener(this);
noBtn.setOnClickListener(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
#Override
public void onClick(View v) {
if (v == yesBtn) {
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
String date = currentDate.format(new Date());
String time = currentTime.format(new Date());
double qty = 0;
//get quantity amount
// if (portionMeasure.equals("singles")) {
//qty = foodQty.getValue();
// } else {
if (foodQty.getText().length() != 0) {
qty = Double.valueOf(foodQty.getText().toString());
} else {
qty = 0;
}
// }
if (qty == 0 || String.valueOf(qty) == "") {
Toast.makeText(getContext(), "Please enter an amount", Toast.LENGTH_SHORT).show();
} else {
//create new intake
Intake intake = new Intake(0, foodID, portionType, qty, date, time);
//record it and increment food used value
db.recordIntake(intake, user);
db.incrementUsedCount(intake.getFoodID(), 1);
db.close();
cancel();
Toast.makeText(getContext(), foodName + " recorded", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("What next?");
builder.setItems(new CharSequence[]
{"Record another food intake..", "Main Menu..", "View Stats.."},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
cancel();
break;
case 1:
Intent main = new Intent(getContext(), ProfileActivity.class);
getContext().startActivity(main);
break;
case 2:
Intent stats = new Intent(getContext(), StatsActivity.class);
getContext().startActivity(stats);
break;
}
}
});
AlertDialog choose = builder.create();
choose.show();
}
} else if (v == noBtn) {
cancel();
}
}
}
You can catch your buttons click listener as follows:
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//yes button click code here
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//no button click code here
}
});
You can use the logcat to see if your listener are being fired.

NullpointerException when called alertdialog

I want call alertdialog in my application and getting error
"12-02 09:40:07.500: E/AndroidRuntime(4693): FATAL EXCEPTION: main
12-02 09:40:07.500: E/AndroidRuntime(4693): java.lang.NullPointerException
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.getVolumeControlStream(Activity.java:3714)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Dialog.setOwnerActivity(Dialog.java:188)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.onPrepareDialog(Activity.java:2494)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.onPrepareDialog(Activity.java:2518)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.showDialog(Activity.java:2568)
12-02 09:40:07.500: E/AndroidRuntime(4693): at android.app.Activity.showDialog(Activity.java:2527)
12-02 09:40:07.500: E/AndroidRuntime(4693): at com.example.ok1.ToDoCalendarViewMaker$2.onItemLongClick(ToDoCalendarViewMaker.java:170)"
source code:
public class ToDoCalendarViewMaker extends SherlockFragmentActivity implements OnItemLongClickListener {
//final String Tag="States";
public ToDoCalendarViewMaker() {
}
public void makeGrid(Context context, View view, final MyCalendar myCalendar) {
final String Tag="States";
Log.d(Tag, "ljokj до сюдого 4");
GridView myGridView;
final Context myContext;
final Context myContext1;
View myView;
myView = view;
myContext = context;
myGridView = (GridView) myView.findViewById(R.id.gridView);
String[] from = { "text", "background" };
int[] to = { R.id.tvDay, R.id.llDay };
ArrayList<Map<String, Object>> myData = new ArrayList<Map<String, Object>>();
myData = (ArrayList<Map<String, Object>>) myCalendar.myData.clone();
SimpleAdapter sAdapter = new SimpleAdapter(myContext,
myData, R.layout.day_layout, from, to);
Log.d(Tag, "до биндера");
sAdapter.setViewBinder(new MyViewBinder());
Log.d(Tag, "после");
myGridView.setAdapter(sAdapter);
myGridView.setNumColumns(7);
myGridView.setVerticalSpacing(5);
myGridView.setHorizontalSpacing(5);
myGridView.setOnTouchListener(new MyGridOnTouchListener());
myGridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,int position, long id){
Log.d(Tag, "сработал onItemClick= "+ MainActivity.MyFlag_onClick);
if (MainActivity.MyFlag_onClick == true) {
Log.d(Tag, "идем в лист задач ");
//*********работа с БД****************
// создаем объект для данных
ContentValues cv = new ContentValues();
DBHelper dbHelper = new DBHelper(myContext);
SQLiteDatabase db = dbHelper.getWritableDatabase();
//*********работа с БД****************
// Toast.makeText(myContext,
// "" + myCalendar.returnDateById(position) + " + " + id,
// Toast.LENGTH_SHORT).show();
String id_for_listtsk=myCalendar.returnDateById(position).toString();
//добавляем строку в БД
cv.put("data_id", myCalendar.returnDateById(position));
// long rowID = db.insert("mytable", null, cv);
Log.d(Tag, "row inserted, ID = ");
Cursor c = db.query("mytable", null, null, null, null, null, null);
// logCursor(c);
dbHelper.close();
Intent intent = new Intent(myContext, ListTsk.class);
Log.d(Tag, "==== "+id_for_listtsk);
intent.putExtra("dat", id_for_listtsk.toString());
intent.putExtra("currentPagerList", "1");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Context myContext1=myContext.getApplicationContext();
myContext.startActivity(intent);
// return false;
//************************
// ToDoCalendarActivity.this.finish();
}
}
private void logCursor(Cursor c) {
// TODO Auto-generated method stub
final String Tag="States";
if (c!=null) {
if (c.moveToFirst()) {
String str;
do {
str="";
for (String cn: c.getColumnNames()) {
str = str.concat(cn + " = " + c.getString(c.getColumnIndex(cn)) + "; ");
}
Log.d(Tag, str);
} while (c.moveToNext());
}
}
}
});
myGridView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Log.d(Tag, "11111111111111");
String id_for_listtsk=myCalendar.returnDateById(position).toString();
/*
* вызываем диалог
*/
int dialogId = 0;
dialogId = DialogFactory.DIALOG_TASKS;
//ToDoCalendarActivity.showDial(dialogId);//showDialog(dialogId);
showDialog(dialogId);
//***
return true;
}});
//sAdapter.notifyDataSetChanged();
}
#Override
protected Dialog onCreateDialog(int id) {
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(dialogButtonedit1, InputMethodManager.SHOW_IMPLICIT);
return DialogFactory.getDialogById(id, ToDoCalendarActivity.context);//this
}
public static Dialog createCustomAlertTasks(final Context context) {
//Dialog dialog2=null;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from( context );
View layout = inflater.inflate(R.layout.customnew, null);
builder.setView(layout);
Dialog dialog2 = builder.setTitle("Введите новый список")
.create();
return dialog2;
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
return false;
}
}
//********************************************************
class MyViewBinder implements SimpleAdapter.ViewBinder {
int p;
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
// TODO Auto-generated method stub
int i;
switch (view.getId()) {
// LinearLayout
case R.id.llDay:
i = ((Integer) data).intValue();
if (i == -1)
view.setBackgroundResource(R.drawable.another_day);
else if (i == 0)
view.setBackgroundResource(R.drawable.day);
else if (i == 1)
view.setBackgroundResource(R.drawable.weekend);
else if (i == 2)
p=4;//view.setBackgroundResource(R.drawable.today_another_day);
else if (i == 3)
view.setBackgroundResource(R.drawable.today_day);
else if (i == 4)
p=6;//view.setBackgroundResource(R.drawable.today_weekend);
return true;
}
return false;
}
}
class MyGridOnTouchListener implements OnTouchListener{
final String Tag="States";
#Override
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
Log.d(Tag, "сработал онтач.....");
// TODO Auto-generated method stub
MainActivity.MyFlag_onClick=false;
if (paramMotionEvent.getAction() == MotionEvent.ACTION_DOWN) {
Log.d(Tag, "опустил палец");
ToDoCalendarActivity.touchX1 = paramMotionEvent.getX();
Log.d(Tag, "x1="+String.valueOf(ToDoCalendarActivity.touchX1));
ToDoCalendarActivity.touchY1 = paramMotionEvent.getY();
ToDoCalendarActivity.flag = true;
}
if (paramMotionEvent.getAction() == MotionEvent.ACTION_MOVE) {
ToDoCalendarActivity.touchY2 = paramMotionEvent.getY();
}
if (paramMotionEvent.getAction() == MotionEvent.ACTION_UP) {
ToDoCalendarActivity.touchX2 = paramMotionEvent.getX();
Log.d(Tag, "x2="+String.valueOf(ToDoCalendarActivity.touchX2));
Log.d(Tag, "Поднял палец");
if (ToDoCalendarActivity.flag==true &&
Math.abs(ToDoCalendarActivity.touchX2 - ToDoCalendarActivity.touchX1)>
Math.abs(ToDoCalendarActivity.touchY2 - ToDoCalendarActivity.touchY1)){
if (ToDoCalendarActivity.touchX2>ToDoCalendarActivity.touchX1){
if ((ToDoCalendarActivity.touchX2-ToDoCalendarActivity.touchX1)>50) {
ToDoCalendarActivity.prevMonth();
}
else if (((ToDoCalendarActivity.touchX2-ToDoCalendarActivity.touchX1)<10)) {
MainActivity.MyFlag_onClick=true;
}
Log.d(Tag, String.valueOf(ToDoCalendarActivity.touchX2-ToDoCalendarActivity.touchX1));
ToDoCalendarActivity.flag=false;
} else {
Log.d(Tag, String.valueOf(ToDoCalendarActivity.touchX1-ToDoCalendarActivity.touchX2));
if ((ToDoCalendarActivity.touchX1-ToDoCalendarActivity.touchX2)>50) {
ToDoCalendarActivity.nextMonth();
}
else if (((ToDoCalendarActivity.touchX1-ToDoCalendarActivity.touchX2)<10)) {
MainActivity.MyFlag_onClick=true;
}
ToDoCalendarActivity.flag=false;
}
}
// ToDoCalendarActivity.flag = false;
}
Log.d(Tag, "....................");
if (ToDoCalendarActivity.touchX1==ToDoCalendarActivity.touchX2){
Log.d(Tag, "Значения равны");
MainActivity.MyFlag_onClick=true;
}
return false;
}
}
public static Dialog getDialogById(int id, final Context context) {
Dialog dialog = null;
switch (id) {
case DIALOG_ALERT:
//dialog = createAlertDialog(context);
break;
case DIALOG_PROGRESS:
//dialog = createProgressDialog(context);
break;
case DIALOG_INPUT:
// dialog = Lists.createInputAlert(context);
dialog = Lists.createCustomAlertNew(context);
break;
case DIALOG_CUSTOM:
dialog = Lists.createCustomAlert(context);
break;
case DIALOG_TASKS:
dialog = ToDoCalendarViewMaker.createCustomAlertTasks(context);
break;
}
return dialog;
}
}
public class ToDoCalendarActivity extends Activity implements OnClickListener{
private KillReceiver mKillReceiver;
final String Tag="States";
static private View[] views = new View[3];
private static final String PREF_ACCOUNT_NAME = "accountName";
static MyCalendar[] cArray = new MyCalendar[3];
static ViewFlipper vf;
static int currentView;
View mainView;
AlarmManager alarmManager;
int REQUEST_CODE = 11223344;
static ToDoCalendarViewMaker toDoCalendarViewMaker;
static float touchX1,touchX2,touchY1,touchY2;
static boolean flag;
static int bb = 0;
static Context context;
static TextView myTextView;
static final String SOME_ACTION = "com.BAO.OK1.SOME_ACTION";
TextView[] textViewArray = new TextView[7];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
// if (getIntent().getBooleanExtra("finish_cal", true)) {
//
// finish();
// }
// Log.d(Tag, "!!!!!!!!!!!!!!!!!!финализируем календарь"+getIntent().getBooleanExtra("finish_cal", true));
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar_layout);
// Log.d(Tag, "ljokj до сюдого");
//кнопки отвечающие за переход по месяцам
Log.d(Tag, "Пытаемся запустить календарь");
View prevButton = findViewById(R.id.prev_button);
prevButton.setOnClickListener(this);
View nextButton = findViewById(R.id.next_button);
nextButton.setOnClickListener(this);
//останавливаем AlarmManager
try {
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent_stop_alarm = new Intent(MainActivity.BROADCAST_ACTION);
alarmManager.cancel(PendingIntent.getBroadcast(this, REQUEST_CODE, intent_stop_alarm, 0));
} catch (Exception e) {
// TODO: handle exception
}
//*******************пытаемся навешать слушатель для закрытия активити
Log.d(Tag, "Пытаемся запустить календарь");
mKillReceiver = new KillReceiver();
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
registerReceiver(mKillReceiver,intentFilter);
Log.d(Tag, "Пытаемся запустить календарь1");
//******************************************************************
vf = (ViewFlipper) findViewById(R.id.flipper);
context = getApplicationContext();
// Log.d(Tag, "ljokj до сюдого 2");
LayoutInflater ltInflater = getLayoutInflater();
for (int i = 0; i<3; i++){
views[i] = ltInflater.inflate(R.layout.grid_layout, null, false);
}
// Log.d(Tag, "ljokj до сюдого 3");
mainView = findViewById(R.id.mainll);
Log.d(Tag, "ljokj до сюдого 3.1");
cArray[0] = new MyCalendar();
Log.d(Tag, "ljokj до сюдого 3ю2");
cArray[1] = new MyCalendar();
Log.d(Tag, "ljokj до сюдого 3ю3");
cArray[2] = new MyCalendar();
Log.d(Tag, "ljokj до сюдого 3ю4");
Resources res = getResources();
MyCalendar.setNamesOfDays(
res.getString(R.string.Mon),
res.getString(R.string.Tue),
res.getString(R.string.Wed),
res.getString(R.string.Thu),
res.getString(R.string.Fri),
res.getString(R.string.Sat),
res.getString(R.string.Sun));
MyCalendar.setNamesOfMonths(
res.getString(R.string.January),
res.getString(R.string.February),
res.getString(R.string.March),
res.getString(R.string.April),
res.getString(R.string.May),
res.getString(R.string.June),
res.getString(R.string.July),
res.getString(R.string.August),
res.getString(R.string.September),
res.getString(R.string.October),
res.getString(R.string.November),
res.getString(R.string.December));
Log.d(Tag, "ljokj до сюдого 4");
cArray[0].setState();
Log.d(Tag, "ljokj до сюдого 4/0");
cArray[1].setState();
cArray[2].setState();
cArray[1].nextMonth();
toDoCalendarViewMaker = new ToDoCalendarViewMaker();
cArray[2].prevMonth();
Log.d(Tag, "ljokj до сюдого 4/1");
toDoCalendarViewMaker.makeGrid(this, views[0], cArray[0]);
Log.d(Tag, "ljokj до сюдого 4/1\1");
toDoCalendarViewMaker.makeGrid(this, views[1], cArray[1]);
Log.d(Tag, "ljokj до сюдого 4/1.2");
toDoCalendarViewMaker.makeGrid(this, views[2], cArray[2]);
Log.d(Tag, "ljokj до сюдого 4/1.3");
Log.d(Tag, "ljokj до сюдого 5");
vf.addView((View) views[0]);
vf.addView((View) views[1]);
vf.addView((View) views[2]);
currentView = 0;
myTextView = (TextView) findViewById(R.id.myText);
textViewArray[0] = (TextView) findViewById(R.id.textData);
textViewArray[1] = (TextView) findViewById(R.id.textView2);
textViewArray[2] = (TextView) findViewById(R.id.textView3);
textViewArray[3] = (TextView) findViewById(R.id.textView4);
textViewArray[4] = (TextView) findViewById(R.id.textView5);
textViewArray[5] = (TextView) findViewById(R.id.textView6);
textViewArray[6] = (TextView) findViewById(R.id.textView7);
// рисуем названия дней недели
Log.d(Tag, "ljokj до сюдого 6");
int j = MyCalendar.beforeFirstDay;
for (int i = 0; i < 7; i++) {
if (j == 7) {
j = 0;
}
textViewArray[i].setText(MyCalendar.namesOfDays[j]);
j++;
}
// рисуем текущую дату посредине
myTextView.setText(cArray[currentView].getMonthName() + " "
+ Integer.toString(cArray[currentView].getYear()));
}
#Override
public void onClick(View v) {
Log.d(Tag, "onClick");
switch (v.getId()) {
case R.id.prev_button:
prevMonth();
break;
case R.id.next_button:
nextMonth();
break;
}
}
//****
public static void nextMonth(){
vf.setInAnimation(AnimationUtils.loadAnimation(context,R.anim.next_appear));
vf.setOutAnimation(AnimationUtils.loadAnimation(context,R.anim.next_disappear));
vf.showNext();
int prevView = currentView - 1;
if (prevView == -1) prevView = 2;
currentView++;
if (currentView == 3) currentView = 0;
cArray[prevView].nextMonth();
cArray[prevView].nextMonth();
cArray[prevView].nextMonth();
toDoCalendarViewMaker.makeGrid(context, views[prevView], cArray[prevView]);
// рисуем текущую дату посредине
myTextView.setText(cArray[currentView].getMonthName() + " "
+ Integer.toString(cArray[currentView].getYear()));
}
public static void prevMonth(){
// Log.d(Tag, "предыдущий месяц");
vf.setInAnimation(AnimationUtils.loadAnimation(context,R.anim.next_appear_1));
vf.setOutAnimation(AnimationUtils.loadAnimation(context,R.anim.next_disappear_1));
vf.showPrevious();
int nextView = currentView + 1;
if (nextView == 3) nextView = 0;
currentView--;
if (currentView == -1) currentView = 2;
cArray[nextView].prevMonth();
cArray[nextView].prevMonth();
cArray[nextView].prevMonth();
toDoCalendarViewMaker.makeGrid(context, views[nextView], cArray[nextView]);
// рисуем текущую дату посредине
myTextView.setText(cArray[currentView].getMonthName() + " "
+ Integer.toString(cArray[currentView].getYear()));
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
Log.d(Tag, "onTouchEvent ToDoCalendarActivity");
if (event.getAction() == MotionEvent.ACTION_DOWN) {
touchX1 = event.getX();
Log.d(Tag, "x1="+String.valueOf(touchX1));
touchY1 = event.getY();
flag = true;
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
touchX2 = event.getX();
Log.d(Tag, "x2="+String.valueOf(touchX2));
touchY2 = event.getY();
if (flag==true && Math.abs(touchX2 - touchX1)>Math.abs(touchY2 - touchY1)){
if (touchX2>touchX1) {
Log.d(Tag, String.valueOf(touchX2-touchX1));
prevMonth();flag=false;
} else {
Log.d(Tag, String.valueOf(touchX1-touchX2));
nextMonth();flag=false;
}
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
flag = false;
}
return super.onTouchEvent(event);
}
//*****
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(0, 1, 0, "Today");
// menu.add(0, 2, 0, "Убрать выполненные");
menu.add(0, 3, 3, "Exit");
// menu.add(1, 4, 1, "copy");
// menu.add(1, 5, 2, "paste");
// menu.add(1, 6, 4, "exit");
return super.onCreateOptionsMenu(menu);
// getMenuInflater().inflate(R.menu.main, menu);
//return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
switch (item.getItemId()) {
case 1:
Intent intent = new Intent(this, MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
ListTsk.id_for_listtsk=null;
onDestroy();
break;
// case 2:
//
// break;
case 3:
//this.onDestroy();
Intent myintent = new Intent(this, MainActivity.class);
myintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myintent.putExtra("finish", true);
startActivity(myintent);
onDestroy();
// break;
}
return super.onOptionsItemSelected(item);
}
protected void onDestroy() {
super.onDestroy();
// закрываем подключение при выходе
try {
//******************************пробуем засунуть сюда настройки
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
String nastrPreferences = settings.getString(PREF_ACCOUNT_NAME, null);
//*******************************
startService(new Intent(this, ServiceUpdate.class).putExtra("preferences", nastrPreferences));
Log.d(Tag, "запустили службу ServiceUpdate");
} catch (Exception e) {
// TODO: handle exception
}
Log.d(Tag, "todocalendarActivity: onDestroy()");
finish();
// db.close();
}
#Override
protected void onStop() {
super.onStop();
Log.d(Tag, "todocalendarActivity: onStop()");
// finish();
}
#Override
protected void onPause() {
super.onPause();
//this.dbHelper.close();
Log.d(Tag, "todocalendarActivity: onPause()");
}
public static void showDial(int num) {
//Toast.makeText(context, "hello", 1000).show();
bb++;
// showDialog(num);
}
#Override
public void onBackPressed() {
// Log.d(Tag, "Была нажата кнопка возврат");
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(100);
return;
}
private final class KillReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
}
}
may be I have error in raw "return DialogFactory.getDialogById(id, ToDoCalendarActivity.context)" ? May be I must use other context? help me please

Custom List item change background in Android

Hi I am using custom listview and my list item contains checkbox. When updating the listview with the existing values the background is changed, so it is working fine.But when i clicks the check button, at that time the background will not changing after loading some where again then the background is changed . My question is at the time of check the item the background need to change immediately.
This is my adapter class.
public class GuestListAdapter extends BaseAdapter implements OnClickListener {
private String strExe;
AlertDialog.Builder builder;
Context context;
private ArrayList<String> arrayListFirstName;
private ArrayList<String> arrayListLastName;
private ArrayList<String> arrayListGuests;
private ArrayList<String> arrayCustomOne;
private ArrayList<String> arTempId;
private ArrayList<Boolean> chickinlist;
public static ArrayList<Integer> arrCheckedItems;
public static ArrayList<Integer> arrUnCheckedItems;
Button btnInfo;
private SQLiteAdapter mySqliteAdapter;
private GuestListScreen myGuestList;
private RelativeLayout views;
// private AlertDialog alertDialog = null;
private ArrayList<Boolean> checks = new ArrayList<Boolean>();
public GuestListAdapter(Context mcontext, ArrayList<String> arrListFN,
ArrayList<String> arrListLN, ArrayList<String> arrListGuest,
ArrayList<String> arrTiketID, ArrayList<String> arrCustOne,
ArrayList<Boolean> chicklist) {
clearAdapter();
arrayListFirstName = new ArrayList<String>();
arrayListLastName = new ArrayList<String>();
arrayListGuests = new ArrayList<String>();
arrayCustomOne = new ArrayList<String>();
arTempId = new ArrayList<String>();
chickinlist = new ArrayList<Boolean>();
arrCheckedItems = new ArrayList<Integer>();
arrUnCheckedItems = new ArrayList<Integer>();
arrayListFirstName = arrListFN;
arrayListLastName = arrListLN;
arrayListGuests = arrListGuest;
arrayCustomOne = arrCustOne;
arTempId = arrTiketID;
chickinlist = chicklist;
context = mcontext;
mySqliteAdapter = new SQLiteAdapter(context);
for (int i = 0; i < arrayListFirstName.size(); i++) {
checks.add(i, false);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.d("", "getCount" + arrayListFirstName.size());
return arrayListFirstName.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
Log.d("", "getItem" + arrayListFirstName.size());
return arrayListFirstName.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
final int pos = position;
views = null;
LayoutInflater layoutInflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
views = (RelativeLayout) layoutInflator.inflate(
R.layout.guest_list_item, null);
final CheckBox chk = (CheckBox) views.getChildAt(0);
// Log.d("", "CheckBox Pos "+position);
chk.setId(position);
TextView txtView = (TextView) views.getChildAt(1);
TextView txtView2 = (TextView) views.getChildAt(2);
TextView txtView3 = (TextView) views.getChildAt(3);
final TextView txtView4 = (TextView) views.getChildAt(4);
TextView txtView5 = (TextView) views.getChildAt(6);
txtView5.setId(position);
// Log.d("", "Button Pos "+position);
txtView4.setId(position);
txtView4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, InfoScreen.class);
intent.putExtra("IDVALUE",arTempId.get(txtView4.getId()) );
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
// System.out.println(v + "##########" + " " + v.getId());
// System.out.println(v + "##########" + " " + arTempId.get(txtView4.getId()));
// System.out.println(v + "##########" + " " + chickinlist.get(txtView4.getId()));
}
});
Log.e("", "****************************************************** " );
// Log.v("", "Adapter arr pos " + pos);
// Log.v("", "Adapter arr position " + position);
Log.v("", "Adapter arr size " + arrayListFirstName.size());
Log.v("", "Passsing arr size " + chickinlist.size());
for (int dd = 0; dd < arrayListFirstName.size(); dd++) {
if (position == dd) {
// Log.d("", "Passsing arr size " + chickinlist.size());
Boolean result = chickinlist.get(position);
// Log.d("", "After " + result);
if (result == true) {
chk.setChecked(true);
arrCheckedItems.add(position);
views.setBackgroundResource(R.drawable.list_item_checked);
} else {
chk.setChecked(false);
arrUnCheckedItems.add(position);
views.setBackgroundResource(R.drawable.list_item_unchecked);
}
txtView.setText(arrayListFirstName.get(position));
txtView2.setText(arrayListLastName.get(position));
txtView3.setText("(" + arrayListGuests.get(position) + ")");
if(arrayCustomOne.get(position).equalsIgnoreCase("0")||arrayCustomOne.get(position).equalsIgnoreCase(null)||arrayCustomOne.get(position).equalsIgnoreCase(""))
{
txtView5.setText("");
}else
{
txtView5.setText(arrayCustomOne.get(position));
}
}
}
chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
strExe = "update ticket_details set checkin_status=1 where tempid="+arTempId.get(chk.getId());
// Log.d("Adapter", "Checked Temp Id "+arTempId.get(chk.getId()));
Log.d("", "Position "+chk.getId()+"tempid "+arTempId.get(chk.getId()));
if (isChecked) {
// views.setBackgroundResource(R.drawable.list_item_checked);
AlertDialog.Builder builder = new AlertDialog.Builder(
context);
builder.create();
builder.setMessage(arrayListFirstName.get(chk.getId())
+ " " + arrayListLastName.get(chk.getId())
+ " has been checked in.");
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// myGuestList = new GuestListScreen();
mySqliteAdapter.executeCheckQurey(strExe);
// myGuestList.ListUpdate();
dialog.dismiss();
}
}).show();
// Log.d("", "ID = " + buttonView.getId());
} else {
// views.setBackgroundResource(R.drawable.list_item_unchecked);
strExe = "update ticket_details set checkin_status=0 where tempid="+arTempId.get(chk.getId());
mySqliteAdapter.executeCheckQurey(strExe);
// Toast.makeText(context, "check release", Toast.LENGTH_SHORT)
// .show();
}
}
});
return views;
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Integer index = (Integer) view.getTag();
boolean state = checks.get(index.intValue());
checks.set(index.intValue(), !state);
}
// private void showADialog(int posit) {
//
// AlertDialog.Builder builder = new AlertDialog.Builder(
// context);
// builder.create();
// builder.setMessage("The clicked row is "
// + arrayListFirstName.get(posit));
// builder.setPositiveButton("Ok?", new DialogInterface.OnClickListener() {
//
// #Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
//
// }).show();
// }
public void clearAdapter() {
if (arrayListFirstName != null) {
arrayListFirstName.clear();
arrayListFirstName = null;
arrayListLastName.clear();
arrayListLastName = null;
arrayListGuests.clear();
arrayListGuests = null;
arrayCustomOne.clear();
arrayCustomOne = null;
arTempId.clear();
arTempId = null;
chickinlist.clear();
chickinlist = null;
arrCheckedItems.clear();
arrCheckedItems = null;
arrUnCheckedItems.clear();
arrUnCheckedItems = null;
}
}
}
I just want to change the background of the checked item immediatly without updating the list again.
I think you need to tell the BaseAdapter to refresh the data when your OnCheckedChanged Listener is called.
GuestListAdapter.this.notifyDataSetChanged()

Activity State not saved

I want to save my Activity state while I swipe between activities but I cannot. Some things are saved and the others dont. I think it has to do somehow with the gestureListener I'm impementing but I'm not sure.
When I swipe to a different activity and then back to this one - the AsyncTask is still running and the Handler is still updating the GUI, however, the views I have displaying in this activity and the buttons are all in their initial configuration.
what am I doing wrong?
public class Main extends Activity implements OnClickListener,
SimpleGestureListener {
/** Called when the activity is first created. */
static String checkedIN = "";
private int hoursSum;
private int minutesSum;
static int dayIs;
static String madeSoFar = "";
static int hoursCount = 0;
static String formattedSeconds = "";
static String formattedMinutes = "";
public static NumberFormat formatter = new DecimalFormat("#0.00");
static boolean killcheck = false;
static String time = "";
static Handler mHandler;
private boolean clicked = false;
private boolean wasShift = false;
static String startString;
static String finishString;
private SimpleGestureFilter detector;
private Typeface tf, tf2, roboto;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// **************** Set Fonts **************
roboto = Typeface.createFromAsset(getAssets(), "fonts/robotothin.ttf");
tf = Typeface.createFromAsset(getAssets(), "fonts/Advert.ttf");
tf2 = Typeface.createFromAsset(getAssets(), "fonts/passion.ttf");
// **************** Gesture implementation ************
detector = new SimpleGestureFilter(this, this);
// **************** Date and Time Objects *************
final Date date = new Date();
final Date today = Calendar.getInstance().getTime();
DateFormat DF = new SimpleDateFormat("dd/MM/yyyy");
final String DateInString = DF.format(today);
String myString = DateFormat.getDateInstance().format(date);
final TextView dateDisplay = (TextView) findViewById(R.id.dateDisplay);
dateDisplay.setText(myString);
final DBAdapter DB = new DBAdapter(this);
// ************* Apply custom fonts ***************
TextView Title = (TextView) findViewById(R.id.textView2);
Title.setTypeface(tf);
final TextView Author = (TextView) findViewById(R.id.textView3);
Author.setTypeface(roboto);
TextView Current = (TextView) findViewById(R.id.textView1);
Current.setTypeface(roboto);
DigitalClock DG = (DigitalClock) findViewById(R.id.digitalClock1);
DG.setTypeface(roboto);
TextView dater = (TextView) findViewById(R.id.date);
dater.setTypeface(roboto);
TextView dateDisp = (TextView) findViewById(R.id.dateDisplay);
dateDisp.setTypeface(roboto);
CheckedTextView CV = (CheckedTextView) findViewById(R.id.radioButton1);
CV.setTypeface(roboto);
// *************************************************//
final Button checkIn = (Button) findViewById(R.id.CheckIn);
checkIn.setTypeface(roboto);
CheckedTextView check = (CheckedTextView) findViewById(R.id.radioButton1);
Boolean enable = false;
check.setEnabled(enable);
mHandler = new Handler() {
public void handleMessage(Message msg) {
time = "Time: " + hoursCount + ":" + formattedMinutes + ":"
+ formattedSeconds + " Money: " + madeSoFar;
Author.setText(time);
}
};
// **************** Click Listener for first Check In Button
checkIn.setOnClickListener(new OnClickListener() {
int startHours;
int startMinutes;
int finishHours;
int finishMinutes;
#Override
public void onClick(View v) {
// Check Out
if (clicked == true) {
killcheck = true;
checkedIN = "Check In";
checkIn.setText(checkedIN);
finishHours = Utility.getHoursTime();
finishMinutes = Utility.getMinutesTime();
finishString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
clicked = false;
wasShift = true;
hoursSum = finishHours - startHours;
minutesSum = finishMinutes - startMinutes;
// Check In
} else if (clicked == false) {
checkedIN = "Check Out";
checkIn.setText(checkedIN);
killcheck = false;
new ShiftProgress().execute();
startHours = Utility.getHoursTime();
startMinutes = Utility.getMinutesTime();
startString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
String s = "In Shift ";
CheckedTextView radio = (CheckedTextView) findViewById(R.id.radioButton1);
radio.setText(s);
clicked = true;
}
}
});
Button addShift = (Button) findViewById(R.id.addShift);
addShift.setTypeface(tf2);
// **************** On click listener for adding a shift
addShift.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (wasShift == true) {
changeDateToString(DateInString);
DB.open();
final Cursor cursor = DB.getAllShifts();
startManagingCursor(cursor);
cursor.moveToLast();
int count = cursor.getPosition();
final int position = count + 2;
cursor.moveToNext();
GregorianCalendar GC = new GregorianCalendar();
DB.addToDBTotal(DateInString, "Money: " + madeSoFar,
hoursSum, minutesSum,
Utility.getDay(GC.get(Calendar.DAY_OF_WEEK)),
position, startString, finishString);
DBAdapter.close();
wasShift = false;
printAny(getApplicationContext(), "Added to Shifts",
Toast.LENGTH_SHORT);
} else {
printAny(getApplicationContext(), "Please Check In First", Toast.LENGTH_SHORT);
}
}
});
}
// **************** METHOD DECLERATIONS ****
public void viewShifts() {
Intent myIntent = new Intent(Main.this, Shifts.class);
startActivity(myIntent);
}
public void changeDateToString(String s) {
Utility.INSTANCE.setDate(s);
}
public void changeDurationToString(String s) {
Utility.INSTANCE.setDuration(s);
}
public void printAny(Context c, CharSequence s, int i) {
Context context = c;
CharSequence text = s;
final int duration = i;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.exit:
System.exit(1);
DBAdapter.close();
return true;
case R.id.view:
viewShifts();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onSwipe(int direction) {
Intent intent = new Intent();
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_LEFT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
}
public class ShiftProgress extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
int count = 0;
int seconds = 0;
int minutesTime = 0;
int minutesCount = 1;
for (;;) {
if (seconds % 60 == 0) {
minutesTime = count / 60;
seconds = 0;
}
if (seconds < 10) {
formattedSeconds = String.format("%02d", seconds);
}
else if (seconds >= 10) {
formattedSeconds = String.valueOf(seconds);
}
if (minutesTime < 10) {
formattedMinutes = String.format("%02d", minutesTime);
}
else if (minutesTime >= 10) {
formattedMinutes = String.valueOf(minutesTime);
}
if (minutesTime % 60 == 0) {
hoursCount = minutesCount / 60;
minutesTime = 0;
}
double sal = 40;
double SEC = 3600;
double salper = count * (sal / SEC);
madeSoFar = String.valueOf(formatter.format(salper));
try {
mHandler.obtainMessage(1).sendToTarget();
Thread.sleep(1000);
seconds++;
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
if (killcheck) {
break;
}
}
// int length = count /360;
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}
}
#Override
public void onSaveInstanceState() {
// TODO Auto-generated method stub
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
checkedIN = savedInstanceState.getString("checkIN");
clicked = savedInstanceState.getBoolean("button");
Toast.makeText(this, "Activity state Restored", Toast.LENGTH_LONG);
}
#Override
public void onPause(Bundle b) {
// TODO Auto-generated method stub
b.putString("checkIN", checkedIN);
b.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
super.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("checkIN", checkedIN);
outState.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
// etc.
super.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Activity is getting killed", Toast.LENGTH_LONG)
.show();
}
}
You should not keep your Async task running in the background when your activity is send to the background. Your activity can be quit at any time so that you wouldn't have a reference to your activity anymore.
Regarding the preservation of state you could have a look at Activity.onRetainNonConfigurationInstance()

Categories

Resources