Вставка текста TextView в SQLite по нажатию кнопки - PullRequest
0 голосов
/ 09 декабря 2018

Вопрос : Как передать информацию TextView в переменную, чтобы при нажатии кнопки она добавляла эту информацию в созданную базу данных SQLite, называемую коллекциями.

Файлыопущены (потому что я не думал, что они связали : androidmanafest.xml, database.java (это было для заполнения базы данных карт) и cards.java (для методов получения сеттеров).

Как это выглядит : введите описание изображения здесь

Основная деятельность :

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();
    }


}

Ответы [ 2 ]

0 голосов
/ 10 декабря 2018

Как я уже говорил ранее: вам нужно добавить onClick() метод вашего addCollectionButton Button к вашему классу адаптера в методе onBindViewHolder()."Button_collection" Button в вашем макете CardView не имеет ничего общего с макетом "main_activity".


Попробуйте этот код для своего Adapter.

Примечание: Я сделал это в текстовом редакторе, так что может быть несколько опечаток!

Также обратите внимание : я изменил вам «карты» List на ArrayList - так что вам нужно будет компенсировать ваш Activity код.

public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.MyViewHolder> {

    private static final String TAG = SearchAdapter.class.getSimpleName();

    private Context mContext;
    private final DB_Controller dbController;
    private ArrayList<Cards> cards;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView card_name, type, rarity, artist;
        public Button addCollectionButton;


        public MyViewHolder(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);
            addCollectionButton = (Button)itemView.findViewById(R.id.button_collection);
        }
    }


    public SearchAdapter(Context context, ArrayList<Cards> cards) {
        this.mContext = context;
        dbController = new DB_Controller(context,"collection.db",null,1);
        this.cards = cards;
    }


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

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Cards cardsData = cards.get(position);

        holder.card_name.setText(cardsData.getName());
        holder.type.setText(cardsData.getType());
        holder.rarity.setText(cardsData.getRarity());
        holder.artist.setText(cardsData.getArtist());

        holder.addCollectionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e(TAG, "on click " + position);

                String cardName = cardsData.getName();
                String cardType = cardsData.getType();
                String cardRarity = cardsData.getRarity();
                String cardArtist = cardsData.getArtist();

                // You will need to add the data as needed!
                dbController.insert_card("drl","drl", "drl", "drl", "drl");
                Toast.makeText(mContext, "ADDED TO COLLECTION: " + cardName, Toast.LENGTH_LONG).show(); //confirm card was added
            }
        });
    }

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

----------
Пожалуйста, дайте мне знать, если у вас есть какие-либо проблемы с вышеуказанным кодом.

0 голосов
/ 09 декабря 2018

Вам нужно иметь onClickListener внутри адаптера, где кнопка на самом деле находится.То, что вы сделали, так это включили слушателя в основную деятельность, что неверно.Поместите ваш слушатель в onBindViewHolder (), и он должен работать, если в коде sql нет проблем

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...