android-on导航抽屉项单击从数据库中获取数据并填充另一个列表

时间:2014-07-15 18:48:12

标签: java android listview navigation-drawer onitemclicklistener

我的应用程序包含一个导航抽屉,我使用其列表项作为菜单,通过单击帮助从数据库中检索数据并在主活动中填充我的列表视图... 我想根据抽屉列表的项目点击向数据库函数发送查询,并根据查询结果填充主活动中的另一个列表视图。

基本上我到目前为止尝试的是分配一个不同的字符串,根据项目点击进入String类型变量“query”,并将其作为参数传递给数据库的一个函数,该函数将其作为rawQuery处理并检索结果... 由于一些无法检测到的错误,它会抛出Null Pointer Exception ......

以下是MainActivity.java的代码

public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {

private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;

private Cursor c;
public MyDatabaseHandler dbOpen;
private String query; 

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


    mNavigationDrawerFragment = 
    (NavigationDrawFragment) 
     getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();


    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));


    dbOpen = new MyDatabaseHandler(this);
    c = dbOpen.getListContent(query);
    ListView lv = (ListView) findViewById(R.id.list);
    lv.setAdapter(new SimpleCursorAdapter(this,R.layout.topic_list_each_row,
    c,new String[]{MyDatabaseHandler.KEY_UTOPICNAME,MyDatabaseHandler.KEY_UNAME },
    new int[] {R.id.topicname,R.id.unitname} ,0));
    }

@Override
public void onNavigationDrawerItemSelected(int position) {

    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
            .commit();
}
//here where i have thought of passing string into query variable
public void onSectionAttached(int number) {
    switch (number) {
        case 1:
            query = "SELECT * FROM cosmtable ORDER BY utopicname";
             break;
             ...............
             ..............
                }}

public void restoreActionBar() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.main, menu);
        restoreActionBar();
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));}}}

activity_main文件是 -

<android.support.v4.widget.DrawerLayout   

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.pockettutsforcosm.MainActivity" >

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView 
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:dividerHeight="10dp">
</ListView>
</LinearLayout>
<fragment
    android:id="@+id/navigation_drawer"
    android:name="com.example.pockettutsforcosm.NavigationDrawerFragment"
    android:layout_width="@dimen/navigation_drawer_width"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    tools:layout="@layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>

请帮助我找到实现结果的方法.. 如果需要进一步的详细信息,请告知我们.. 谢谢

更新 我想到的一件事是我试图在错误的地方写入查询,即查询变量不应该在onAttach事件中赋值...

我改变了主要活动中的代码,如下所示 -

public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    //FragmentManager fragmentManager = getSupportFragmentManager();
    //fragmentManager.beginTransaction()
      //      .replace(R.id.container, PlaceholderFragment.newInstance(position))
        //    .commit();

    try
    {
        switch(position)
        {
        case 0:
            query = "SELECT * FROM cosmtable ORDER BY topic_name";
            c = dbOpen.getListContent(query);
            ListView lv = (ListView) findViewById(R.id.list);
            lv.setAdapter(new SimpleCursorAdapter(this,R.layout.topic_list_each_row,c,
            new String[]{MyDatabasehandler.KEY_UTOPICNAME,MyDatabaseHandler.KEY_UNAME},
            new int[] {R.id.topicname,R.id.unitname} ,0));
            break;
             .............................................

        }
    }

    catch (Exception e) {
        Log.e("error on fragment", "creating the mainScreen");
    }
    finally {

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
        .replace(R.id.container, PlaceholderFragment.newInstance(position + 1 ))
                .commit();}}

执行此操作后,首次启动应用程序时,不会显示从导航抽屉的第一个项目点击加载的内容.... 它只在单击项目时出现... 我希望它出现在应用程序启动...

我是否需要在我的数据库处理程序类中创建单独的方法来为每个switch case返回单独的查询结果?

1 个答案:

答案 0 :(得分:0)

基本上我所做的是创建了一个单独的函数,它可以相应地操纵查询字符串导航抽屉的每个元素的位置然后传递给数据库处理程序中的游标数据函数,然后返回查询结果到MainActivity中的简单游标适配器....

另一件事就是在启动应用程序时出现空白屏幕问题,我称之为操作第一个元素的数据库查询的相同函数...

这给了我想要的输出.. 如果还有另一个好的方法,那么我也愿意知道这种方法。 到现在为止,我会接受这个答案..