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
}
}
Related
I made an app in android and it is working fine but when I shifted my app to my main app it start showing error from that point package name is same as that of my previous app then also this is the error that i am getting .I followed many question but cant able to find any solution .
FATAL EXCEPTION: main
Process: unnion.neelay.beatbox, PID: 12739
java.lang.RuntimeException: Unable to start activity ComponentInfo{unnion.neelay.beatbox/unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
at android.app.Activity.performCreate(Activity.java:6303)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
it is showing null point exception but it was working properly when not added to the main app.
the ringdroid select activity
public class RingdroidSelectActivity
extends ListActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
private SearchView mFilter;
private SimpleCursorAdapter mAdapter;
private boolean mWasGetContentIntent;
private boolean mShowAll;
private Cursor mExternalCursor;
// Result codes
private static final int EXT_STORAGE_PERMISSION_REQ_CODE = 2;
private static final int WRITE_EXTERNAL_STORAGE = 4;
private static final int READ_PHONE_STATE = 3;
private static final int WRITE_SETTINGS = 3;
private static final int CHANGE_CONFIGURATION = 1;
private static final int MODIFY_AUDIO_SETTINGS = 5;
private static final int INTERNET = 6;
private static final int REQUEST_CODE_EDIT = 1;
private static final int REQUEST_CODE_CHOOSE_CONTACT = 2;
// Context menu
private static final int CMD_EDIT = 4;
private static final int CMD_DELETE = 5;
private static final int CMD_SET_AS_DEFAULT = 6;
private static final int CMD_SET_AS_CONTACT = 7;
public RingdroidSelectActivity() {
}
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
checkReadStoragePermission();
mShowAll = false;
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
showFinalAlert(getResources().getText(R.string.sdcard_readonly));
return;
}
if (status.equals(Environment.MEDIA_SHARED)) {
showFinalAlert(getResources().getText(R.string.sdcard_shared));
return;
}
if (!status.equals(Environment.MEDIA_MOUNTED)) {
showFinalAlert(getResources().getText(R.string.no_sdcard));
return;
}
Intent intent = getIntent();
mWasGetContentIntent = intent.getAction().equals(
Intent.ACTION_GET_CONTENT);
// Inflate our UI from its XML layout description.
setContentView(R.layout.media_select);
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
getActionBar().setDisplayShowTitleEnabled(false);
try {
mAdapter = new SimpleCursorAdapter(
this,
// Use a template that displays a text view
R.layout.media_select_row,
null,
// Map from database columns...
new String[]{
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media._ID},
// To widget ids in the row layout...
new int[]{
R.id.row_artist,
R.id.row_title,
R.id.row_icon,
R.id.row_options_button},
0);
setListAdapter(mAdapter);
// Normal click - open the editor
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
startRingdroidEditor();
}
});
mExternalCursor = null;
getLoaderManager().initLoader(EXTERNAL_CURSOR_ID, null, this);
} catch (SecurityException e) {
// No permission to retrieve audio?
Log.e("Ringdroid", e.toString());
// TODO error 1
} catch (IllegalArgumentException e) {
// No permission to retrieve audio?
Log.e("Ringdroid", e.toString());
// TODO error 2
}
mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (view.getId() == R.id.row_options_button) {
// Get the arrow ImageView and set the onClickListener to open the context menu.
ImageView iv = (ImageView) view;
iv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openContextMenu(v);
}
});
return true;
} else if (view.getId() == R.id.row_icon) {
setSoundIconFromCursor((ImageView) view, cursor);
return true;
}
return false;
}
});
// Long-press opens a context menu
registerForContextMenu(getListView());
}
private void setSoundIconFromCursor(ImageView view, Cursor cursor) {
if (0 != cursor.getInt(cursor.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_MUSIC))) {
view.setImageResource(R.drawable.type_music);
((View) view.getParent()).setBackgroundColor(
getResources().getColor(R.color.type_bkgnd_music));
}
String filename = cursor.getString(cursor.getColumnIndexOrThrow(
MediaStore.Audio.Media.DATA));
}
/**
* Called with an Activity we started with an Intent returns.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent dataIntent) {
if (requestCode != REQUEST_CODE_EDIT) {
return;
}
if (resultCode != RESULT_OK) {
return;
}
setResult(RESULT_OK, dataIntent);
//finish(); // TODO(nfaralli): why would we want to quit the app here?
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.select_options, menu);
mFilter = (SearchView) menu.findItem(R.id.action_search_filter).getActionView();
if (mFilter != null) {
mFilter.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
refreshListView();
return true;
}
public boolean onQueryTextSubmit(String query) {
refreshListView();
return true;
}
});
}
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.action_record).setVisible(true);
// TODO(nfaralli): do we really need a "Show all audio" item now?
menu.findItem(R.id.action_show_all_audio).setVisible(true);
menu.findItem(R.id.action_show_all_audio).setEnabled(!mShowAll);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_record:
onRecord();
return true;
case R.id.action_show_all_audio:
mShowAll = true;
refreshListView();
return true;
default:
return false;
}
}
#Override
public void onCreateContextMenu(ContextMenu menu,
View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
Cursor c = mAdapter.getCursor();
String title = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
menu.setHeaderTitle(title);
menu.add(0, CMD_EDIT, 0, R.string.context_menu_edit);
menu.add(0, CMD_DELETE, 0, R.string.context_menu_delete);
// Add items to the context menu item based on file type
if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_RINGTONE))) {
menu.add(0, CMD_SET_AS_DEFAULT, 0, R.string.context_menu_default_ringtone);
menu.add(0, CMD_SET_AS_CONTACT, 0, R.string.context_menu_contact);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_NOTIFICATION))) {
menu.add(0, CMD_SET_AS_DEFAULT, 0, R.string.context_menu_default_notification);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CMD_EDIT:
startRingdroidEditor();
return true;
case CMD_DELETE:
confirmDelete();
return true;
case CMD_SET_AS_DEFAULT:
setAsDefaultRingtoneOrNotification();
return true;
case CMD_SET_AS_CONTACT:
return chooseContactForRingtone(item);
default:
return super.onContextItemSelected(item);
}
}
private void setAsDefaultRingtoneOrNotification() {
Cursor c = mAdapter.getCursor();
// If the item is a ringtone then set the default ringtone,
// otherwise it has to be a notification so set the default notification sound
if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_RINGTONE))) {
RingtoneManager.setActualDefaultRingtoneUri(
RingdroidSelectActivity.this,
RingtoneManager.TYPE_RINGTONE,
getUri());
Toast.makeText(
RingdroidSelectActivity.this,
R.string.default_ringtone_success_message,
Toast.LENGTH_SHORT)
.show();
} else {
RingtoneManager.setActualDefaultRingtoneUri(
RingdroidSelectActivity.this,
RingtoneManager.TYPE_NOTIFICATION,
getUri());
Toast.makeText(
RingdroidSelectActivity.this,
R.string.default_notification_success_message,
Toast.LENGTH_SHORT)
.show();
}
}
private int getUriIndex(Cursor c) {
int uriIndex;
String[] columnNames = {
MediaStore.Audio.Media.INTERNAL_CONTENT_URI.toString(),
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString()
};
for (String columnName : Arrays.asList(columnNames)) {
uriIndex = c.getColumnIndex(columnName);
if (uriIndex >= 0) {
return uriIndex;
}
// On some phones and/or Android versions, the column name includes the double quotes.
uriIndex = c.getColumnIndex("\"" + columnName + "\"");
if (uriIndex >= 0) {
return uriIndex;
}
}
return -1;
}
private Uri getUri() {
//Get the uri of the item that is in the row
Cursor c = mAdapter.getCursor();
int uriIndex = getUriIndex(c);
if (uriIndex == -1) {
return null;
}
String itemUri = c.getString(uriIndex) + "/" +
c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
return (Uri.parse(itemUri));
}
private boolean chooseContactForRingtone(MenuItem item) {
try {
//Go to the choose contact activity
Intent intent = new Intent(Intent.ACTION_EDIT, getUri());
intent.setClassName(
"unnion.neelay.beatbox.ringdroid",
"unnion.neelay.beatbox.ringdroid.ChooseContactActivity");
startActivityForResult(intent, REQUEST_CODE_CHOOSE_CONTACT);
} catch (Exception e) {
Log.e("Ringdroid", "Couldn't open Choose Contact window");
}
return true;
}
private void confirmDelete() {
// See if the selected list item was created by Ringdroid to
// determine which alert message to show
Cursor c = mAdapter.getCursor();
String artist = c.getString(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.ARTIST));
CharSequence ringdroidArtist =
getResources().getText(R.string.artist_name);
CharSequence message;
if (artist.equals(ringdroidArtist)) {
message = getResources().getText(
R.string.confirm_delete_ringdroid);
} else {
message = getResources().getText(
R.string.confirm_delete_non_ringdroid);
}
CharSequence title;
if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_RINGTONE))) {
title = getResources().getText(R.string.delete_ringtone);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_ALARM))) {
title = getResources().getText(R.string.delete_alarm);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_NOTIFICATION))) {
title = getResources().getText(R.string.delete_notification);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_MUSIC))) {
title = getResources().getText(R.string.delete_music);
} else {
title = getResources().getText(R.string.delete_audio);
}
new AlertDialog.Builder(RingdroidSelectActivity.this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(
R.string.delete_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
onDelete();
}
})
.setNegativeButton(
R.string.delete_cancel_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
})
.setCancelable(true)
.show();
}
private void onDelete() {
Cursor c = mAdapter.getCursor();
int dataIndex = c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String filename = c.getString(dataIndex);
int uriIndex = getUriIndex(c);
if (uriIndex == -1) {
showFinalAlert(getResources().getText(R.string.delete_failed));
return;
}
if (!new File(filename).delete()) {
showFinalAlert(getResources().getText(R.string.delete_failed));
}
String itemUri = c.getString(uriIndex) + "/" +
c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
getContentResolver().delete(Uri.parse(itemUri), null, null);
}
private void showFinalAlert(CharSequence message) {
new AlertDialog.Builder(RingdroidSelectActivity.this)
.setTitle(getResources().getText(R.string.alert_title_failure))
.setMessage(message)
.setPositiveButton(
R.string.alert_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
finish();
}
})
.setCancelable(false)
.show();
}
private void onRecord() {
try {
Intent intent = new Intent(Intent.ACTION_EDIT, Uri.parse("record"));
intent.putExtra("was_get_content_intent", mWasGetContentIntent);
intent.setClassName("unnion.neelay.mediaplayer.ringdroid", "unnion.neelay.mediaplayer.ringdroid.RingdroidEditActivity");
startActivityForResult(intent, REQUEST_CODE_EDIT);
} catch (Exception e) {
Log.e("Ringdroid", "Couldn't start editor");
}
}
private void startRingdroidEditor() {
Cursor c = mAdapter.getCursor();
int dataIndex = c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String filename = c.getString(dataIndex);
try {
Intent intent = new Intent(Intent.ACTION_EDIT, Uri.parse(filename));
intent.putExtra("was_get_content_intent", mWasGetContentIntent);
intent.setClassName("unnion.neelay.mediaplayer.ringdroid", "unnion.neelay.mediaplayer.ringdroid.RingdroidEditActivity");
startActivityForResult(intent, REQUEST_CODE_EDIT);
} catch (Exception e) {
Log.e("Ringdroid", "Couldn't start editor");
}
}
private void refreshListView() {
mExternalCursor = null;
Bundle args = new Bundle();
args.putString("filter", mFilter.getQuery().toString());
getLoaderManager().restartLoader(EXTERNAL_CURSOR_ID, args, this);
}
private static final String[] EXTERNAL_COLUMNS = new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.IS_RINGTONE,
MediaStore.Audio.Media.IS_ALARM,
MediaStore.Audio.Media.IS_NOTIFICATION,
MediaStore.Audio.Media.IS_MUSIC,
"\"" + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "\""
};
private static final int EXTERNAL_CURSOR_ID = 1;
/* Implementation of LoaderCallbacks.onCreateLoader */
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
ArrayList<String> selectionArgsList = new ArrayList<String>();
String selection;
Uri baseUri;
String[] projection;
switch (id) {
case EXTERNAL_CURSOR_ID:
baseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
projection = EXTERNAL_COLUMNS;
break;
default:
return null;
}
if (mShowAll) {
selection = "(_DATA LIKE ?)";
selectionArgsList.add("%");
} else {
selection = "(";
for (String extension : SoundFile.getSupportedExtensions()) {
selectionArgsList.add("%." + extension);
if (selection.length() > 1) {
selection += " OR ";
}
selection += "(_DATA LIKE ?)";
}
selection += ")";
selection = "(" + selection + ") AND (_DATA NOT LIKE ?)";
selectionArgsList.add("%espeak-data/scratch%");
}
String filter = args != null ? args.getString("filter") : null;
if (filter != null && filter.length() > 0) {
filter = "%" + filter + "%";
selection =
"(" + selection + " AND " +
"((TITLE LIKE ?) OR (ARTIST LIKE ?) OR (ALBUM LIKE ?)))";
selectionArgsList.add(filter);
selectionArgsList.add(filter);
selectionArgsList.add(filter);
}
String[] selectionArgs =
selectionArgsList.toArray(new String[selectionArgsList.size()]);
return new CursorLoader(
this,
baseUri,
projection,
selection,
selectionArgs,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER
);
}
/* Implementation of LoaderCallbacks.onLoadFinished */
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case EXTERNAL_CURSOR_ID:
mExternalCursor = data;
break;
default:
return;
}
// TODO: should I use a mutex/synchronized block here?
if (mExternalCursor != null) {
Cursor mergeCursor = new MergeCursor(new Cursor[]{mExternalCursor});
mAdapter.swapCursor(mergeCursor);
}
}
/* Implementation of LoaderCallbacks.onLoaderReset */
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
#TargetApi(Build.VERSION_CODES.M)
private void checkReadStoragePermission() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
ActivityCompat.requestPermissions(RingdroidSelectActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, EXT_STORAGE_PERMISSION_REQ_CODE);
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
onPermissionsNotGranted();
}
dialog.dismiss();
finish();
startActivity(getIntent());
}
};
new android.support.v7.app.AlertDialog.Builder(this)
.setTitle(R.string.permissions_title)
.setMessage(R.string.read_ext_permissions_message)
.setPositiveButton(R.string.btn_continue, onClickListener)
.setNegativeButton(R.string.btn_cancel, onClickListener)
.setCancelable(false)
.show();
return;
}
ActivityCompat.requestPermissions(RingdroidSelectActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE}, EXT_STORAGE_PERMISSION_REQ_CODE);
return;
}
}
private void onPermissionsNotGranted() {
Toast.makeText(this, R.string.toast_permissions_not_granted, Toast.LENGTH_SHORT).show();
Log.v("tom", "JERRY");
}
}
Looking at your callstack it should really help you narrow down your problem.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
at android.app.Activity.performCreate(Activity.java:6303)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
For example, in your callstack, you first have the exception that's being thrown, NullPointerException, and it's telling you what is causing it.
java.lang.String.equals(java.lang.Object)
So, you have a String that you're attempting to call .equals on, but the String is null.
Now, a bit lower, it shows the line number of where this issue is happening.
unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
So, you're calling .equals within your RingdroidSelectActivity's onCreate at line 123.
However, perhaps your code has changed since you posted your error, there isn't a .equals around that line, but I'm thinking it may be your getExternalStroage().
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
showFinalAlert(getResources().getText(R.string.sdcard_readonly));
return;
}
Perhaps you don't have the permission for this or something else. Add in some checks for null, and that will help you debug the problem.
Hopefully that helps!
Edit:
The issue was this
so the answer is
mWasGetContentIntent = Intent.ACTION_GET_CONTENT.equals(intent.getAction());
Hi i'm still trying to make my wavPlayer. My apps has listitem that contain wav file. When I click a file, it should be played but it didn't. I've tried some way on OnListItemClick() to make it work (I marked it with double slash), but it still error. Most of error are nullpointer. Anybody can help me?
here's my code and log cat
public class PlayercobaActivity extends ListActivity implements View.OnClickListener {
private MediaCursorAdapter mediaAdapter = null;
PlayAudio playTask;
Button startRecordingButton, stopRecordingButton, startPlaybackButton,
stopPlaybackButton;
boolean isPlaying = false;
int frequency = 11025;
int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
//File item ;
String item;
// File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Datarekaman/recording5.wav");
//Cursor acursor;
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playercoba);
startPlaybackButton = (Button) this .findViewById(R.id.StartPlaybackButton);
stopPlaybackButton = (Button) this.findViewById(R.id.StopPlaybackButton);
startPlaybackButton.setOnClickListener(this);
stopPlaybackButton.setOnClickListener(this);
startPlaybackButton.setEnabled(true);
stopPlaybackButton.setEnabled(false);
ContentResolver cr = getContentResolver();
Uri uri = MediaStore.Files.getContentUri("external");
String[] projection = null;
String sortOrder = null; // unordered
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("wav");
String[] selectionArgsPdf = new String[]{ mimeType };
Cursor cursor = cr.query(uri, projection , selectionMimeType, selectionArgsPdf, sortOrder );
if(null != cursor)
{
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem, cursor);
setListAdapter(mediaAdapter);
}
}
//#Override
public void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
//String name = cursor.getString(cursor. getColumnIndex(MediaStore. MediaColumns.DISPLAY_NAME));
//item =(String) list.getItemAtPosition(position);
//File item = new File(name);
//item = new File();
//item = (String) view.getTag();
//item = (String) getListAdapter().getItem(position);
item = cursor.getString(cursor. getColumnIndex(MediaStore. MediaColumns.DATA));
//playTask = new PlayAudio();
//playTask.execute();
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}
public void onClick(View v) {
if (v == startPlaybackButton) {
play();
} else if (v == stopPlaybackButton) {
stopPlaying();
}
}
public void play() {
startPlaybackButton.setEnabled(false);
playTask = new PlayAudio();
playTask.execute();
stopPlaybackButton.setEnabled(true);
}
public void stopPlaying() {
isPlaying = false;
stopPlaybackButton.setEnabled(false);
startPlaybackButton.setEnabled(true);
}
private class PlayAudio extends AsyncTask<Void, Integer, Void> {
#Override
protected Void doInBackground(Void... params) {
isPlaying = true;
int bufferSize = AudioTrack.getMinBufferSize(frequency,
channelConfiguration, audioEncoding);
short[] audiodata = new short[bufferSize/4];
try {
DataInputStream dis = new DataInputStream(
new BufferedInputStream(new FileInputStream(item)));
AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC, frequency,
channelConfiguration, audioEncoding, bufferSize,
AudioTrack.MODE_STREAM);
audioTrack.play();
while (isPlaying && dis.available() > 0) {
int i = 0;
while (dis.available() > 0 && i < audiodata.length) {
audiodata[i] = dis.readShort();
i++;
}
audioTrack.write(audiodata, 0, audiodata.length);
}
dis.close();
startPlaybackButton.setEnabled(false);
stopPlaybackButton.setEnabled(true);
} catch (Throwable t) {
Log.e("AudioTrack", "Playback Failed");
}
return null;
}
protected void onPostExecute(Void result) {
startPlaybackButton.setEnabled(true);
stopPlaybackButton.setEnabled(false);
}
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[] { MediaStore.MediaColumns.DISPLAY_NAME},
new int[] { R.id.displayname});
}
}
}
LogCat
05-19 23:01:17.015 13752-13752/com.example.agita.playercoba E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.agita.playercoba.PlayercobaActivity.onListItemClick(PlayercobaActivity.java:93)
at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
at android.widget.AdapterView.performItemClick(AdapterView.java:301)
at android.widget.AbsListView.performItemClick(AbsListView.java:1287)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3078)
at android.widget.AbsListView$1.run(AbsListView.java:4159)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4947)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
if you are extending CursorAdapter, you can get the Cursor at position through the first argument of onListItemClick
Cursor cursor = (Cursor) list.getItemAtPosition(position);
item = cursor.getString(cursor. getColumnIndex(MediaStore. MediaColumns.DATA));
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
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
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()
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()