简体   繁体   English

在带有片段的Lis​​tView中显示数据库中的数据

[英]Display Data from Database in ListView With Fragment

I am trying to display all the data from the second column of my database to my ListView inside a ScrollView . 我试图在ScrollView显示从数据库第二列到ListView所有数据。

I am using a fragment, but I'm having a problem using getSupportLoaderManager().initLoader(1, data, this); 我正在使用一个片段,但是在使用getSupportLoaderManager().initLoader(1, data, this);遇到问题 it sais " getSupportLoaderManager() is undefined method", so I create a new class inside this fragment just as an experiment, and the result is there is no error but when I execute it, there's nothing happening as well ie. 它说“ getSupportLoaderManager()是未定义的方法”,所以我就像在实验中一样在此片段内创建一个新类,结果没有错误,但是当我执行它时,也没有任何反应。 the expected data is not showing in my ListView. 预期的数据没有显示在我的ListView中。

Here is my layout: 这是我的布局:

main.xml main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_body"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:fillViewport="true"
    android:background="@drawable/b">

   <ListView
        android:id="@+id/lv_countries_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</ScrollView>

and the Main.Java 和Main.Java

public class Main extends Fragment {    
    public Main() {
    }

    Button btn;
    TextView tx;
    EditText InputSearch;
    ArrayAdapter<String> dataAdapter = null;
    View rootView;
    ScrollView mainBody;
    ListView mLVCountries;
    SimpleCursorAdapter mCursorAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.main, container, false);
        setHasOptionsMenu(true);
        getActivity().setTitle("Search");

        mLVCountries = (ListView)rootView.findViewById(R.id.lv_countries_main); 
        mainBody = (ScrollView)rootView.findViewById(R.id.main_body);
    return rootView;
}

public class MainMain extends FragmentActivity implements LoaderCallbacks<Cursor> {
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            mLVCountries.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent countryIntent = new Intent(getActivity().getApplicationContext(), CountryActivity.class);
                    // Creating a uri to fetch country details corresponding to selected listview item
                    Uri data = Uri.withAppendedPath(CountryContentProvider.CONTENT_URI, String.valueOf(id));
                    // Setting uri to the data on the intent
                    countryIntent.setData(data);
                    // Open the activity
                    startActivity(countryIntent);
                }
            });
            // Defining CursorAdapter for the ListView      
            mCursorAdapter = new SimpleCursorAdapter(getActivity().getBaseContext(),
                    android.R.layout.simple_list_item_1,
                    null,
                    new String[] { SearchManager.SUGGEST_COLUMN_TEXT_1},
                    new int[] { android.R.id.text1}, 0);
            // Setting the cursor adapter for the country listview
            mLVCountries.setAdapter(mCursorAdapter);
            // Getting the intent that invoked this activity
            Intent intent = getActivity().getIntent();      
            // If this activity is invoked by selecting an item from Suggestion of Search dialog or 
            // from listview of SearchActivity

            if(intent.getAction().equals(Intent.ACTION_VIEW)){ 
                Intent countryIntent = new Intent(getActivity(), CountryActivity.class);
                countryIntent.setData(intent.getData());
                startActivity(countryIntent);
                getActivity().finish();         
            }else if(intent.getAction().equals(Intent.ACTION_SEARCH)){ // If this activity is invoked, when user presses "Go" in the Keyboard of Search Dialog
                String query = intent.getStringExtra(SearchManager.QUERY);
                doSearch(query);
            }   
        }

        private void doSearch(String query){
            Bundle data = new Bundle();
            data.putString("query", query);
            // Invoking onCreateLoader() in non-ui thread
            getSupportLoaderManager().initLoader(1, data, this);        
        }


        /** This method is invoked by initLoader() */
        @Override
        public Loader<Cursor> onCreateLoader(int arg0, Bundle data) {
            Uri uri = CountryContentProvider.CONTENT_URI;       
            return new CursorLoader(getBaseContext(), uri, null, null , new String[]{data.getString("query")}, null);   
        }
        /** This method is executed in ui thread, after onCreateLoader() */
        @Override
        public void onLoadFinished(Loader<Cursor> arg0, Cursor c) { 
            mCursorAdapter.swapCursor(c);       
        }
        @Override
        public void onLoaderReset(Loader<Cursor> arg0) {

        }
    }
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
       // inflater.inflate.getMenuInflater();
       inflater.inflate(R.menu.main_search_view, menu); //Do not ADD this otherwise the searcView will be duplicate
       MenuItem menuItem = menu.findItem(R.id.search);
       SearchView searchView = (SearchView) menuItem.getActionView();
       searchView.setIconifiedByDefault(false);
       searchView.setQueryHint("Type a something...");

        int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
        View searchPlate = searchView.findViewById(searchPlateId);
        if (searchPlate!=null) {
            searchPlate.setBackgroundColor(Color.DKGRAY);
            int searchTextId = searchPlate.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
            TextView searchText = (TextView) searchPlate.findViewById(searchTextId);
            if (searchText!=null) {
                searchText.setTextColor(Color.WHITE);
                searchText.setHintTextColor(Color.WHITE);
            }
        }

     // Associate searchable configuration with the SearchView
        SearchManager searchManager =
               (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
        searchView =
                (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getActivity().getComponentName()));

        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar actions click
        switch (item.getItemId()) {
        case R.id.action_settings:
            return false;
        case R.id.search:
            return true;    
        default:
            break;
        }
        return false;
    }
}

First, you have to put the info in your database in a String [] 首先,您必须将信息放在数据库的String []中

Go over the columns first with the cursor to get the count 首先使用光标浏览列以获取计数

Set the String[] length like this, String [] values= new String [int count] 像这样设置String []的长度,String []的值= new String [int count]

Move over the cursor again with a for and insert the string of each column in each position 使用for再次移至光标上方,然后将每个列的字符串插入每个位置

When you have filled the info you need from the database, define ArrayAdapter ... Then setlistadapter 当您从数据库中填充了所需的信息后,请定义ArrayAdapter ...然后setlistadapter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM