书签/收藏夹

时间:2012-11-14 15:02:46

标签: android

我正在尝试制作一个仅包含文字的应用。每个页面(xml)都不同。现在我想为用户创建一个书签页面来为他/她的收藏夹添加书签。我成功制作了一个书签页面,该页面通过主屏幕上的按钮激活,我在每个文本页面上都有一个书签按钮,但我无法弄清楚如何在书签上发送或显示我的书签页面/文本页。这就是我得到的,这不起作用:

package life.quotes;


/** Called when the activity is first created. */    
@Override    
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page1);
    cb = (CheckBox)findViewById(R.id.favorites);
    b = (Button)findViewById(R.id.button_right);

    Button Page2 = (Button) findViewById(R.id.button_right);
    Page2.setOnClickListener(new View.OnClickListener() {
        public void onClick (View view) {
            Intent myIntent = new Intent(view.getContext(), Page2.class);
            startActivityForResult(myIntent, 0);
        }
    });

    cb.setOnClickListener(this);
}

private void savePrefs(String key, boolean value){
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    Editor edit= sp.edit();
    edit.putBoolean(key, value);
    edit.commit();
}

private void savePrefs(String key, String value){ 
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    Editor edit= sp.edit();
    edit.putString(key, value);
    edit.commit();
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    savePrefs("FAVORITES", cb.isChecked());
    savePrefs("QUOTE1", getString(R.string.quote1));
}
        `

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

如果每个页面都只是你说的文字,你可以从textview获取文本并将它们添加到SQLite数据库中。

这是我的意思的一个例子,基于我做的应用程序 DatabaseConnector.java:

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;


public class DatabaseConnector {

    private static final String DB_NAME = "WorldCountries";
    private SQLiteDatabase database;
    private DatabaseOpenHelper dbOpenHelper;

    public DatabaseConnector(Context context) {
            dbOpenHelper = new DatabaseOpenHelper(context, DB_NAME, null, 1);
    }

    public void open() throws SQLException {
       database = dbOpenHelper.getWritableDatabase();
    } 

    public void close() {
      if (database != null)
         database.close();
    }      

    public void insertContact(String name, String cap)  {
      ContentValues newCon = new ContentValues();
      newCon.put("name", name);
      newCon.put("cap", cap);

      open();
      database.insert("country", null, newCon);
      close();
    }


    public void updateContact(long id, String name, String cap) {
      ContentValues editCon = new ContentValues();
      editCon.put("name", name);
      editCon.put("cap", cap);

      open();
      database.update("country", editCon, "_id=" + id, null);
      close();
    }


    public Cursor getAllContacts() {
       return database.query("country", new String[] {"_id", "name"}, null, null, null, null, "name");
    }

    public Cursor getOneContact(long id) {
       return database.query("country", null, "_id=" + id, null, null, null, null);
    }

    public void deleteContact(long id) {
       open(); 
       database.delete("country", "_id=" + id, null);
       close();
    }
}

<强> DatabaseOpenHelper.java:

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseOpenHelper extends SQLiteOpenHelper {

    public DatabaseOpenHelper(Context context, String name,
            CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createQuery = "CREATE TABLE country (_id integer primary key autoincrement,name, cap);";                 
        db.execSQL(createQuery);        
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

现在这是包含添加到收藏夹或书签的项目列表的活动 FavoriteList.java:

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class FavoriteList extends ListActivity {

    public static final String ROW_ID = "row_id";
    private ListView conListView;
    private CursorAdapter conAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        conListView=getListView();
        conListView.setOnItemClickListener(viewConListener);

        // map each name to a TextView
    String[] from = new String[] { "name" };
    int[] to = new int[] { R.id.countryTextView };
    conAdapter = new SimpleCursorAdapter(FavoriteList.this, R.layout.country_list, null, from, to);
    setListAdapter(conAdapter); // set adapter
    }


    @Override
    protected void onResume() {
       super.onResume();  
       new GetContacts().execute((Object[]) null);
    } 


    @Override
    protected void onStop() {
       Cursor cursor = conAdapter.getCursor();

       if (cursor != null) 
          cursor.deactivate();

       conAdapter.changeCursor(null);
       super.onStop();
    }    


    private class GetContacts extends AsyncTask<Object, Object, Cursor> 
    {
       DatabaseConnector dbConnector = new DatabaseConnector(FavoriteList.this);

       @Override
       protected Cursor doInBackground(Object... params) {
          dbConnector.open();
          return dbConnector.getAllContacts(); 
       } 

       @Override
       protected void onPostExecute(Cursor result) {
            conAdapter.changeCursor(result); // set the adapter's Cursor
            dbConnector.close();
       } 
    } 

    OnItemClickListener viewConListener = new OnItemClickListener() {
       public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {         
          Intent viewCon = new Intent(FavoriteList.this, ViewFav.class);
          viewCon.putExtra(ROW_ID, arg3);
          startActivity(viewCon);
       }
    };   

}

这是查看收藏夹列表中每个项目的活动,其中有一个菜单项可以从数据库中删除条目 ViewFav.java

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;

public class ViewFav extends Activity {

   private long rowID;
   private TextView nameTv;
   private TextView capTv;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.view_fav);

      setUpViews();
      Bundle extras = getIntent().getExtras();
      rowID = extras.getLong(FavoriteList.ROW_ID); 
   }

   private void setUpViews() {
       nameTv = (TextView) findViewById(R.id.nameText);
       capTv = (TextView) findViewById(R.id.capText);
   }

   @Override
   protected void onResume() {
      super.onResume();
      new LoadContacts().execute(rowID);
   } 

   private class LoadContacts extends AsyncTask<Long, Object, Cursor> {
      DatabaseConnector dbConnector = new DatabaseConnector(ViewFav.this);

      @Override
      protected Cursor doInBackground(Long... params) {
         dbConnector.open();
         return dbConnector.getOneContact(params[0]);
      } 

      @Override
      protected void onPostExecute(Cursor result) {
         super.onPostExecute(result);

         result.moveToFirst();
         int nameIndex = result.getColumnIndex("name");
         int capIndex = result.getColumnIndex("cap");

         nameTv.setText(result.getString(nameIndex));
         capTv.setText(result.getString(capIndex));

         result.close();
         dbConnector.close();
      }
   } 


   @Override
   public boolean onCreateOptionsMenu(Menu menu)  {
      super.onCreateOptionsMenu(menu);
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.view_fav_menu, menu);
      return true;
   }

   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
         case R.id.deleteItem:
            deleteContact();
            return true;

         default:
            return super.onOptionsItemSelected(item);
      } 
   }

   private void deleteContact() {
      AlertDialog.Builder alert = new AlertDialog.Builder(ViewFav.this);
      alert.setTitle(R.string.confirmTitle); 
      alert.setMessage(R.string.confirmMessage); 
      alert.setPositiveButton(R.string.delete_btn,
         new DialogInterface.OnClickListener()  {
            public void onClick(DialogInterface dialog, int button) {
               final DatabaseConnector dbConnector = 
                  new DatabaseConnector(ViewFav.this);

               AsyncTask<Long, Object, Object> deleteTask =
                  new AsyncTask<Long, Object, Object>()  {
                     @Override
                     protected Object doInBackground(Long... params) {
                        dbConnector.deleteContact(params[0]); 
                        return null;
                     } 

                     @Override
                     protected void onPostExecute(Object result) {
                        finish(); 
                     }
                  };

               deleteTask.execute(new Long[] { rowID });               
            }
         }
      );

      alert.setNegativeButton(R.string.cancel_btn, null).show();
   }
}

最后在您的活动/片段中添加一个最喜欢的按钮 当点击收藏夹按钮获取textview中的内容并将它们添加为数据库中的条目时,在这种情况下数据库包含

    private long rowID; 
    private TextView nameEt;
    private TextView capEt;

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

         nameEt = (TextView) findViewById(R.id.textView1);
         capEt = (TextView) findViewById(R.id.textView2);

         //other stuff in OnCreate ......
    }

    private MenuItem itemfav;
    @Override
    public boolean  onCreateOptionsMenu(Menu menu) {
        itemfav = menu.add(0, 10, 10, "Favorite");
        itemfav.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case 10:
                fav();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    private void fav() {
        AsyncTask<Object, Object, Object> saveContactTask = 
                   new AsyncTask<Object, Object, Object>() 
                   {
                      @Override
                      protected Object doInBackground(Object... params) 
                      {
                         saveContact();
                         return null;
                      }

                      @Override
                      protected void onPostExecute(Object result) 
                      {
                         Toast.makeText(Button2.this, "Item has been added to favorites", Toast.LENGTH_SHORT).show();
                      }
                   }; 

                saveContactTask.execute((Object[]) null); 
    }

    private void saveContact() 
       {
          DatabaseConnector dbConnector = new DatabaseConnector(this);
              dbConnector.insertContact(nameEt.getText().toString(),capEt.getText().toString());

       }