我点击时出错

时间:2013-06-11 08:36:02

标签: android

我有自定义SimpleCursorAdapter MySqlCursorAdapter。我希望在我的班级MySqlCursorAdapter中使用PageFragment,但是当我点击任意按钮时出现错误.CopyOfMainActivity活动

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;
    }

  }

日志

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>

我做错了什么?我如何理解错误出现在“破坏”活动

2 个答案:

答案 0 :(得分:1)

许多代码存在很多问题。没有阅读所有这些,所以这个答案并没有解决所有问题,但希望它可以帮助你在学习的道路上前进。 @ Houcine的调查结果也很有帮助,虽然他们没有直接回答你所看到的例外问题。

finish()中的

onDestroy()不正确。该活动已被销毁。删除它。

直接拨打onDestroy()是不正确的。删除电话。如果您想关闭活动,只需致电finish()

通常,当发生特定事件时,框架会调用onXxx()覆盖。你不应该自己打电话。

此外,在onCreate()中,您可能会在正确创建活动之前完成活动:

if (getIntent().getBooleanExtra("finish", false)) finish();
super.onCreate(savedInstanceState);

答案 1 :(得分:0)

onCreate()方法中,您遇到两个问题:

1-您正在创建活动之前完成活动。

Log.d(Tag, "copyofMaimActivity1...");
if (getIntent().getBooleanExtra("finish", false)) finish();
super.onCreate(savedInstanceState);

更正:您应该在super.onCreate()

之前执行任何操作之前调用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-您在将View布局设置为Content之前尝试找到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);
    }

更正:在通过ID(或其标记)检索视图的任何操作之前,您应该调用setContentView(int resId);

@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);

onDestroy()方法中,onFinish()的调用出现问题,您正在调用super.onDestroy(),这会导致活动失败,而您正在尝试调用{{1}方法(杀死已经被finish()调用破坏的活动。你的代码应该是这样的:

super.onDestroy()