как получить значения всех текстовых представлений выбранного флажка формы настраиваемого списка в Android - PullRequest
0 голосов
/ 19 ноября 2018

У меня есть имя фрагмента selectattributefragment.java, в котором у меня есть настраиваемый просмотр списка, включающий два четырех текстовых просмотра и один флажок для каждой строки, данные текстового просмотра извлекаются из базы данных sqlite с использованием простого настраиваемого адаптера, теперь я хочу получить значения текстовое поле выбранного флажка для отображения при событии нажатия кнопки

1.    selectattributefragment.java

public class ObservationselectattributeFragment extends Fragment {

    DatabaseHandler mDBHandler;
    ListView mListView;
    SimpleCursorAdapter mSCA;
    Cursor mCsr;
    ArrayList<String> attributeItems = new ArrayList<>();
    SparseBooleanArray sparseBooleanArray ;

    public ObservationselectattributeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_observationselectattribute, container, false);
        mListView = (ListView)view.findViewById(R.id.lv001);
        mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        Button addattribute = (Button)view.findViewById(R.id.addattribute);
        addattribute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String items="";
                Integer tcount=0;
                for(String item:attributeItems){
                   items+="-"+item+"\n";
                    tcount++;
                }
                Toast.makeText(getActivity(),"you have selected \n"+items,Toast.LENGTH_LONG).show();
                Toast.makeText(getActivity(),"you have selected \n"+tcount,Toast.LENGTH_LONG).show();
               FragmentTransaction fr= getFragmentManager().beginTransaction();
                fr.replace(R.id.main_container, new ShowObservationDataRecordingFragment()).addToBackStack("ObservationselectattributeFragment");
                fr.commit();
            }
        });
        mDBHandler = new DatabaseHandler(this.getActivity());
        mCsr = mDBHandler.getAllRecords();
        // Prepare a list of the columns to get the data from, for the ListViewt
        String[] columns_to_get_data_from = new String[]{
                DatabaseHandler.KEY_IDS,
                DatabaseHandler.KEY_NAMES,
                DatabaseHandler.KEY_FNAME,
                DatabaseHandler.KEY_MONAME
        };

        // Prepare a list of the Views into which to place the data
        int[] itemviews_to_place_data_in = new int[]{
                R.id.euserid,
                R.id.eusername,
                R.id.efname,
                R.id.emoname
        };

        // get and instance of SimpleCursorAdapter
        mSCA = new SimpleCursorAdapter(this.getActivity(),
                R.layout.listviewitem_record,
                mCsr,
                columns_to_get_data_from,
                itemviews_to_place_data_in,
                0);
        // get and instance of SimpleCursorAdapter the listviewitem_record layout
        mListView.setAdapter(mSCA);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String attributeItem = ((TextView)view).getText().toString();
                if(attributeItems.contains(attributeItem)){
                    attributeItems.remove(attributeItem);//uncheck item
                }
                else
                {
                    attributeItems.add(attributeItem);
                }


            }
        });

        ((HomeActivity) getActivity())
                .setActionBarTitle("Select Attribute");
        return view;
    }

}

2.    selectattributefragment.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.akmu_11.aicrpreporter.ObservationselectattributeFragment">

    <ListView
        android:id="@+id/lv001"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
    </ListView>
    <Button
        android:id="@+id/addattribute"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="20dp"
        android:background="@color/colorPrimary"
        android:text="Add Attribute"
        android:textAllCaps="false"
        android:textColor="@color/backgroundcolor"
        android:textSize="22dp" />


</LinearLayout>

3.    DatabaseHandler.java


public class DatabaseHandler extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    public static final String DATABASE_NAME = "aicrpmain";

    // Labels table name
    public static final String TABLE_LABELS = "labels";
    public static final String TABLE_RECORDS = "Records";
    // Labels Table Columns names
    public static final String KEY_ID = "id";
    public static final String KEY_NAME = "name";
    public static final String KEY_IDS = "_id";
    public static final String KEY_NAMES = "names";
    public static final String KEY_FNAME = "fname";
    public static final String KEY_MONAME = "moname";
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        // Category table create query
        String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
        db.execSQL(CREATE_CATEGORIES_TABLE);
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " +
                TABLE_RECORDS +
                "(" +
                KEY_IDS + " INTEGER PRIMARY KEY," +
                KEY_NAMES + " TEXT," + KEY_FNAME + " TEXT," + KEY_MONAME + " TEXT)";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECORDS);

        // Create tables again
        onCreate(db);
    }

    /**
     * Inserting new lable into lables table
     * */
    /*public void insertLabel(String label){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, label);

        // Inserting Row
        db.insert(TABLE_LABELS, null, values);
        db.close(); // Closing database connection
    }*/

    /**
     * Getting all labels
     * returns list of labels
     * */
    public List<String> getAllLabels(){
        List<String> labels = new ArrayList<String>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_LABELS;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                labels.add(cursor.getString(1));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning lables
        return labels;
    }
    public List<String> getAllItems(){
        List<String> dataitems = new ArrayList<String>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_LABELS;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                dataitems.add(cursor.getString(0));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning lables
        return dataitems;
    }
    public Cursor getAllRecords() {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.query(TABLE_RECORDS,null,null,null,null,null,null);
    }


4.     listviewitem_record.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="110dp"
        android:layout_weight="8"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="Id"
        android:textStyle="bold"
        />
    <TextView
        android:layout_width="110dp"
        android:layout_weight="10"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="Name"
        android:textStyle="bold"
        />
    <TextView
        android:layout_width="110dp"
        android:layout_weight="10"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="Fname"
        android:textStyle="bold"/>
    <TextView
        android:layout_width="110dp"
        android:layout_weight="10"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="Moname"
        android:textStyle="bold"/>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_marginTop="-110dp">
    <TextView
        android:id="@+id/euserid"
        android:layout_width="110dp"
        android:layout_weight="8"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"/>
    <TextView
        android:id="@+id/eusername"
        android:layout_width="110dp"
        android:layout_weight="10"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"/>
    <TextView
        android:id="@+id/efname"
        android:layout_width="110dp"
        android:layout_weight="10"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"/>
    <TextView
        android:id="@+id/emoname"
        android:layout_width="110dp"
        android:layout_weight="10"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"/>

</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="-80dp"
        android:layout_marginLeft="300dp"
        >
    <CheckBox
        android:id="@+id/record_checkbox"
        android:layout_width="110dp"
        android:layout_weight="2"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:focusable="false"
        />
    </LinearLayout>

</LinearLayout>
...