1

我有我的自定义SimpleCursorAdapterMySqlCursorAdapter。我想 MySqlCursorAdapter在我的课堂上使用,PageFragment但是我有一个错误。

寻呼机活动

    public class Pager extends FragmentActivity {

    SQLiteDatabase db;
    Cursor c;
    ContentValues cv;


     static final String Tag = "States";
     static final int PAGE_COUNT = 4;
     ViewPager pager;
     PagerAdapter pagerAdapter;
     LinearLayout L_view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pager);

        //мой блок получаю курсор
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String id_for_listtsk_today = sdf.format(new Date());
        ContentValues cv = new ContentValues();
        DBHelper dbHelper = new DBHelper(this);     
        final SQLiteDatabase db = dbHelper.getWritableDatabase();

        try {
            c=dbHelper.getCursor(id_for_listtsk_today);
        } catch (SQLException sqle) {
            Log.d(Tag, "неудача");
            throw sqle;

        }
        //String[] arr_date = logCursor(c);


       c.close();
       db.close();


        pager = (ViewPager) findViewById(R.id.pager);
        pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
        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) {
          }
        });


    }

    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }*/

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

      }

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

    }

}

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


}

MySQLCcursorAdapter.java

  public class MySqlCursorAdapter extends SimpleCursorAdapter implements OnClickListener {
final String Tag="States";
private Context context;

private DBHelper dbHelper;
private Cursor currentCursor;
TextView txtTitle;
TextView txtTitle1;
final String needsAction="completed";
public MySqlCursorAdapter(Context context, int layout, Cursor c,
        String[] from, int[] to, DBHelper dbHelper) {

    super(context, layout, c, from, to);
    //Log.d(Tag, "трассировка1" );
    this.currentCursor = c;
    this.context = context;
    this.dbHelper = dbHelper;
    //Log.d(Tag, "MySqlCursorAdapter()");
    Integer b = c.getCount();
    //Log.d(Tag, "b="+b);
}

public View getView(int pos, View inView, ViewGroup parent) {
    Log.d(Tag, "getView() + posss=" + pos);
    View v = inView;
    if (v == null) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.my_list_item, null);
    }

    this.currentCursor.moveToPosition(pos);

    CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);

    cBox.setTag(Integer.parseInt(this.currentCursor
            .getString(this.currentCursor
                    .getColumnIndex(DBHelper.COLUMN_ID))));
    //Log.d(Tag, "tag="+cBox.getTag().toString());
    if (this.currentCursor.getString(this.currentCursor
            .getColumnIndex(DBHelper.COLUMN_STATUS)) != null
            &&  String.valueOf(this.currentCursor
                    .getString(this.currentCursor
                            .getColumnIndex(DBHelper.COLUMN_STATUS))).equals(needsAction)) {
        cBox.setChecked(true);
    } else {
        cBox.setChecked(false);
    }
    cBox.setOnClickListener(this);

    txtTitle = (TextView) v.findViewById(R.id.txtTitle);
    txtTitle1 = (TextView) v.findViewById(R.id.textData1);
    txtTitle.setText(this.currentCursor.getString(this.currentCursor
            .getColumnIndex(DBHelper.COLUMN_TIME))+" , "+this.currentCursor.getString(this.currentCursor
                    .getColumnIndex(DBHelper.COLUMN_NAME)));
    txtTitle1.setText(this.currentCursor.getString(this.currentCursor
            .getColumnIndex(DBHelper.COLUMN_TASK)));
    if (cBox.isChecked())
    {
        //Log.d(Tag, " pos=" + pos);
        txtTitle.setPaintFlags(txtTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);    
        txtTitle1.setPaintFlags(txtTitle1.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
    }
    else
    {
        //Log.d(Tag, "!pos=" + pos);
        txtTitle.setPaintFlags(txtTitle.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);    
        txtTitle1.setPaintFlags(txtTitle1.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
        // txtTitle1.setSelected(true);
    }


    return (v);
}

public void ClearSelections() {
    //Log.d(Tag, "ClearSelections()");
    this.dbHelper.clearSelections();
    this.currentCursor.requery();

}

@Override
public void onClick(View v) {
    Log.d(Tag, "onClick(View v) в адаптере");
    if(dbHelper.dbSqlite==null) {
        //Log.d(Tag, "00000000000");
        SQLiteDatabase db = dbHelper.getWritableDatabase(); 
        //Log.d(Tag, "onClick");
        CheckBox cBox = (CheckBox) v;
        Integer _id = (Integer) cBox.getTag();
        //Integer _id = 4;
        //Log.d(Tag, "Integer _id="+_id.toString());
        ContentValues values = new ContentValues();
        values.put(" status", cBox.isChecked() ? "completed" : "needsAction");
        try {
            db.update("mytable", values, "_id = ?", new String[] { Integer.toString(_id) });
        } catch (SQLException sqle) {
            //  Log.d(Tag, "неудача");
            throw sqle;

        }
    }



}}

日志

06-10 09:23:52.437: D/States(5342): MainActivity: onDestroy()
06-10 09:23:52.460: D/States(5342): запустили службу ServiceUpdate
06-10 09:23:52.812: D/States(5605): onStartCommand
06-10 09:23:52.828: D/States(5605): onCreate
06-10 09:23:52.843: D/States(5605): Service onDestroy(). Stop AlarmManager at 2013-06-10 09:23:52.834
06-10 09:23:52.843: V/com.example.ok1.ServiceUpdate(5605): AlarmManger started at 2013-06-10 09:23:52.847
06-10 09:23:52.953: D/States(5342): getCursor() получаем курсор с базы
06-10 09:23:52.960: D/States(5342): getCursor() получили курсор с базы
06-10 09:23:53.031: D/States(5342): onCreateView1
06-10 09:23:53.078: D/dalvikvm(5342): GC_EXTERNAL_ALLOC freed 236K, 47% free 3103K/5767K, external 973K/1036K, paused 42ms
06-10 09:23:53.125: D/States(5342): onCreateView2
06-10 09:23:53.125: D/States(5342): onCreateView3
06-10 09:23:53.125: D/States(5342): switch (pageNumber)1
06-10 09:23:53.125: D/States(5342): onCreateView4
06-10 09:23:53.148: D/States(5342): onCreateView5
06-10 09:23:53.148: D/States(5342): getCursor() получаем курсор с базы
06-10 09:23:53.164: D/States(5342): getCursor() получили курсор с базы
06-10 09:23:53.164: D/States(5342): мы в курсоре
06-10 09:23:53.164: D/States(5342): onCreateView6
06-10 09:23:53.171: D/States(5342): onCreateView7
06-10 09:24:29.335: D/AndroidRuntime(5342): Shutting down VM
06-10 09:24:29.335: W/dalvikvm(5342): threadid=1: thread exiting with uncaught exception (group=0x40018578)
06-10 09:24:29.398: E/AndroidRuntime(5342): FATAL EXCEPTION: main
06-10 09:24:29.398: E/AndroidRuntime(5342): java.lang.NullPointerException
06-10 09:24:29.398: E/AndroidRuntime(5342):     at com.example.ok1.PageFragment.onCreateView(PageFragment.java:191)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1064)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.view.View.measure(View.java:8313)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:581)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:365)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.view.View.measure(View.java:8313)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.view.View.measure(View.java:8313)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.view.View.measure(View.java:8313)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.view.View.measure(View.java:8313)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.view.ViewRoot.performTraversals(ViewRoot.java:847)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1867)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at     android.os.Looper.loop(Looper.java:130)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at android.app.ActivityThread.main(ActivityThread.java:3687)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at java.lang.reflect.Method.invokeNative(Native Method)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at java.lang.reflect.Method.invoke(Method.java:507)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
06-10 09:24:29.398: E/AndroidRuntime(5342):     at dalvik.system.NativeStart.main(Native Method)
06-10 09:24:32.070: W/jdwp(5342): Debugger is telling the VM to exit with code=1

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>

寻呼机.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>

什么我不正确?

4

1 回答 1

1

您正在搜索您的 ListView

lvMain_today = (ListView) view.findViewById(R.id.list);

但在activity_page_fragment.xmlid 里面是android:id="@+id/lvMain".

因此,访问您的 ListView 会引发 NPElvMain_today.setAdapter(adapter);

请将布局 xml 中的 id 更改为R.id.list

也许本教程可以帮助您理解堆栈跟踪。

于 2013-06-10T07:47:17.937 回答