在主流程详细数据显示 [英] Show data in Master detail flow

查看:100
本文介绍了在主流程详细数据显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Eclipse上的主从流运行一个新的项目后,它显示的虚拟物品。

我想从的SQLite

更换的数据,这些虚拟物品

调用 DBAdapter 的方法(安培;与光标的帮助下)之后,我能够在日志打印值

我如何显示存储在的ArrayList&LT上的数据不知道; GetterSetter> 来掌握详细流程

请告诉我应该修改哪些东西在其中的类,或者我应该如何code?

更新

DBAdapter.java

 公共类DBAdapter扩展SQLiteOpenHelper
{
静态字符串名称=superstition.sqlite;
静态字符串路径=;
公共静态的ArrayList< GS>一个;
静态SQLiteDatabase SDB;@覆盖
公共无效的onCreate(SQLiteDatabase DB)
{
    // TODO自动生成方法存根
}@覆盖
公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页)
{
    // TODO自动生成方法存根
}私人DBAdapter(上下文V)
{
    超级(ⅴ,名称,无效,1);
    PATH =/数据/数据​​/+ v.getApplicationContext()getPackageName()+/数据库。
}公共布尔checkDatabase()
{
    SQLiteDatabase DB = NULL;
    尝试
    {
        DB = SQLiteDatabase.openDatabase(路径+/+名称,空,SQLiteDatabase.OPEN_READONLY);
    }赶上(例外五)
    {
        e.printStackTrace();
    }
    如果(DB == NULL)
    {
        返回false;
    }
    其他
    {
        db.close();
        返回true;
    }
}公共静态同步DBAdapter getDBAdapter(上下文V)
{
    返回(新DBAdapter(ⅴ));
}公共无效的CreateDatabase(上下文V)
{
    this.getReadableDatabase();
    尝试
    {
        InputStream的myInput = v.getAssets()开(名称)。
        //路径刚刚创建的空分贝
    字符串outFileName =路径+/+名;
        //打开空分贝的输出流
    的OutputStream myOutput =新的FileOutputStream(outFileName);
        //传递从inputfile中字节到OUTPUTFILE
    字节[]缓冲区=新的字节[1024];
    INT长;
    而((长度= myInput.read(缓冲液))大于0)
    {
        myOutput.write(缓冲液,0,长度);
    }
        //关闭流
    myOutput.flush();
    myOutput.close();
    myInput.close();    }赶上(IOException异常E)
    {
        的System.out.println(E);
    }
}公共无效的openDatabase()
{
    尝试
    {
        SDB = SQLiteDatabase.openDatabase(路径+/+姓名,空,
                SQLiteDatabase.OPEN_READWRITE);
    }赶上(例外五)
    {
        的System.out.println(E);
    }
}公众的ArrayList< GS>的getData()
{
    游标c1 = sdb.rawQuery(SELECT * FROM数据,NULL);
    一个=新的ArrayList< GS>();
    而(c1.moveToNext())
    {
        GS GS =新GS();        gs.setItem(c1.getString(1));
        gs.setDesc(c1.getString(2));
        Log.v(ID,gs.item +);        a.add(GS);
    }
    返回;
}
}

GS.java //的getter setter方法​​类

 公共类GS {
串项,递减;
公共字符串的getItem(){
归还物品;
}公共无效setItem(字符串项){
this.item =项目;
}公共字符串getDesc(){
返回说明;
}公共无效setDesc(字符串DESC){
this.desc =说明;
}
}

ItemListActivity.java

 公共类ItemListActivity扩展FragmentActivity工具
    ItemListFragment.Callbacks {/ **
 *无论是否活动有两种窗格模式,即在平板电脑上运行
 *设备。
 * /
公共DummyContent直流电;
私人布尔mTwoPane;
公众的ArrayList< GS> Q =新的ArrayList< GS>();
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_item_list);    如果(findViewById(R.id.item_detail_container)!= NULL){
        //细节容器视图将只有present在
        //大屏幕布局(RES /价值观大
        // RES /价值观sw600dp)。如果这观点是present,那么
        //活动应在两个窗格模式。
        mTwoPane = TRUE;        //在双窗格模式,列表中的项目应给予
        //触摸时激活状态。
        ((ItemListFragment)getSupportFragmentManager()。findFragmentById(
                R.id.item_list))setActivateOnItemClick(真)。
    }    DBAdapter分贝= DBAdapter.getDBAdapter(getApplicationContext());
    如果(!db.checkDatabase())
    {
        db.createDatabase(getApplicationContext());
    }
    db.openDatabase();
    Q = db.getData();
    DC =新DummyContent();
    // TODO:如果暴露深层链接到您的应用程序,在这里处理意图。
}/ **
 *回调从{@link ItemListFragment.Callbacks}方法说明
 *具有指定ID的项目被选中。
 * /
@覆盖
公共无效onItemSelected(字符串ID){
    如果(mTwoPane){
        //在双窗格模式,显示出本次活动的详细视图通过
        //添加或更换使用的细节片段
        //片段交易。
        捆绑参数=新包();
        arguments.putString(ItemDetailFragment.ARG_ITEM_ID,身份证);
        ItemDetailFragment片段=新ItemDetailFragment();
        fragment.setArguments(参数);
        getSupportFragmentManager()调用BeginTransaction()
                .replace(R.id.item_detail_container,片段).commit();    }其他{
        //在单窗格模式,只需启动该活动的细节
        //所选项目的ID。
        意图detailIntent =新意图(这一点,ItemDetailActivity.class);
        detailIntent.putExtra(ItemDetailFragment.ARG_ITEM_ID,身份证);
        startActivity(detailIntent);
    }
}
}

DummyContent.java //我认为,在这种静态块被修改

 公共类DummyContent {
静态INT I = 0;
/ **
 *样品(虚拟)项目的数组。
 * /
公共静态列表< D​​ummyItem> ITEMS =新的ArrayList< D​​ummyItem>();/ **
 *地图的样本(虚拟)的项目,由ID。
 * /
公共静态地图<弦乐,DummyItem> ITEM_MAP =新的HashMap<弦乐,DummyItem>();静态{    对于(i = 0; I< 182;我++)
    的addItem(新DummyItem(+ I项目+ i)段);}私有静态无效的addItem(DummyItem项){
    ITEMS.add(项目);
    ITEM_MAP.put(item.id,项目);
}/ **
 *重新$ P $ A虚拟物品psenting一块内容。
 * /
公共静态类DummyItem {
    公共字符串ID;
    公共字符串的内容;    公共DummyItem(ID字符串,字符串的内容){
        this.id = ID;
        this.content =内容;
    }    @覆盖
    公共字符串的toString(){
        返回的内容;
    }
}
}

ItemDetailActivity.java //一样Eclipse生成

 公共类ItemDetailActivity扩展FragmentActivity {@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_item_detail);    //显示操作栏中的向上按钮。
    getActionBar()setDisplayHomeAsUpEnabled(真)。    // savedInstanceState非空时,有碎片状态
    //从本次活动的previous配置保存
    //(例如从纵向旋转屏幕为横向时)。
    //在这种情况下,该片段将被自动重新添加
    //它的容器,所以我们并不需要手动添加。
    //欲了解更多信息,请参阅碎片API指南在:
    //
    // http://developer.android.com/guide/components/fragments.html
    //
    如果(savedInstanceState == NULL){
        //创建细节片段并将其添加到活动
        使用片段交易//。
        捆绑参数=新包();
        arguments.putString(ItemDetailFragment.ARG_ITEM_ID,getIntent()
                .getStringExtra(ItemDetailFragment.ARG_ITEM_ID));
        ItemDetailFragment片段=新ItemDetailFragment();
        fragment.setArguments(参数);
        getSupportFragmentManager()调用BeginTransaction()
                。新增(R.id.item_detail_container,片段).commit();
    }
}@覆盖
公共布尔onOptionsItemSelected(菜单项项){
    INT ID = item.getItemId();
    如果(ID == android.R.id.home){
        //这个ID重新presents主页或向上按钮。在这种情况下
        //活动,向上按钮显示。使用NavUtils允许用户
        //浏览了在应用结构中的一个级别。对于
        //更多详细信息,请参见Android设计的导航模式:
        //
        // http://developer.android.com/design/patterns/navigation.html#up-vs-back
        //
        NavUtils.navigateUpTo(这一点,
                新的意图(这一点,ItemListActivity.class));
        返回true;
    }
    返回super.onOptionsItemSelected(项目);
}
}

ItemDetailFragment.java //一样Eclipse生成

 公共类ItemDetailFragment扩展片段{
/ **
 *片段参数重新presenting项ID,该片段
 *重新presents。
 * /
公共静态最后弦乐ARG_ITEM_ID =ITEM_ID;/ **
 *虚设内容,此片段是presenting。
 * /
私人DummyContent.DummyItem MITEM;/ **
 *必须填写空构造函数片段经理来实例化
 *片段(例如在屏幕方向变化)。
 * /
公共ItemDetailFragment(){
}@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);    如果(getArguments()。的containsKey(ARG_ITEM_ID)){
        //加载的片段指定的虚拟内容
        //参数。在真实的场景中,使用Loader
        //从内容提供商加载内容。
        MITEM = DummyContent.ITEM_MAP.get(getArguments()的getString(
                ARG_ITEM_ID));
    }
}@覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
        捆绑savedInstanceState){
    查看rootView = inflater.inflate(R.layout.fragment_item_detail,
            集装箱,FALSE);    //显示虚拟内容作为一个TextView文本。
    如果(MITEM!= NULL){
        ((的TextView)rootView.findViewById(R.id.item_detail))
                .setText(mItem.content);
    }    返回rootView;
}
}

ItemListFragment.java //一样Eclipse生成

 公共类ItemListFragment扩展ListFragment {/ **
 *序列化(保存实例状态)软件包密钥再presenting的
 *激活项目的位置。只有用在平板电脑上。
 * /
私有静态最后弦乐STATE_ACTIVATED_POSITION =activated_position;/ **
 *片段的当前回调对象,这是通知列表项
 *点击。
 * /
私人回调mCallbacks = sDummyCallbacks;/ **
 *当前激活的项目的位置。只有用在平板电脑上。
 * /
私人INT mActivatedPosition = ListView.INVALID_POSITION;/ **
 *含有该片段的所有活动的回调接口必须
 * 实行。此机制允许被通知项的活动
 *选择。
 * /
公共接口回调{
    / **
     *回调时,已经选择了一个项目的。
     * /
    公共无效onItemSelected(字符串ID);
}/ **
 *一个虚拟执行{@link回调}界面,做的
 * 没有。用于只有当该片段没有连接到的活性。
 * /
私有静态回调sDummyCallbacks =新的回调(){
    @覆盖
    公共无效onItemSelected(字符串ID){
    }
};/ **
 *必须填写空构造函数片段经理来实例化
 *片段(例如在屏幕方向变化)。
 * /
公共ItemListFragment(){
}@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);    // TODO:一个真正的名单适配器更换。
    setListAdapter(新ArrayAdapter&所述; DummyContent.DummyItem>(getActivity(),
            android.R.layout.simple_list_item_activated_1,
            android.R.id.text1,DummyContent.ITEMS));
}@覆盖
公共无效onViewCreated(查看视图,捆绑savedInstanceState){
    super.onViewCreated(查看,savedInstanceState);    //恢复previously连载激活项目的位置。
    如果(savedInstanceState!= NULL
            &功放;&安培; savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)){
        setActivatedPosition(savedInstanceState
                .getInt(STATE_ACTIVATED_POSITION));
    }
}@覆盖
公共无效onAttach(活动活动){
    super.onAttach(活动);    //包含此片段必须实现回调活动。
    如果(!(的instanceof回调活性)){
        抛出新IllegalStateException异常(
                活动必须实现片段的回调。);
    }    mCallbacks =(回调)的活动;
}@覆盖
公共无效onDetach(){
    super.onDetach();    //重置主动回调接口虚拟实现。
    mCallbacks = sDummyCallbacks;
}@覆盖
公共无效onListItemClick(ListView控件的ListView,观景,INT位置,
        长ID){
    super.onListItemClick(ListView控件,查看,位置,ID);    //通知活性回调接口(活动,如果
    //片段连接到一个),该项目已经被选择。
    mCallbacks.onItemSelected(DummyContent.ITEMS.get(位置).ID);
}@覆盖
公共无效的onSaveInstanceState(捆绑outState){
    super.onSaveInstanceState(outState);
    如果(mActivatedPosition!= ListView.INVALID_POSITION){
        //序列化和持久化启动项目的位置。
        outState.putInt(STATE_ACTIVATED_POSITION,mActivatedPosition);
    }
}/ **
 *启用激活上点击模式。当此模式时,列表项将是
 *给出的激活状态时感动。
 * /
公共无效setActivateOnItemClick(布尔activateOnItemClick){
    //当设置CHOICE_MODE_SINGLE,自动的ListView会
    触摸时//给项目激活状态。
    getListView()。setChoiceMode(
            activateOnItemClick? ListView.CHOICE_MODE_SINGLE
                    :ListView.CHOICE_MODE_NONE);
}私人无效setActivatedPosition(INT位置){
    如果(位置== ListView.INVALID_POSITION){
        getListView()setItemChecked(mActivatedPosition,FALSE)。
    }其他{
        getListView()setItemChecked(位置,真)。
    }    mActivatedPosition =位置;
}
}


解决方案

您读取数据只是一次,而是需要一个背景下这样做。这似乎是一个不错的选择,延长应用程序

ItemListApplication:

 公共类ItemListApplication扩展应用{    @覆盖
    公共无效的onCreate(){
        super.onCreate();
        字符串路径=/数据/数据​​/+ getPackageName()+/数据库;
        如果(!checkDatabase(路径)){
            档案文件=新的文件(路径);
            file.mkdirs();
            尝试{
                InputStream的myInput = getAssets()开(名称)。
                //路径刚刚创建的空分贝
                字符串outFileName =路径+/+名;
                //打开空分贝的输出流
                的OutputStream myOutput =新的FileOutputStream(outFileName);
                //传递从inputfile中字节到OUTPUTFILE
                字节[]缓冲区=新的字节[1024];
                INT长;
                而((长度= myInput.read(缓冲液))大于0){
                    myOutput.write(缓冲液,0,长度);
                }
                //关闭流
                myOutput.flush();
                myOutput.close();
                myInput.close();            }赶上(IOException异常五){
                的System.out.println(E);
            }
        }
        SQLiteDatabase SDB =的openDatabase(路径);
        的getData(SDB);
        sdb.close();
    }    私人的ArrayList< GS>一个;    公共GS的getItem(INT ID){
        返回a.get(ID);
    }    公共ArrayAdapter< GS> getAdapter(上下文的背景下){
        返回新ArrayAdapter< GS>(上下文,android.R.layout.simple_list_item_activated_1,
                android.R.id.text1,一);
    }    私人最终字符串名称=superstition.sqlite;    私人布尔checkDatabase(字符串路径){
        SQLiteDatabase DB = NULL;
        尝试{
            DB = SQLiteDatabase.openDatabase(路径+/+名称,空
                    SQLiteDatabase.OPEN_READONLY);
        }赶上(例外五){
            e.printStackTrace();
        }
        如果(DB == NULL){
            返回false;
        }其他{
            db.close();
            返回true;
        }
    }    私人SQLiteDatabase的openDatabase(字符串路径){
        返回SQLiteDatabase.openDatabase(路径+/+姓名,空,
                SQLiteDatabase.OPEN_READWRITE);
    }    私人无效的getData(SQLiteDatabase SDB){
        游标c1 = sdb.rawQuery(SELECT * FROM数据,NULL);
        一个=新的ArrayList< GS>();
        而(c1.moveToNext()){
            GS GS =新GS();            gs.setItem(c1.getString(1));
            gs.setDesc(c1.getString(2));
            Log.v(ID,gs.item +);            a.add(GS);
        }
        c1.close();
    }
}

和添加类的名称属性添加到<应用> 标签:

 的android:NAME =com.example.myproject.ItemListApplication

这有效果,即 ItemListApplication.onCreate()是需要数据之前调用一次。同时在应用程序启动创建的实例,可通过 getApplication()

由于在列表中的数据是相同的适配器中的数据, INT 可用于通过位置来标识的项目。

有些变化都到code到进行:


  • ItemListActivity.java


    • 删除字段 DC

    • 后先删除一切如果的onCreate()

    • 改变 onItemSelected()为以下内容:

        @覆盖
      公共无效onItemSelected(INT ID){
          如果(mTwoPane){
              //在双窗格模式,显示出本次活动的详细视图通过
              //添加或更换使用的细节片段
              //片段交易。
              捆绑参数=新包();
              arguments.putInt(ItemDetailFragment.ARG_ITEM_ID,身份证);
              ItemDetailFragment片段=新ItemDetailFragment();
              fragment.setArguments(参数);
              getSupportFragmentManager()调用BeginTransaction()
                      .replace(R.id.item_detail_container,片段).commit();    }其他{
              //在单窗格模式,只需启动该活动的细节
              //所选项目的ID。
              意图detailIntent =新意图(这一点,ItemDetailActivity.class);
              detailIntent.putExtra(ItemDetailFragment.ARG_ITEM_ID,身份证);
              startActivity(detailIntent);
          }
      }



  • ItemDetailActivity.java


    • 的onCreate()更改如何使用参数填充:

        arguments.putInt(ItemDetailFragment.ARG_ITEM_ID,getIntent()
                          .getIntExtra(ItemDetailFragment.ARG_ITEM_ID,-1));



  • ItemDetailFragment.java


    • MITEM 的类型更改为 GS

    • 的onCreate()的分配 MITEM 更改为:

        MITEM =((ItemListApplication)getActivity()。getApplication())。的getItem(getArguments()调用getInt(
              ARG_ITEM_ID));


    • onCreateView()文本设置为 mItem.desc 而不是 MITEM的。内容搜索结果


  • ItemListFragment.java


    • 回调接口以及它的anomymus实现改变 onItemSelected(字符串)的签名 onItemSelected(INT)

    • 改变的onCreate()为以下内容:

       公共无效的onCreate(捆绑savedInstanceState){
          super.onCreate(savedInstanceState);    FragmentActivity活性= getActivity();
          setListAdapter(((ItemListApplication)activity.getApplication())getAdapter(活动));
      }


    • 更改 mCallbacks.onItemSelected(DummyContent.ITEMS.get(位置).ID); mCallbacks.onItemSelected(位置); onListItemClick()搜索结果


  • GS.java


    • 覆盖的toString()

        @覆盖
      公共字符串的toString(){
          归还物品;
      }



After running a new project on Master Detail flow in eclipse it shows the dummy items.

I want to replace these dummy items by the data from SQLite.

After calling the method of DBAdapter(& with the help of Cursor) I was able to print the values in log.

I have no Idea on how to display data stored in ArrayList<GetterSetter> to Master detail flow.

Please tell me what things should be modified in which of classes, or how should I code ?

UPDATE

DBAdapter.java

public class DBAdapter extends SQLiteOpenHelper
{
static String name = "superstition.sqlite";
static String path = "";
public static ArrayList<GS> a;
static SQLiteDatabase sdb;

@Override
public void onCreate(SQLiteDatabase db)
{
    // TODO Auto-generated method stub
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
    // TODO Auto-generated method stub
} 

private DBAdapter(Context v) 
{
    super(v, name, null, 1);
    path = "/data/data/" + v.getApplicationContext().getPackageName() + "/databases";
}

public boolean checkDatabase()
{
    SQLiteDatabase db = null;
    try 
    {
        db = SQLiteDatabase.openDatabase(path + "/" + name, null, SQLiteDatabase.OPEN_READONLY);
    } catch (Exception e) 
    {
        e.printStackTrace();
    }
    if (db == null) 
    {
        return false;
    } 
    else
    {
        db.close();
        return true;
    }
}

public static synchronized DBAdapter getDBAdapter(Context v)
{
    return (new DBAdapter(v));
}

public void createDatabase(Context v) 
{
    this.getReadableDatabase();
    try
    {
        InputStream myInput = v.getAssets().open(name);
        // Path to the just created empty db
    String outFileName = path +"/"+ name;
        // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);
        // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) 
    {
        myOutput.write(buffer, 0, length);
    }
        // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

    } catch (IOException e) 
    {
        System.out.println(e);
    }
}

public void openDatabase() 
{
    try 
    {
        sdb = SQLiteDatabase.openDatabase(path + "/" + name, null,
                SQLiteDatabase.OPEN_READWRITE);
    } catch (Exception e) 
    {
        System.out.println(e);
    }
}

public ArrayList<GS> getData() 
{
    Cursor c1 = sdb.rawQuery("SELECT * FROM data", null);
    a = new ArrayList<GS>();
    while (c1.moveToNext())
    {
        GS gs = new GS();

        gs.setItem(c1.getString(1));
        gs.setDesc(c1.getString(2));
        Log.v("id",gs.item+"");

        a.add(gs);
    }
    return a;
}
}

GS.java //getter setter class

public class GS {
String item,desc;


public String getItem() {
return item;
}

public void setItem(String item) {
this.item = item;
}

public String getDesc() {
return desc;
}

public void setDesc(String desc) {
this.desc = desc;
}
}

ItemListActivity.java

public class ItemListActivity extends FragmentActivity implements
    ItemListFragment.Callbacks {

/**
 * Whether or not the activity is in two-pane mode, i.e. running on a tablet
 * device.
 */
public DummyContent dc;
private boolean mTwoPane;
public ArrayList<GS> q = new ArrayList<GS>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_item_list);

    if (findViewById(R.id.item_detail_container) != null) {
        // The detail container view will be present only in the
        // large-screen layouts (res/values-large and
        // res/values-sw600dp). If this view is present, then the
        // activity should be in two-pane mode.
        mTwoPane = true;

        // In two-pane mode, list items should be given the
        // 'activated' state when touched.
        ((ItemListFragment) getSupportFragmentManager().findFragmentById(
                R.id.item_list)).setActivateOnItemClick(true);
    }

    DBAdapter db = DBAdapter.getDBAdapter(getApplicationContext());
    if (!db.checkDatabase()) 
    {
        db.createDatabase(getApplicationContext());
    }
    db.openDatabase();
    q=db.getData();
    dc = new DummyContent();


    // TODO: If exposing deep links into your app, handle intents here.
}

/**
 * Callback method from {@link ItemListFragment.Callbacks} indicating that
 * the item with the given ID was selected.
 */
@Override
public void onItemSelected(String id) {
    if (mTwoPane) {
        // In two-pane mode, show the detail view in this activity by
        // adding or replacing the detail fragment using a
        // fragment transaction.
        Bundle arguments = new Bundle();
        arguments.putString(ItemDetailFragment.ARG_ITEM_ID, id);
        ItemDetailFragment fragment = new ItemDetailFragment();
        fragment.setArguments(arguments);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.item_detail_container, fragment).commit();

    } else {
        // In single-pane mode, simply start the detail activity
        // for the selected item ID.
        Intent detailIntent = new Intent(this, ItemDetailActivity.class);
        detailIntent.putExtra(ItemDetailFragment.ARG_ITEM_ID, id);
        startActivity(detailIntent);
    }
}
}

DummyContent.java // I think that in this static block has to be modified

public class DummyContent {
static int i=0;
/**
 * An array of sample (dummy) items.
 */
public static List<DummyItem> ITEMS = new ArrayList<DummyItem>();

/**
 * A map of sample (dummy) items, by ID.
 */
public static Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();

static {

    for(i=0;i<182;i++)
    addItem(new DummyItem(""+i, "Item "+i));

}

private static void addItem(DummyItem item) {
    ITEMS.add(item);
    ITEM_MAP.put(item.id, item);
}

/**
 * A dummy item representing a piece of content.
 */
public static class DummyItem {
    public String id;
    public String content;

    public DummyItem(String id, String content) {
        this.id = id;
        this.content = content;
    }

    @Override
    public String toString() {
        return content;
    }
}
}

ItemDetailActivity.java // same as generated by eclipse

public class ItemDetailActivity extends FragmentActivity {

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

    // Show the Up button in the action bar.
    getActionBar().setDisplayHomeAsUpEnabled(true);

    // savedInstanceState is non-null when there is fragment state
    // saved from previous configurations of this activity
    // (e.g. when rotating the screen from portrait to landscape).
    // In this case, the fragment will automatically be re-added
    // to its container so we don't need to manually add it.
    // For more information, see the Fragments API guide at:
    //
    // http://developer.android.com/guide/components/fragments.html
    //
    if (savedInstanceState == null) {
        // Create the detail fragment and add it to the activity
        // using a fragment transaction.
        Bundle arguments = new Bundle();
        arguments.putString(ItemDetailFragment.ARG_ITEM_ID, getIntent()
                .getStringExtra(ItemDetailFragment.ARG_ITEM_ID));
        ItemDetailFragment fragment = new ItemDetailFragment();
        fragment.setArguments(arguments);
        getSupportFragmentManager().beginTransaction()
                .add(R.id.item_detail_container, fragment).commit();
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        // This ID represents the Home or Up button. In the case of this
        // activity, the Up button is shown. Use NavUtils to allow users
        // to navigate up one level in the application structure. For
        // more details, see the Navigation pattern on Android Design:
        //
        // http://developer.android.com/design/patterns/navigation.html#up-vs-back
        //
        NavUtils.navigateUpTo(this,
                new Intent(this, ItemListActivity.class));
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

ItemDetailFragment.java // same as generated by eclipse

public class ItemDetailFragment extends Fragment {
/**
 * The fragment argument representing the item ID that this fragment
 * represents.
 */
public static final String ARG_ITEM_ID = "item_id";

/**
 * The dummy content this fragment is presenting.
 */
private DummyContent.DummyItem mItem;

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public ItemDetailFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments().containsKey(ARG_ITEM_ID)) {
        // Load the dummy content specified by the fragment
        // arguments. In a real-world scenario, use a Loader
        // to load content from a content provider.
        mItem = DummyContent.ITEM_MAP.get(getArguments().getString(
                ARG_ITEM_ID));
    }
}

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

    // Show the dummy content as text in a TextView.
    if (mItem != null) {
        ((TextView) rootView.findViewById(R.id.item_detail))
                .setText(mItem.content);
    }

    return rootView;
}
}

ItemListFragment.java // same as generated by eclipse

public class ItemListFragment extends ListFragment {

/**
 * The serialization (saved instance state) Bundle key representing the
 * activated item position. Only used on tablets.
 */
private static final String STATE_ACTIVATED_POSITION = "activated_position";

/**
 * The fragment's current callback object, which is notified of list item
 * clicks.
 */
private Callbacks mCallbacks = sDummyCallbacks;

/**
 * The current activated item position. Only used on tablets.
 */
private int mActivatedPosition = ListView.INVALID_POSITION;

/**
 * A callback interface that all activities containing this fragment must
 * implement. This mechanism allows activities to be notified of item
 * selections.
 */
public interface Callbacks {
    /**
     * Callback for when an item has been selected.
     */
    public void onItemSelected(String id);
}

/**
 * A dummy implementation of the {@link Callbacks} interface that does
 * nothing. Used only when this fragment is not attached to an activity.
 */
private static Callbacks sDummyCallbacks = new Callbacks() {
    @Override
    public void onItemSelected(String id) {
    }
};

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public ItemListFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // TODO: replace with a real list adapter.
    setListAdapter(new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
            android.R.layout.simple_list_item_activated_1,
            android.R.id.text1, DummyContent.ITEMS));
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Restore the previously serialized activated item position.
    if (savedInstanceState != null
            && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
        setActivatedPosition(savedInstanceState
                .getInt(STATE_ACTIVATED_POSITION));
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // Activities containing this fragment must implement its callbacks.
    if (!(activity instanceof Callbacks)) {
        throw new IllegalStateException(
                "Activity must implement fragment's callbacks.");
    }

    mCallbacks = (Callbacks) activity;
}

@Override
public void onDetach() {
    super.onDetach();

    // Reset the active callbacks interface to the dummy implementation.
    mCallbacks = sDummyCallbacks;
}

@Override
public void onListItemClick(ListView listView, View view, int position,
        long id) {
    super.onListItemClick(listView, view, position, id);

    // Notify the active callbacks interface (the activity, if the
    // fragment is attached to one) that an item has been selected.
    mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (mActivatedPosition != ListView.INVALID_POSITION) {
        // Serialize and persist the activated item position.
        outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
    }
}

/**
 * Turns on activate-on-click mode. When this mode is on, list items will be
 * given the 'activated' state when touched.
 */
public void setActivateOnItemClick(boolean activateOnItemClick) {
    // When setting CHOICE_MODE_SINGLE, ListView will automatically
    // give items the 'activated' state when touched.
    getListView().setChoiceMode(
            activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
                    : ListView.CHOICE_MODE_NONE);
}

private void setActivatedPosition(int position) {
    if (position == ListView.INVALID_POSITION) {
        getListView().setItemChecked(mActivatedPosition, false);
    } else {
        getListView().setItemChecked(position, true);
    }

    mActivatedPosition = position;
}
}

解决方案

You read the data just once, but need a context to do so. It seems a good choice to extend Application:

ItemListApplication:

public class ItemListApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        String path = "/data/data/" + getPackageName() + "/databases";
        if (!checkDatabase(path)) {
            File file = new File(path);
            file.mkdirs();
            try {
                InputStream myInput = getAssets().open(name);
                // Path to the just created empty db
                String outFileName = path + "/" + name;
                // Open the empty db as the output stream
                OutputStream myOutput = new FileOutputStream(outFileName);
                // transfer bytes from the inputfile to the outputfile
                byte[] buffer = new byte[1024];
                int length;
                while ((length = myInput.read(buffer)) > 0) {
                    myOutput.write(buffer, 0, length);
                }
                // Close the streams
                myOutput.flush();
                myOutput.close();
                myInput.close();

            } catch (IOException e) {
                System.out.println(e);
            }
        }
        SQLiteDatabase sdb = openDatabase(path);
        getData(sdb);
        sdb.close();
    }

    private ArrayList<GS> a;

    public GS getItem(int id) {
        return a.get(id);
    }

    public ArrayAdapter<GS> getAdapter(Context context) {
        return new ArrayAdapter<GS>(context, android.R.layout.simple_list_item_activated_1,
                android.R.id.text1, a);
    }

    private final String name = "superstition.sqlite";

    private boolean checkDatabase(String path) {
        SQLiteDatabase db = null;
        try {
            db = SQLiteDatabase.openDatabase(path + "/" + name, null,
                    SQLiteDatabase.OPEN_READONLY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (db == null) {
            return false;
        } else {
            db.close();
            return true;
        }
    }

    private SQLiteDatabase openDatabase(String path) {
        return SQLiteDatabase.openDatabase(path + "/" + name, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    private void getData(SQLiteDatabase sdb) {
        Cursor c1 = sdb.rawQuery("SELECT * FROM data", null);
        a = new ArrayList<GS>();
        while (c1.moveToNext()) {
            GS gs = new GS();

            gs.setItem(c1.getString(1));
            gs.setDesc(c1.getString(2));
            Log.v("id", gs.item + "");

            a.add(gs);
        }
        c1.close();
    }
}

and add the class name as attribute to the <application> tag:

android:name="com.example.myproject.ItemListApplication"

This has the effect, that ItemListApplication.onCreate() is called once before the data is needed. Also the instance created on application start is available through getApplication().

Since the data in the list is identical to the data in the adapter, int can be used to identify the items by position.

Some changes have to be made to your code:

  • ItemListActivity.java

    • delete fields dc, q
    • delete everything after the first if in onCreate()
    • change onItemSelected() to the following:

      @Override
      public void onItemSelected(int id) {
          if (mTwoPane) {
              // In two-pane mode, show the detail view in this activity by
              // adding or replacing the detail fragment using a
              // fragment transaction.
              Bundle arguments = new Bundle();
              arguments.putInt(ItemDetailFragment.ARG_ITEM_ID, id);
              ItemDetailFragment fragment = new ItemDetailFragment();
              fragment.setArguments(arguments);
              getSupportFragmentManager().beginTransaction()
                      .replace(R.id.item_detail_container, fragment).commit();
      
          } else {
              // In single-pane mode, simply start the detail activity
              // for the selected item ID.
              Intent detailIntent = new Intent(this, ItemDetailActivity.class);
              detailIntent.putExtra(ItemDetailFragment.ARG_ITEM_ID, id);
              startActivity(detailIntent);
          }
      }
      

  • ItemDetailActivity.java

    • in onCreate() change how the arguments is filled:

      arguments.putInt(ItemDetailFragment.ARG_ITEM_ID, getIntent()
                          .getIntExtra(ItemDetailFragment.ARG_ITEM_ID, -1));
      

  • ItemDetailFragment.java

    • change the type of mItem to GS
    • in onCreate() change the assignment of mItem to:

      mItem = ((ItemListApplication)getActivity().getApplication()).getItem(getArguments().getInt(
              ARG_ITEM_ID));
      

    • in onCreateView() set the text to mItem.desc instead of mItem.content

  • ItemListFragment.java

    • in the Callbacks interface as well as it's anomymus implementation change the signature of onItemSelected(String) to onItemSelected(int)
    • change onCreate() to the following:

      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
      
          FragmentActivity activity = getActivity();
          setListAdapter(((ItemListApplication)activity.getApplication()).getAdapter(activity));
      }
      

    • change mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id); to mCallbacks.onItemSelected(position); in onListItemClick()

  • GS.java

    • override toString():

      @Override
      public String toString() {
          return item;
      }
      

这篇关于在主流程详细数据显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆