android - 单击按钮时将 TextView 文本插入 SQLite

标签 android sqlite button textview

问题:如何将 TextView 信息传递到变量中,以便在单击按钮时将该信息添加到创建的名为集合的 SQLite 数据库中。

遗漏的文件(因为我认为它们不相关):androidmanafest.xml、database.java(用于填充卡片数据库)和 cards.java(用于 setter getter)。

它的样子: enter image description here

主要 Activity :

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    SearchAdapter adapter;

    MaterialSearchBar materialSearchBar;
    List<String> suggestList = new ArrayList<>();

    Database database;

    //used for inserting card into collection database
    DB_Controller controller;
    TextView card_name, type, rarity, artist;

    Button addCollectionButton;

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


        //This is all for the controller in order to pass each card into collection database
        controller = new DB_Controller(this,"collection.db",null,1);
        setContentView(R.layout.layout_item);
        card_name = (TextView)findViewById(R.id.card_name);
        type = (TextView)findViewById(R.id.type);
        rarity = (TextView)findViewById(R.id.rarity);
        artist = (TextView)findViewById(R.id.artist);

        //functionality of button "ADD TO COLLECTION"
        addCollectionButton = (Button)findViewById(R.id.button_collection);
        addCollectionButton.setOnClickListener(new View.OnClickListener() {

            //when button clicked, insert into collection database
            @Override
            public void onClick(View view) {

                String nameCard = card_name.getText().toString();
                String typeCard = type.getText().toString();
                String rarityCard = rarity.getText().toString();
                String artistCard = artist.getText().toString();
                //switch is used in case we need to add more buttons elsewhere in the app
                //switch(view.getId()){
                //    case R.id.button_collection:
                        //controller.insert_card("drl","drl", "drl", "drl", "drl");
                        Toast.makeText(getBaseContext(), "ADDED TO COLLECTION", Toast.LENGTH_LONG).show(); //confirm card was added
                        //break;
                //}
            }
        });

        setContentView(R.layout.activity_main);
        //init View
        recyclerView = (RecyclerView)findViewById(R.id.recycler_search);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);

        materialSearchBar = (MaterialSearchBar)findViewById(R.id.search_bar);
        //materialSearchBar.inflateMenu(R.layout.activity_main);
        //init DB
        database = new Database(this);

        //setup search bar
        //materialSearchBar.setHint("Search");
        //materialSearchBar.setCardViewElevation(10);
        loadSuggestList();

        //This is used when typing in search bar suggesting words like those that have been typed
        materialSearchBar.addTextChangeListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

            }

            // method for when user types in search bar, return suggested strings
            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int after) {

                List<String> suggest = new ArrayList<>();
                for(String search : suggestList) {
                    if(search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
                        suggest.add(search);
                }
                materialSearchBar.setLastSuggestions(suggest);

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


        //This is used when user has typed the word(s) needed to search and hits the search icon
        materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {

            @Override
            public void onSearchStateChanged(boolean enabled) {
                if(!enabled)
                    recyclerView.setAdapter(adapter);
            }

            @Override
            public void onSearchConfirmed(CharSequence text) {
                startSearch(text.toString());
            }

            @Override
            public void onButtonClicked(int buttonCode) {

            }
        });

        //init Adapter default set all result
        //adapter = new SearchAdapter(this, database.getFriends());
        adapter = new SearchAdapter(this, database.getCards());
        recyclerView.setAdapter(adapter);
    }


    private void startSearch(String text) {
        //adapter = new SearchAdapter(this, database.getFriendByName(text));
        adapter = new SearchAdapter(this, database.getCardsByName(text));
        recyclerView.setAdapter(adapter);
    }


    //for populating suggestion list when search bar has been activated
    private void loadSuggestList() {
        suggestList = database.getNames();
        materialSearchBar.setLastSuggestions(suggestList);
    }

}

layout_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardElevation="8dp"
    android:layout_margin="8dp">

    <!--Creation of overall look of searched results
        Main design tile for each searched result-->
    <LinearLayout
        android:orientation="horizontal"
        android:layout_margin="8dp"
        android:background="@android:color/white"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!--default image for each tile-->
        <ImageView
            android:src="@drawable/ic_image_black_24dp"
            android:layout_width="70dp"
            android:layout_height="70dp" />

        <!--design tile within the main tile to display the information pulled from database-->
        <LinearLayout
            android:orientation="vertical"
            android:layout_weight="9"
            android:layout_width="0dp"
            android:layout_height="wrap_content">

            <!--information pulled from database design: NAME
            android:id="@+id/name"-->
            <TextView
                android:id="@+id/card_name"
                android:layout_marginLeft="10dp"
                android:gravity="center_vertical|start"
                android:textAllCaps="true"
                android:textStyle="bold"
                android:text="Eddy Lee"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <!--information pulled from database design: EMAIL
            android:id="@+id/email"-->
            <TextView
                android:id="@+id/type"
                android:layout_marginLeft="10dp"
                android:gravity="center_vertical|start"
                android:textStyle="italic"
                android:text="eddy@gmail.com"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <!--information pulled from database design: PHONE
            android:id="@+id/phone"-->
            <TextView
                android:id="@+id/rarity"
                android:layout_marginLeft="10dp"
                android:gravity="center_vertical|start"
                android:textAllCaps="true"
                android:textStyle="bold"
                android:text="(123)456-7890"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <!--information pulled from database design: ADDRESS
            android:id="@+id/address"-->
            <TextView
                android:id="@+id/artist"
                android:layout_marginLeft="10dp"
                android:gravity="center_vertical|start"
                android:textAllCaps="true"
                android:textStyle="normal"
                android:text="123 Seseme Street"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <Button
                android:id="@+id/button_collection"
                android:layout_width="200dp"
                android:layout_height="35dp"
                android:text="Add to Collection"
                />
        </LinearLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.darrelbott.search.MainActivity">

    <com.mancj.materialsearchbar.MaterialSearchBar
        app:mt_speechMode="false"
        app:mt_hint="Custom hint"
        app:mt_maxSuggestionsCount="10"
        app:mt_searchBarColor="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/search_bar" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_search"
        android:layout_below="@+id/search_bar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

DB_Controller:

public class DB_Controller extends SQLiteOpenHelper {

    private static final String TABLE_COLLECTION = "collection";
    private static final String COLUMN_COLLECTION_ACCOUNT = "account";
    private static final String COLUMN_COLLECTION_NAME = "card_name";
    private static final String COLUMN_COLLECTION_TYPE = "type";
    private static final String COLUMN_COLLECTION_RARITY = "rarity";
    private static final String COLUMN_COLLECTION_ARTIST = "artist";

    SQLiteDatabase db;
    Context context;
    int version = 1;

    public DB_Controller(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, "collection.db", factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_COLLECTION + " (id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COLUMN_COLLECTION_ACCOUNT + " TEXT, "
                + COLUMN_COLLECTION_NAME + " TEXT, "
                + COLUMN_COLLECTION_TYPE + " TEXT, "
                + COLUMN_COLLECTION_RARITY + " TEXT, "
                + COLUMN_COLLECTION_ARTIST + " TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        //sqLiteDatabase.execSQL("DROP TABLE IF EXISTS collection;");
        //onCreate(sqLiteDatabase);
    }

    public void insert_card(String account, String card_name, String type, String rarity, String artist) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_COLLECTION_ACCOUNT,account);
        contentValues.put(COLUMN_COLLECTION_NAME,card_name);
        contentValues.put(COLUMN_COLLECTION_TYPE,type);
        contentValues.put(COLUMN_COLLECTION_RARITY,rarity);
        contentValues.put(COLUMN_COLLECTION_ARTIST,artist);

        db.insert(TABLE_COLLECTION,null,contentValues);


        //this.getWritableDatabase().insertOrThrow("collection.db","",contentValues);
    }
}

适配器(包含 SearchAdapter 和 SearchViewHolder):

    class SearchViewHolder extends RecyclerView.ViewHolder {

    //public TextView name, address, email, phone;
    public TextView card_name, type, rarity, artist;

    public SearchViewHolder(@NonNull View itemView) {
        super(itemView);
        card_name = (TextView)itemView.findViewById(R.id.card_name);
        type = (TextView)itemView.findViewById(R.id.type);
        rarity = (TextView)itemView.findViewById(R.id.rarity);
        artist = (TextView)itemView.findViewById(R.id.artist);
    }
}

public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder> {

    private Context context;
    //private List<Friend> friends;
    private List<Cards> cards;


    public SearchAdapter(Context context, List<Cards> cards /*List<Friend> friends*/ ) {
        this.context = context;
        //this.friends = friends;
        this.cards = cards;
    }

    @NonNull
    @Override
    public SearchViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View itemView = inflater.inflate(R.layout.layout_item, parent, false);
        return new SearchViewHolder(itemView);
    }

    Button addCollectionButton;

    @Override
    public void onBindViewHolder(@NonNull SearchViewHolder holder, int position) {
        /*
        holder.name.setText(friends.get(position).getName());
        holder.address.setText(friends.get(position).getAddress());
        holder.email.setText(friends.get(position).getEmail());
        holder.phone.setText(friends.get(position).getPhone());
        */
        holder.card_name.setText(cards.get(position).getName());
        holder.type.setText(cards.get(position).getType());
        holder.rarity.setText(cards.get(position).getRarity());
        holder.artist.setText(cards.get(position).getArtist());

        /*
        //functionality of button "ADD TO COLLECTION"
        final DB_Controller controller = new DB_Controller(this,"collection.db",null,1);
        addCollectionButton.setOnClickListener(new View.OnClickListener() {

            //when button clicked, insert into collection database
            @Override
            public void onClick(View view) {

                //String card_name1 = card_name.setText(cards.get(position).getName());
                //switch is used in case we need to add more buttons elsewhere in the app
                //switch(view.getId()){
                //    case R.id.button_collection:
                controller.insert_card("drl","drl", "drl", "drl", "drl");
                //Toast.makeText(getApplicationContext(), "ADDED TO COLLECTION", Toast.LENGTH_LONG).show(); //confirm card was added
                //break;
                //}
            }
        });
        */
    }

    @Override
    public int getItemCount() {
        //return friends.size();
        return cards.size();
    }


}

最佳答案

您需要在按钮实际所在的适配器内安装 onClickListener。您所做的是让听众参与主要 Activity ,这是不正确的。将您的监听器放在 onBindViewHolder() 中,如果 sql 代码中没有问题,它应该可以工作

关于android - 单击按钮时将 TextView 文本插入 SQLite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53694941/

相关文章:

android - 下拉按钮/微调器,就像谷歌设计规范中的那些

java - 动态向 Fragment 添加按钮

java - 在 ImageView 中分别设置来自相机的两个裁剪图像(Android Studio)

android - Textviews 与 edittext android 相去甚远

node.js - Node sqlite3 : Trying to write a function to return an array of rows

sqlite - 将数据插入 blob

android - 调试Widget导致ANR

android - 在没有 Google 开发者帐户的情况下使用 Google Play 游戏服务

delphi - 在 SQLite 数据库(Delphi)中存储日期时间值的最佳方式

android - 左键没有出现 [XML 布局]