NullpointerException when called alertdialog - android

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

Related

Getting ArrayIndexOutofBoundsException in android listview

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.

xml not showing checkbox prechecked

i have create an app in which,i want to show the checkbox prechecked with the help of xml,and after that user can checked or uncheked the checkbox,but xaml is not showing it checked on start of the app in device,what is the problem.please advise.
MainActivity
public class File_Selecter extends Activity implements OnItemClickListener {
EditText edDelimiter, edqualifier, edcolumn, edrow;
ListView list;
StringBuilder addition = new StringBuilder();
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
ArrayList<String> list3 = new ArrayList<String>();
ArrayList<String> phno0 = new ArrayList<String>();
private Button btnsave;
String str;
int t;
int count = 0;
String[] BreakData, roz;
TextView textnum;
static String fileinfo;
static StringBuilder conct = new StringBuilder();
static int ResultCode = 12;
String name = "", number = "";
MyAdapter ma;
String fin = "";
String[] cellArray;
String[] art = null;;
String pathname = Environment.getExternalStorageDirectory()
.getAbsolutePath();
static String contacts = "";
static String mixer;
static String delimiter, qulifier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_file);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
ColorDrawable colorDrawable = new ColorDrawable(
Color.parseColor("#00aef0"));
actionBar.setBackgroundDrawable(colorDrawable);
Intent itadd = new Intent();
// edittext name
// final String name=itadd.getStringExtra("name").toString();
textnum = (TextView) findViewById(R.id.textnum1);
list = (ListView) findViewById(R.id.listview);
ma = new MyAdapter();
list.setAdapter(ma);
// list.setOnItemClickListener(this);
// list.setItemsCanFocus(false);
// list.setTextFilterEnabled(true);
edDelimiter = (EditText) findViewById(R.id.edDelimiter);
edcolumn = (EditText) findViewById(R.id.edcoloumns);
edrow = (EditText) findViewById(R.id.edrow);
edqualifier = (EditText) findViewById(R.id.edqualifier);
// edittext number
// final String number=itadd.getStringExtra("number").toString();
edDelimiter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
edDelimiter.setError(null);
}
});
if(fileinfo!=null){
//Toast.makeText(getApplication(),
//fileinfo.toString(), Toast.LENGTH_LONG)
//.show();
if (delimiter != null){
edDelimiter.setText( SmsSend
.delim1.toString());
qulifier= SmsSend
.qulifier.toString(); }
ToRead(fileinfo);
// contacts from smssend
contacts = SmsSend.contacts1;
if (SmsSend.contacts1 != null) {
cellArray = contacts.split(";");
if(list2.size() != 0){
for (int i = 0; i < cellArray.length; i++) {
for (int j = 0; j < list2.size(); j++) {
if (list2.get(j).contains(cellArray[i])) {
//ma.setChecked(j, true);
break;
}}}}
else{
for (int i = 0; i < cellArray.length; i++) {
for (int j = 0; j < list1.size(); j++) {
if (list1.get(j).contains(cellArray[i])) {
//ma.setChecked(j, true);
break;
}
}
}
}
}
}
// button1
btnsave = (Button) findViewById(R.id.btnsave);
btnsave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(edDelimiter.getText().toString().length()== 0){
edDelimiter.setError("Delimiter ir required");
}
if(File_Explorer.fileSizeInMB <= 1){
ToRead(fileinfo);
//finish();
}else{
Toast.makeText(getApplication(), "file size is too large", Toast.LENGTH_LONG).show();
}
}
});
}
public void ToRead(String fileinfo) {
if (fileinfo != null) {
delimiter = edDelimiter.getText().toString();
// Toast.makeText(getApplication(), delimiter, Toast.LENGTH_LONG).show();
//delim=":";
qulifier = edqualifier.getText().toString();
//Toast.makeText(getApplication(), qulifier.toString(), Toast.LENGTH_LONG).show();
// qulifier="\\";
// finish();
mixer = qulifier + delimiter;
BreakData = fileinfo.split(mixer);
str = edrow.getText().toString().trim();
try {
t = Integer.parseInt(str);
} catch (NumberFormatException nfe) {
// Handle parse error.
}
if (BreakData != null) {
// String t2= (String.valueOf(t));
if (File_Explorer.fileExtension.equals("vcf")) {
if (!(String.valueOf(t)).equals("0")) {
if (t > BreakData.length) {
Toast.makeText(getApplication(),
"Data is less then entered rows",
Toast.LENGTH_LONG).show();
Arrays.fill(BreakData, null);
Toast.makeText(getApplication(),
"empty.................", Toast.LENGTH_LONG)
.show();
} else {
for (int i = 0; i < BreakData.length; i++) {
if (BreakData[i].contains("FN")) {
art = BreakData[i + 1].split("\n");
name = art[0].toString();
} else if (BreakData[i].contains("TEL;CELL")) {
roz = BreakData[i + 1].split("\n");
number = roz[0].toString();
fin = name.toString() + "\n" + "\n"
+ number.toString();
list2.add(fin.toString());
}
}
for (int a = 0; a < list2.size() && a < t; a++) {
list1.add(list2.get(a).toString());
}
}
textnum.setText(Integer.toString(list1.size()));
}
else {
for (int i = 0; i < BreakData.length; i++) {
if (BreakData[i].contains("FN")) {
art = BreakData[i + 1].split("\n");
name = art[0].toString();
} else if (BreakData[i].contains("TEL;CELL")) {
roz = BreakData[i + 1].split("\n");
number = roz[0].toString();
fin = name.toString() + "\n" + "\n"
+ number.toString();
list1.add(fin.toString());
}
}
textnum.setText(Integer.toString(list1.size()));
}
} else {
if (!(String.valueOf(t)).equals("0")) {
if (t > BreakData.length) {
Toast.makeText(getApplication(),
"Data is less then entered rows",
Toast.LENGTH_LONG).show();
Arrays.fill(BreakData, null);
Toast.makeText(getApplication(),
"empty.................", Toast.LENGTH_LONG)
.show();
} else {
for (int i = 0; i < BreakData.length && i < t; i++) {
list1.add(BreakData[i].toString());
}
textnum.setText(Integer.toString(t));
}
}
else {
for (int i = 0; i < BreakData.length; i++) {
list1.add(BreakData[i].toString());
//t = i;
}
textnum.setText(Integer.toString(BreakData.length));
}
}
}
}
list.setAdapter(ma);
// fileinfo= null;
//edDelimiter.setText(null);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
StringBuilder checkedcontacts = new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for (int i = 0; i < list1.size(); i++)
{
if (ma.mCheckStates.get(i) == false) {
// Toast.makeText(getApplication(), "hiii",
// Toast.LENGTH_LONG).show();
StringTokenizer st1 = new StringTokenizer(list1.get(i)
.toString(), "\n");
String first = st1.nextToken();
String second = st1.nextToken();
phno0.add(second.toString());
checkedcontacts.append(list1.get(i).toString());
checkedcontacts.append("\n");
} else {
System.out.println("..Not Checked......"
+ list1.get(i).toString());
}
}
//Toast.makeText(getApplication(), phno0.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("extermal_name", phno0);
setResult(RESULT_OK, returnIntent);
finish();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.add_button, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.attachments:
fileinfo = null;
Intent i = new Intent(File_Selecter.this, File_Explorer.class);
startActivityForResult(i, ResultCode);
break;
case android.R.id.home:
// app icon in action bar clicked; go home
StringBuilder checkedcontacts = new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for (int j = 0; j < list1.size(); j++)
{
if (ma.mCheckStates.get(j) == true) {
StringTokenizer st1 = new StringTokenizer(list1.get(j)
.toString(), "\n");
String first = st1.nextToken();
String second = st1.nextToken();
phno0.add(second.toString());
checkedcontacts.append(list1.get(j).toString());
checkedcontacts.append("\n");
} else {
System.out.println("..Not Checked......"
+ list1.get(j).toString());
}
}
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("extermal_name", phno0);
setResult(RESULT_OK, returnIntent);
finish();
break;
}
return super.onOptionsItemSelected(item);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ResultCode) {
if (resultCode == RESULT_OK) {
fileinfo = data.getStringExtra("name");
}
// list.setAdapter(ma);
}
if (resultCode == RESULT_CANCELED) {
}
}
AdapterCLass
class MyAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
public SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(list1.size());
mInflater = (LayoutInflater) File_Selecter.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// Save ListView state
#Override
public int getCount() {
// TODO Auto-generated method stub
return list1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.row, null);
tv = (TextView) vi.findViewById(R.id.textView1);
// tv1 = (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText(list1.get(position));
// tv1.setText(phno1.get(position));
cb.setTag(position);
//cb.setChecked(mCheckStates.get(position, true));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
row.layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:ems="20"
android:text="TextView"
android:textColor="#0082e6" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:checked="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="22dp"
android:layout_marginTop="5dp" />
</RelativeLayout>

Error when I do onclick

I have my Custom SimpleCursorAdapter MySqlCursorAdapter. I want use MySqlCursorAdapter in my class PageFragment but, I have an error when onclick any button on.CopyOfMainActivity activity
PageFragment.java
public class PageFragment extends Fragment {
static final String ARGUMENT_PAGE_NUMBER = "arg_page_number";
int pageNumber;
int backColor;
final String Tag="States";
SQLiteDatabase db;
static Cursor c, c2;
ContentValues cv;
static int itemselected, id_itemselected;
final static int M_EDIT1 = 100;
final static int M_EDIT2 = 101;
final static int M_DELETE = 102;
final static int M_ADD = 103;
final static int M_REF = 104;
final static int D_EDIT = 200;
final static int D_DELETE = 201;
final static int D_ADD = 202;
ListView lvMain_today;
DialogFragment dlg1;
TextView tv;
static SimpleCursorAdapter scAdapter, scAdapter2;
MySqlCursorAdapter adapter = null;
static PageFragment newInstance(int page) {
PageFragment pageFragment = new PageFragment();
Bundle arguments = new Bundle();
arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
pageFragment.setArguments(arguments);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(ARGUMENT_PAGE_NUMBER);
// dlg1 = new dialog_edit();
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case M_EDIT1:
dlg1.show(getFragmentManager(), "dlg1");
break;
case M_EDIT2:
Toast.makeText(getActivity(), "Изменение во втором списке", Toast.LENGTH_SHORT).show();
break;
case M_DELETE:
//dlg2.show(getFragmentManager(), "dlg2");
break;
case M_ADD:
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(Tag, "onCreateView1");
View view = inflater.inflate(R.layout.activity_page_fragment, null);
lvMain_today = (ListView) view.findViewById(R.id.list);
//tv = (TextView) view.findViewById(R.id.tv);
Log.d(Tag, "onCreateView2");
OnCreateContextMenuListener occm1 = new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
AdapterContextMenuInfo aMenuInfo = (AdapterContextMenuInfo) menuInfo;
itemselected = aMenuInfo.position;
id_itemselected = (int) aMenuInfo.id;
menu.add(Menu.NONE, M_EDIT1, Menu.NONE, "Изменить1");
menu.add(Menu.NONE, M_DELETE, Menu.NONE, "Удалить1");
menu.add(Menu.NONE, M_ADD, Menu.NONE, Integer.toString(id_itemselected));
}
};
Log.d(Tag, "onCreateView3");
OnCreateContextMenuListener occm2 = new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
AdapterContextMenuInfo aMenuInfo = (AdapterContextMenuInfo) menuInfo;
itemselected = aMenuInfo.position;
id_itemselected = (int) aMenuInfo.id;
menu.add(Menu.NONE, M_EDIT2, Menu.NONE, "Изменить2");
menu.add(Menu.NONE, M_DELETE, Menu.NONE, "Удалить2");
menu.add(Menu.NONE, M_ADD, Menu.NONE, Integer.toString(id_itemselected));
}
};
switch (pageNumber){
case 0:
Log.d(Tag, "switch (pageNumber)1");
// DBase = new DataBase(getActivity());
// db = DBase.getWritableDatabase();
// c = db.query("items1", null, null, null, null, null, null);
case 1:
//пробуем*****
Log.d(Tag, "onCreateView4");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String id_for_listtsk_today = sdf.format(new Date());
ContentValues cv = new ContentValues();
DBHelper dbHelper = new DBHelper(getActivity());
final SQLiteDatabase db = dbHelper.getWritableDatabase();
Log.d(Tag, "onCreateView5");
try {
c=dbHelper.getCursor(id_for_listtsk_today);
} catch (SQLException sqle) {
Log.d(Tag, "неудача");
throw sqle;
}
String[] arr_date = Pager.logCursor(c);
//*************
Log.d(Tag, "onCreateView6");
getActivity().startManagingCursor(c);
int[] listFields = new int[] { R.id.txtTitle, R.id.textData1 };
String[] dbColumns = new String[] { DBHelper.COLUMN_NAME, DBHelper.COLUMN_TASK };
// Log.d(Tag, "трассировка" );
adapter = new MySqlCursorAdapter(
getActivity(), R.layout.my_list_item,
c, dbColumns, listFields,
dbHelper);
Log.d(Tag, "onCreateView7");
lvMain_today.setAdapter(adapter);
registerForContextMenu(lvMain_today);
lvMain_today.setOnCreateContextMenuListener(occm1);
db.close();
break;
// Log.d(Tag, "switch (pageNumber)2");
// DBase = new DataBase(getActivity());
// db = DBase.getWritableDatabase();
// c2 = db.query("items2", null, null, null, null, null, null);
// getActivity().startManagingCursor(c2);
// String[] from2 = new String[] {"item"};
// int[] to2 = new int[] {R.id.tvText};
// scAdapter2 = new SimpleCursorAdapter(getActivity(), R.layout.item, c2, from2, to2);
// lvMain.setAdapter(scAdapter2);
// lvMain.setOnCreateContextMenuListener(occm2);
// db.close();
// break;
}
return view;
}
}
CopyOfMainActivity.java
public class CopyOfMainActivity extends FragmentActivity implements OnClickListener {
// Button btnCalendar;
//*******************************************8
String[] names = {"Иван", "Марья", "Петр", "Антон", "Даша", "Борис",
"Костя", "Игорь", "Анна", "Денис", "Андрей"};
//Button buttonAddTask;
public final static String FILE_NAME = "filename";
public final static String BROADCAST_ACTION = "ru.ok.intent.action.repeatingalarmservice";
final String Tag="States";
final String Ten = "Ten";
static String login;
TextView txtDataTaskToday;
String id_for_listtsk_today;
ListView lvMain_today;
String[] arr_date;
SharedPreferences sPref;
static Cursor c;
private ListView listView = null;
SQLiteDatabase db;
static boolean MyFlag_onClick = false;
Button Bcalendar;
Button BAddTask;
Button Refresh;
LinearLayout ll;
Context ctx;
//public static String id_for_listtsk_today;
// static SQLiteDatabase db;
MySqlCursorAdapter adapter = null;
private static final int CM_DELETE_ID = 1;
private AlarmManagerBroadcastReceiver alarm;
//private UpdateCursorBroadcastReceiver alarmUpdateCursor;
//пробуем зарегить Broadcast
// RepeatingAlarmService br;
public static final String APP_PREFERENCES = "mysettings";
public static final String ACCAUNT_NAME = "accauntName";
AlarmManager alarmManager;
int REQUEST_CODE = 11223344;
//*******************Google*********************
private static final Level LOGGING_LEVEL = Level.OFF;
private static final String PREF_ACCOUNT_NAME = "accountName";
static final String TAG = "TasksSample";
static final int REQUEST_GOOGLE_PLAY_SERVICES = 0;
static final int REQUEST_AUTHORIZATION = 1;
static final int REQUEST_ACCOUNT_PICKER = 2;
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = new GsonFactory();
GoogleAccountCredential credential;
List<String> tasksList;
List<String> tasksList_Note;
List<String> result_Date;
final String ATTRIBUTE_TITLE_TEXT="title";
final String ATTRIBUTE_NOTE_TEXT="note";
final String ATTRIBUTE_DATE_TEXT="date";
static com.google.api.services.tasks.Tasks service;
int numAsyncTasks;
//переменные для Pager
static final int PAGE_COUNT = 4;
ViewPager pager;
PagerAdapter pagerAdapter;
LinearLayout L_view;
//***********************************************8
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(Tag, "copyofMaimActivity1...");
if (getIntent().getBooleanExtra("finish", false)) finish();
super.onCreate(savedInstanceState);
Log.d(Tag, "copyofMaimActivity2");
ll = (LinearLayout) findViewById(R.id.ll);
setContentView(R.layout.pager_activity_main);
// btnCalendar = (Button) findViewById(R.id.btnActTwo);
// btnCalendar.setOnClickListener(this);
//останавливаем AlarmManager
try {
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent_stop_alarm = new Intent(BROADCAST_ACTION);
alarmManager.cancel(PendingIntent.getBroadcast(this, REQUEST_CODE, intent_stop_alarm, 0));
} catch (Exception e) {
// TODO: handle exception
}
Bcalendar = (Button) findViewById(R.id.Bcalendar);
BAddTask = (Button) findViewById(R.id.BAddTask);
Bcalendar.setOnClickListener(this);
BAddTask.setOnClickListener(this);
Refresh = (Button) findViewById(R.id.refresh);
Refresh.setOnClickListener(this);
alarm = new AlarmManagerBroadcastReceiver();
//alarmUpdateCursor = new UpdateCursorBroadcastReceiver();
//*********************************************
// переменные для query
String[] columns = null;
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
//*********работа с БД****************
// создаем объект для данных
txtDataTaskToday = (TextView) findViewById(R.id.txtDataTaskToday);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String id_for_listtsk_today = sdf.format(new Date());
//final String b = id_for_listtsk_today;
txtDataTaskToday.setText(id_for_listtsk_today.toString());
// txtDataTaskToday.setPaintFlags(txtDataTaskToday.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
// Log.d(Tag, "id_for_listtsk_today ="+id_for_listtsk_today );
ContentValues cv = new ContentValues();
DBHelper dbHelper = new DBHelper(this);
final SQLiteDatabase db = dbHelper.getWritableDatabase();
columns = new String[] {"name"};
selection = "data_id = ?";
selectionArgs = new String[] {id_for_listtsk_today};
//c = db.query("mytable", columns, selection, selectionArgs, null, null, null);
try {
c=dbHelper.getCursor(id_for_listtsk_today);
} catch (SQLException sqle) {
Log.d(Tag, "неудача");
throw sqle;
}
// String[] arr_date = logCursor(c);
Log.d(Tag, "paint_LV");
// paint_LV(c, dbHelper);тут закоментили так как делаем Pager
//toCallAsynchronous();//запускаем аналог слушателя
// создаем фильтр для BroadcastReceiver
// br = new RepeatingAlarmService();
// IntentFilter intFilt = new IntentFilter(BROADCAST_ACTION);
// // регистрируем (включаем) BroadcastReceiver
// registerReceiver(br, intFilt);
//проверяем настройки аккаунта
googleConnect();
//останавливаем и запускаем службу обновления БД и Гугла
Log.d(Tag,"pager 1");
pager = (ViewPager) findViewById(R.id.pager);
Log.d(Tag,"pager 2");
pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
Log.d(Tag,"pager 3");
pager.setAdapter(pagerAdapter);
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
Log.d(Tag, "onPageSelected, position = " + position);
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
void refreshView() {
Log.d(Tag, "refreshView");
// pager = (ViewPager) findViewById(R.id.pager);
Log.d(Tag,"pager 2");
pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
Log.d(Tag,"pager 3");
pager.setAdapter(pagerAdapter);
}
private void paint_LV(Cursor c, DBHelper dbHelper) {
//*********работа с БД****************
lvMain_today = (ListView) findViewById(R.id.list);
// lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//this.listView=getl
//listView = MainActivity.this.getlgetListView();
int n = 0; // прокручиваем до начала
lvMain_today.smoothScrollToPosition(n);
lvMain_today.setItemsCanFocus(false);
lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, arr_date);// R.layout.item, my_list_item
startManagingCursor(c);
int[] listFields = new int[] { R.id.txtTitle, R.id.textData1 };
String[] dbColumns = new String[] { DBHelper.COLUMN_NAME, DBHelper.COLUMN_TASK };
// Log.d(Tag, "трассировка" );
CopyOfMainActivity.this.adapter = new MySqlCursorAdapter(
this, R.layout.my_list_item,
c, dbColumns, listFields,
dbHelper);
//
lvMain_today.setAdapter(CopyOfMainActivity.this.adapter);
registerForContextMenu(lvMain_today);
// setListAdapter(MainActivity.this.adapter);
//lvMain_today.setItemsCanFocus(true);
names = arr_date;
//проверяем наличие интернета
// isOnline();
// alarmUpdateCursor.CancelAlarm(this);
// alarmUpdateCursor.SetAlarm(this);
//c.close();
//db.close();
//dbHelper.close();
}
private String[] logCursor(Cursor c) {
// TODO Auto-generated method stub
final String Tag="States";
String[] arr_date = new String[c.getCount()];//String[] arr_date = new String[] {};
// Log.d(Tag,"мы в курсоре");
if (c!=null) {
if (c.moveToFirst()) {
// Log.d(Tag,"мы в курсоре1");
String str;
int i=-1;
do {
// Log.d(Tag,"мы в курсоре2");
str="";
i=i+1;
for (String cn: c.getColumnNames()) {
str = str.concat(c.getString(c.getColumnIndex(cn)));
}
// Log.d(Tag, "++++"+str);
arr_date[i]=String.valueOf(str);
} while (c.moveToNext());
}
}
return arr_date;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// menu.add(0, 1, 0, "Calendar");
// menu.add(0, 2, 0, "Start");
menu.add(0, 3, 3, "Exit");
// menu.add(0, 4, 1, "Google");
menu.add(1, 5, 2, "Stop");
menu.add(1, 6, 4, "accaunt");
menu.add(1, 7, 4, "pager");
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();
// Выведем в TextView информацию о нажатом пункте меню
// txtDataTaskToday.setText("Item Menu");
// txtDataTaskToday.setText(item.getGroupId());
// txtDataTaskToday.setText("\r\n itemId: " + String.valueOf(item.getItemId()));
// txtDataTaskToday.setText("\r\n order: " + String.valueOf(item.getOrder()));
// txtDataTaskToday.setText("\r\n title: " + item.getTitle());
switch (item.getItemId()) {
case 1:
Intent intent = new Intent(this, ToDoCalendarActivity.class);
// sdt.execute();
onDestroy();
break;
case 2:
//******************************пробуем засунуть сюда настройки
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
String nastrPreferences = settings.getString(PREF_ACCOUNT_NAME, null);
//*******************************
startService(new Intent(this, ServiceUpdate.class).putExtra("preferences", nastrPreferences));
break;
case 3:
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(Ten, "");
Log.d(Tag, "пытаемся выйти");
Intent intent_cal = new Intent("com.BAO.OK1.SOME_ACTION");;
// intent_cal.setType("spartan");
sendBroadcast(intent_cal);
onDestroy();
//finish();
break;
case 4:
Log.d(Tag, "пытаемся открыть гугл");
Intent intent_google = new Intent(this, TasksSample.class);
startActivity(intent_google);
onDestroy();
break;
case 5:
//stopService(new Intent(this, ServiceUpdate.class));
//останавливаем AlarmManager
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent_stop_alarm = new Intent(BROADCAST_ACTION);
alarmManager.cancel(PendingIntent.getBroadcast(this, REQUEST_CODE, intent_stop_alarm, 0));
break;
case 6:
//googleConnect();
rewriteAccaunt();
break;
case 7:
Intent intent_pager = new Intent(this, Pager.class);
startActivity(intent_pager);
// sdt.execute();
onDestroy();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
try {
CopyOfMainActivity.this.onRestart();
} catch (Exception e) {
// Log.d(Tag, "не получилось рестартануть");
}
// Log.d(Tag, "MainActivity: onStart()");
if(alarm != null){
alarm.CancelAlarm(this);
}else{
Toast.makeText(this, "Alarm is null", Toast.LENGTH_SHORT).show();
}
Log.d(Tag, "конец фуекции onstart");
}
#Override
protected void onResume() {
super.onResume();
// if (checkGooglePlayServicesAvailable()) {
// haveGooglePlayServices();
// }
// Log.d(Tag, "MainActivity: onResume()");
}
protected void onDestroy() {
super.onDestroy();
// закрываем подключение при выходе
// ToDoCalendarActivity.this.finish();
Log.d(Tag, "начинаем onDestroy");
finish();
Log.d(Tag, "финишировали onDestroy");
// db.close();
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
}
}
#Override
protected void onPause() {
super.onPause();
//this.dbHelper.close();
// Log.d(Tag, "MainActivity: onPause()");
}
#Override
protected void onStop() {
super.onStop();
// Log.d(Tag, "MainActivity: onStop()");
}
#Override
protected void onRestart() {
super.onRestart();
// new SelectDataTask().execute();
// Log.d(Tag, "MainActivity: onRestart()");
}
#Override
public void onBackPressed() {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(100);
// Log.d(Tag, "Была нажата кнопка возврат");
return;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d(Tag, "onClick(View v)");
switch (v.getId()) {
case R.id.Bcalendar:
Intent intent = new Intent(this, ToDoCalendarActivity.class);
// intent.putExtra("finish_cal", false);
startActivity(intent);
Log.d(Tag, "пытаемся перейти в КАЛЕНДАРЬ");
onDestroy();
break;
case R.id.BAddTask:
Toast.makeText(this, "добавляем значение", Toast.LENGTH_LONG).show();
Log.d(Tag,"BAddTask" + ListTsk.id_for_listtsk);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String id_for_listtsk_today = sdf.format(new Date());
Intent intent_add = new Intent(this, AddLineBD.class);
intent_add.putExtra("id_for_list", id_for_listtsk_today);
startActivity(intent_add);
onDestroy();
break;
case R.id.refresh:
CopyOfAsyncLoadTasks_Del.run(this);
break;
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
Log.d(Tag, "создаем контекстное меню");
menu.add(0, CM_DELETE_ID, 0, "Удалить запись");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
Log.d(Tag, "показываем контекстное меню");
String[] columns = null;
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
if (item.getItemId() == CM_DELETE_ID) {
// получаем инфу о пункте списка
AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) item.getMenuInfo();
ContentValues cv = new ContentValues();
DBHelper dbHelper = new DBHelper(this);
final SQLiteDatabase db = dbHelper.getWritableDatabase();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String id_for_listtsk_today = sdf.format(new Date());
int delCount = db.delete("mytable", "_id = " + acmi.id, null);
Log.d(Tag, "dcxdcc");
columns = new String[] {"name"};
selection = "data_id = ?";
selectionArgs = new String[] {id_for_listtsk_today};
try {
c=dbHelper.getCursor(id_for_listtsk_today);
} catch (SQLException sqle) {
// Log.d(Tag, "неудача");
throw sqle;
}
// String[] arr_date = logCursor(c);
paint_LV(c, dbHelper);
// MainActivity.this.adapter.notifyDataSetChanged();
dbHelper.close();
// удаляем Map из коллекции, используя позицию пункта в списке
// data.remove(acmi.position);
// уведомляем, что данные изменились
// sAdapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PageFragment.newInstance(position);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return "Title " + position;
}
}
Log
06-11 11:58:12.828: D/States(12636): начинаем onDestroy
06-11 11:58:12.835: D/States(12636): финишировали onDestroy
06-11 11:58:16.218: D/AndroidRuntime(12636): Shutting down VM
06-11 11:58:16.218: W/dalvikvm(12636): threadid=1: thread exiting with uncaught exception (group=0x40018578)
06-11 11:58:16.289: E/AndroidRuntime(12636): FATAL EXCEPTION: main
06-11 11:58:16.289: E/AndroidRuntime(12636): java.lang.RuntimeException: Unable to pause activity {com.example.ok1/com.example.ok1.CopyOfMainActivity}: java.lang.IllegalStateException: No activity
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2358)
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2315)
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:2295)
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.app.ActivityThread.access$1700(ActivityThread.java:117)
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:942)
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.os.Handler.dispatchMessage(Handler.java:99)
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.os.Looper.loop(Looper.java:130)
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.app.ActivityThread.main(ActivityThread.java:3687)
06-11 11:58:16.289: E/AndroidRuntime(12636): at java.lang.reflect.Method.invokeNative(Native Method)
06-11 11:58:16.289: E/AndroidRuntime(12636): at java.lang.reflect.Method.invoke(Method.java:507)
06-11 11:58:16.289: E/AndroidRuntime(12636): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
06-11 11:58:16.289: E/AndroidRuntime(12636): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
06-11 11:58:16.289: E/AndroidRuntime(12636): at dalvik.system.NativeStart.main(Native Method)
06-11 11:58:16.289: E/AndroidRuntime(12636): Caused by: java.lang.IllegalStateException: No activity
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1075)
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1070)
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.support.v4.app.FragmentManagerImpl.dispatchPause(FragmentManager.java:1875)
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.support.v4.app.FragmentActivity.onPause(FragmentActivity.java:401)
06-11 11:58:16.289: E/AndroidRuntime(12636): at com.example.ok1.CopyOfMainActivity.onPause(CopyOfMainActivity.java:490)
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.app.Activity.performPause(Activity.java:3862)
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1191)
06-11 11:58:16.289: E/AndroidRuntime(12636): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2345)
06-11 11:58:16.289: E/AndroidRuntime(12636): ... 12 more
06-11 11:58:16.367: D/dalvikvm(12636): GC_CONCURRENT freed 179K, 45% free 3237K/5831K, external 1231K/1560K, paused 4ms+3ms
My_list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#CCFFCC"
android:gravity="center_vertical"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/bcheck"
android:layout_width="62dp"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:focusable="false"
android:gravity="center_vertical|center_horizontal" />
<LinearLayout
android:layout_width="246dp"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:gravity="left|center_vertical"
android:maxLength="25"
android:text="Test"
android:textColor="#000000"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/textData1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="false"
android:maxLength="40"
android:maxLines="1"
android:scrollHorizontally="true"
android:text="TextView"
android:textColor="#000000" />
</LinearLayout>
</LinearLayout>
Pager.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.PagerTabStrip
android:id="#+id/pagerTabStrip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top">
</android.support.v4.view.PagerTabStrip>
</android.support.v4.view.ViewPager>
</RelativeLayout>
activity_page_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#+id/lvMain"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tv"
android:text="Запись 1">
</TextView>
</LinearLayout>
What I do not correctly? How I understand error appear in "destroy" activity
Lots of code with lots of problems. Didn't read all of it so this answer does not solve everything but hopefully it helps you forward on your learning path. #Houcine's findings are also helpful though they don't directly answer to the exception issue you're seeing.
finish() in onDestroy() is not correct. The activity is already being destroyed. Remove it.
Calling onDestroy() directly is not correct. Remove the calls. If you want to close your activity, just call finish().
Generally, the onXxx() overrides are called by framework when a specific event occurs. You should not call them yourself.
Also, in onCreate() you're potentially finishing the activity before it is created properly:
if (getIntent().getBooleanExtra("finish", false)) finish();
super.onCreate(savedInstanceState);
in your onCreate() method you have two problems :
1- You are finishing the activity before its creation.
Log.d(Tag, "copyofMaimActivity1...");
if (getIntent().getBooleanExtra("finish", false)) finish();
super.onCreate(savedInstanceState);
Correction : you should call the super.onCreate() method before any operation you want to do in your Activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(Tag, "copyofMaimActivity1...");
super.onCreate(savedInstanceState);//should be the first instruction of the onCreate() method
if (getIntent().getBooleanExtra("finish", false)) finish();
// your code.....
}
2- you are trying to find a View before setting the Content layout to your Activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(Tag, "copyofMaimActivity1...");
if (getIntent().getBooleanExtra("finish", false)) finish();
super.onCreate(savedInstanceState);
Log.d(Tag, "copyofMaimActivity2");
ll = (LinearLayout) findViewById(R.id.ll); //ll will be null and you will have a NullPointerException
setContentView(R.layout.pager_activity_main);
}
Correction : you should call the setContentView(int resId); before any operation of retrieving a view by its id ( or by its tag) :
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(Tag, "copyofMaimActivity1...");
if (getIntent().getBooleanExtra("finish", false)) finish();
super.onCreate(savedInstanceState);
Log.d(Tag, "copyofMaimActivity2");
setContentView(R.layout.pager_activity_main); // should be called before any call of findViewById()
//your code ...
}
ll = (LinearLayout) findViewById(R.id.ll);
In your onDestroy() method , you have a problem with the call of onFinish(), you are calling super.onDestroy() which will kill the activity , and you are trying to call the finish() method ( killing the activity that is already destroyed by the call of super.onDestroy(). your code should be like this :
protected void onDestroy() {
// закрываем подключение при выходе
Log.d(Tag, "начинаем onDestroy");
Log.d(Tag, "финишировали onDestroy");
// db.close();
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
}
finally {
super.onDestroy();// call the onDestroy method after finishing your operations
}
}

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