2014-04-03 55 views
2

活动类型是“固定标签+刷卡”。我需要从我的Listvew中的数据库sqlite中读取数据,它位于片段xml文件中(不在主要xml中)。 l使用我的旧代码的一些程序,没有用于创建列表视图的方法:不能读取列表视图中的sqlite数据库android

public void createList(){ 
    db = new DB(this); 
    db.open(); 
    String[] from = new String[] {DB.COLUMN_NAME, DB.COLUMN_TIME }; 
    int[] to = new int[] { R.id.tvTextName, R.id.tvText_time}; 
    scAdapter = new SimpleCursorAdapter(this, R.layout.item, null, from, to, 0); 
    lvData = (ListView) findViewById(R.id.lvData); 
    lvData.setAdapter(scAdapter); 
    getSupportLoaderManager().initLoader(0, null, this); 
} 

在简单的活动代码工作不错,但我不知道如何使用的代码片段活动。我尝试在主类中调用该方法,但该代码:

lvData = (ListView) findViewById(R.id.lvData); 
    lvData.setAdapter(scAdapter); 

我放入片段类。程序工作,但列表视图是空的。数据库不是空的。有代码的主要部分:

public class MainActivity extends FragmentActivity implements 
ActionBar.TabListener, LoaderCallbacks<Cursor> { 


    //*****ОСНОВНЫЕ ПЕРЕМЕННЫЕ***** 

    private static String TAG = "MainActivity"; 
    private static final int CM_DELETE_ID = 1; 
    private static final int RESET_STOPWATCH = 2; 
    static ListView lvData; 
    static DB db; 
    static SimpleCursorAdapter scAdapter; 
    static Context ctx; 
    static String[] from = new String[] {DB.COLUMN_NAME, DB.COLUMN_TIME }; 
    static int[] to = new int[] { R.id.tvTextName, R.id.tvText_time}; 

    SectionsPagerAdapter mSectionsPagerAdapter; 
    ViewPager mViewPager; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     // Set up the action bar. 
     final ActionBar actionBar = getActionBar(); 
     actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 
     mSectionsPagerAdapter = new SectionsPagerAdapter(
       getSupportFragmentManager()); 
     mViewPager = (ViewPager) findViewById(R.id.pager); 
     mViewPager.setAdapter(mSectionsPagerAdapter); 
     mViewPager 
     .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 
      @Override 
      public void onPageSelected(int position) { 
       actionBar.setSelectedNavigationItem(position); 
      } 
     }); 

     for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { 
      actionBar.addTab(actionBar.newTab() 
        .setText(mSectionsPagerAdapter.getPageTitle(i)) 
        .setTabListener(this)); 
     } 
     ctx = this; 
     createList(); 
    } 

    public void createList(){ 
     db = new DB(this); 
     db.open(); 
     scAdapter = new SimpleCursorAdapter(this, R.layout.item, null, from, to, 0);Log.d(TAG, "1"); 
     getSupportLoaderManager().initLoader(0, null, this); 
    } 

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

    @Override 
    public void onTabSelected(ActionBar.Tab tab, 
      FragmentTransaction fragmentTransaction) { 
     // When the given tab is selected, switch to the corresponding page in 
     // the ViewPager. 
     mViewPager.setCurrentItem(tab.getPosition()); 
    } 

    @Override 
    public void onTabUnselected(ActionBar.Tab tab, 
      FragmentTransaction fragmentTransaction) { 
    } 

    @Override 
    public void onTabReselected(ActionBar.Tab tab, 
      FragmentTransaction fragmentTransaction) { 
    } 

    /** 
    * A {@link FragmentPagerAdapter} that returns a fragment corresponding to 
    * one of the sections/tabs/pages. 
    */ 
    public class SectionsPagerAdapter extends FragmentPagerAdapter { 

     public SectionsPagerAdapter(FragmentManager fm) { 
      super(fm); 
     } 

     @Override 
     public Fragment getItem(int position) { 
      // getItem is called to instantiate the fragment for the given page. 
      // Return a DummySectionFragment (defined as a static inner class 
      // below) with the page number as its lone argument. 
      if(position == 0){ 
       Fragment fragment = new DummySectionFragment(); 
       Bundle args = new Bundle(); 
       args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1); 
       fragment.setArguments(args); 
       //getSupportLoaderManager().initLoader(0, null, this); 
       return fragment; 
      } 

      if (position == 1) 
      { 
       Fragment fragment2 = new DummySectionFragment2(); 
       Bundle args = new Bundle(); 
       args.putInt(DummySectionFragment2.ARG_SECTION_NUMBER, position + 2); 
       fragment2.setArguments(args); 
       return fragment2; 
      } 
      return null; 

     } 

     @Override 
     public int getCount() { 
      // Show 3 total pages. 
      return 2; 
     } 

     @Override 
     public CharSequence getPageTitle(int position) { 
      Locale l = Locale.getDefault(); 
      switch (position) { 
      case 0: 
       return getString(R.string.title_section1).toUpperCase(l); 
      case 1: 
       return getString(R.string.title_section2).toUpperCase(l); 
      } 
      return null; 
     } 

    } 
    public static class DummySectionFragment extends Fragment{ 
     public static final String ARG_SECTION_NUMBER = "section_number"; 
     public DummySectionFragment() { 
     } 

     static View v; 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.activity_tracker, 
        container, false); 
      v = inflater.inflate(R.layout.activity_tracker, container, false); 
      lvData = (ListView) v.findViewById(R.id.lvData);Log.d(TAG, "2"); 
      lvData.setAdapter(scAdapter);Log.d(TAG, "3"); 
      return rootView; 
     } 
    } 

    public static class DummySectionFragment2 extends Fragment { 
      //code page 2 
     } 
    } 

    //Класс по управлению БД 
    static class MyCursorLoader extends CursorLoader { 

     DB db; 

     public MyCursorLoader(Context context, DB db) { 
      super(context); 
      this.db = db; 
     } 

     @Override 
     public Cursor loadInBackground() { 
      Cursor cursor = db.getAllData(); 
      return cursor; 
     } 

    } 

    } 

} 
+0

请!有人可以帮我 – kolodach

回答

0

我已经安装的类似应用程序读取数据库细节到含有一个ListView的片段。我通过JSON解析完成了这一点。

在下面请看:

public static class EventFragment extends ListFragment { 

     ArrayList<HashMap<String, String>> eventsList; 
     private String url_all_events = "//url of the location of your database"; 

     //used a Progressbar to prompt the user that the data is downloading until it downloads. 
     private ProgressDialog pDialog; 

     JSONParser jParser = new JSONParser(); 

     // JSON Node names 
     private static final String CONNECTION_STATUS = "success"; 
     private static final String TABLE_EVENT = "Event"; 
     private static final String pid = "pid"; 
     private static final String COL_GROUP = "Group"; 
     private static final String COL_NAME = "Event_Name"; 
     private static final String COL_DESC = "Event_Desc"; 
     private static final String COL_DATE = "Event_Date"; 
     private static final String COL_TIME = "Event_Time"; 

     JSONArray Events = null; 

     public static final String ARG_SECTION_NUMBER = "section_number"; 

     public EventFragment() { 
     } 

     public void onStart() { 
      super.onStart(); 

      eventsList = new ArrayList<HashMap<String, String>>(); 
      new LoadAllEvents().execute(); 

      // selecting single ListView item 
      ListView lv = getListView(); 

      // Lauching the Event details screen on selecting a single event 
      lv.setOnItemClickListener(new OnItemClickListener() { 

       @Override 
       public void onItemClick(AdapterView<?> parent, View view, 
         int position, long id) { 
        // getting values from selected ListItem 
        String ID = ((TextView) view.findViewById(R.id.pid)) 
          .getText().toString(); 

        Intent intent = new Intent(view.getContext(), 
          EventDetails.class); 
        intent.putExtra(pid, ID); 
        view.getContext().startActivity(intent); 
       } 
      }); 
     } 

     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_events, 
        container, false); 

      return rootView; 
     } 

     class LoadAllEvents extends AsyncTask<String, String, String> { 

      /** 
      * Before starting background thread Show Progress Dialog 
      * */ 
      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
       pDialog = new ProgressDialog(getActivity()); 
       pDialog.setMessage("Just a moment..."); 
       pDialog.setIndeterminate(true); 
       pDialog.setCancelable(true); 
       pDialog.show(); 
      } 

      protected String doInBackground(String... args) { 
       // Building Parameters 
       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       // getting JSON string from URL 
       JSONObject json = jParser.makeHttpRequest(url_all_events, 
         "GET", params); 

       try { 
        // Checking for SUCCESS TAG 
        int success = json.getInt(CONNECTION_STATUS); 

        if (success == 1) { 
         // products found 
         // Getting Array of Products 
         Events = json.getJSONArray(TABLE_EVENT); 
         // looping through All Contacts 
         for (int i = 0; i < Events.length(); i++) { 
          JSONObject evt = Events.getJSONObject(i); 

          // Storing each json item in variable 
          id = evt.getString(pid); 
          group = evt.getString(COL_GROUP); 
          name = evt.getString(COL_NAME); 
          desc = evt.getString(COL_DESC); 
          date = evt.getString(COL_DATE); 
          time = evt.getString(COL_TIME); 

          // creating new HashMap 
          HashMap<String, String> map = new HashMap<String, String>(); 

          // adding each child node to HashMap key => value 
          map.put(pid, id); 
          map.put(COL_GROUP, group); 
          map.put(COL_NAME, name); 
          map.put(COL_DESC, desc); 
          map.put(COL_DATE, date); 
          map.put(COL_TIME, time); 

          // adding HashList to ArrayList 
          eventsList.add(map); 
         } 
        } else { 
         // Options are not available or server is down. 
         // Dismiss the loading dialog and display an alert 
         // onPostExecute 
         pDialog.dismiss(); 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

       return null; 
      } 

      protected void onPostExecute(String file_url) { 
       // dismiss the dialog after getting all products 
       pDialog.dismiss(); 
       // updating UI from Background Thread 
       getActivity().runOnUiThread(new Runnable() { 
        public void run() { 
         ListAdapter adapter = new SimpleAdapter(getActivity(), 
           eventsList, R.layout.list_item, new String[] { 
             pid, COL_GROUP, COL_NAME, COL_DATE, COL_TIME }, 
           new int[] { R.id.pid, R.id.group, R.id.name, R.id.header, 
             R.id.title2 }); 

         setListAdapter(adapter); 
        } 
       }); 

      } 

     } 
    } 

对于JSON解析器,我用下面的类:

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 

    } 

    // function get json from url 
    // by making HTTP POST or GET mehtod 
    public JSONObject makeHttpRequest(String url, String method, 
      List<NameValuePair> params) { 

     // Making HTTP request 
     try { 

      // check for request method 
      if (method == "POST") { 
       // request method is POST 
       // defaultHttpClient 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 

      } else if (method == "GET") { 
       // request method is GET 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
      } 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 

    } 
} 

最后,这是片段布局的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"> 
    <!-- Main ListView 
     Always give id value as list(@android:id/list) 
    --> 
    <ListView 
     android:id="@android:id/list" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"/> 

</LinearLayout> 

这里我使用了自定义列表视图,所以请注意,我实现它的方式可能有点复杂。

希望这会有所帮助:)

+0

如果它能帮助你,你能请upvote这个答案吗? –

+0

如果我的回答对你有帮助,你可以升高吗? –

相关问题