簡體   English   中英

在主明細流中顯示數據

[英]Show data in Master detail flow

在Eclipse的Master Detail流上運行新項目后,它將顯示虛擬項目。

我想用SQLite的數據替換這些虛擬項。

調用DBAdapter的方法(在Cursor的幫助下,&)之后,我能夠在日志中打印值。

我不知道如何將存儲在ArrayList<GetterSetter>數據顯示到主詳細信息流。

請告訴我應該在哪些類中修改哪些內容,或者應該如何編碼?

更新

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類

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 //我認為必須修改此靜態塊

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

您只讀取一次數據,但是需要上下文。 擴展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();
    }
}

並將類名稱作為屬性添加到<application>標記:

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

這樣的效果是,在需要數據之前, ItemListApplication.onCreate()被調用一次。 同樣,可以通過getApplication()獲得在應用程序啟動時創建的實例。

由於列表中的數據與適配器中的數據相同,因此int可用於按位置識別項目。

必須對您的代碼進行一些更改:

  • ItemListActivity.java

    • 刪除字段dcq
    • 如果在onCreate()則刪除第一個之后的所有內容
    • onItemSelected()更改為以下內容:

       @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

    • onCreate()更改arguments的填充方式:

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

    • mItem的類型mItemGS
    • onCreate()mItem的分配mItem為:

       mItem = ((ItemListApplication)getActivity().getApplication()).getItem(getArguments().getInt( ARG_ITEM_ID)); 
    • onCreateView()將文本設置為mItem.desc而不是mItem.content

  • ItemListFragment.java

    • Callbacks接口及其anomymus實現中,將onItemSelected(String)的簽名更改為onItemSelected(int)
    • onCreate()更改為以下內容:

       public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentActivity activity = getActivity(); setListAdapter(((ItemListApplication)activity.getApplication()).getAdapter(activity)); } 
    • 更改mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id); mCallbacks.onItemSelected(position); onListItemClick()

  • GS.java

    • 覆蓋toString()

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM