简体   繁体   中英

Android- Adding items to spinner from listview

I'm trying to add items from list-view into spinner.My first Activity contains list-view. I'm using button each time which is inserted a new row entry using SQLite database in my activities ListView and every row add in list-view properly. And another I have spinner in second Activity.

And I want to add each list_view items into spinner in second Activity.

This is my Product List Adapter class:

 public class Product_List_Adapter extends BaseAdapter
    {
        @SuppressWarnings("unused")
        private Context mContext;
        private ArrayList<String> Productid_ArrayList;
        private ArrayList<String> ProductName_ArrayList;
        private ArrayList<String> ProductDescription_ArrayList;


        public Product_List_Adapter(Context mContext,
                ArrayList<String> productid_ArrayList,
                ArrayList<String> productName_ArrayList,
                ArrayList<String> productDescription_ArrayList)
        {
            super();
            this.mContext = mContext;
            Productid_ArrayList = productid_ArrayList;
            ProductName_ArrayList = productName_ArrayList;
            ProductDescription_ArrayList = productDescription_ArrayList;
        }




        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return Productid_ArrayList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int pos, View child, ViewGroup parent) {
            // TODO Auto-generated method stub
            Holder mHolder;
            LayoutInflater layoutInflater;

            if(child == null)
            {
                layoutInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                child = layoutInflater .inflate(R.layout.define_products_listrow, null);
                mHolder = new Holder();
                mHolder.txt_product_id = (TextView)child.findViewById(R.id.txt_ProductId);
                mHolder.txt_product_name = (TextView)child.findViewById(R.id.txt_ProductName);
                mHolder.txt_product_description = (TextView)child.findViewById(R.id.txt_ProductDescr);

                child.setTag(mHolder);
            }
            else
            {
                mHolder = (Holder) child.getTag();
            }

            mHolder.txt_product_id.setText(Productid_ArrayList.get(pos));
            mHolder.txt_product_name.setText(ProductName_ArrayList.get(pos));
            mHolder.txt_product_description.setText(ProductDescription_ArrayList.get(pos));

            return child;
        }

        public class Holder {
            TextView txt_product_id;
            TextView txt_product_name;
            TextView txt_product_description;
        }
    }





The ProductDefine Sctivity which is contain Listview



public class DefineProducts_Activity6 extends Activity {

    String log;
    List<String> list_Dataset;
    String[] str_Splitup1;
    String[] str_Splitup2;
    String[] str_Splitup3;

    Product_List_Adapter disadpt;
    //public ArrayAdapter<String> adapter;

    private com.db_mgmt.DbHelper mHelper;
    private SQLiteDatabase dataBase;

    private static ArrayList<String> products_Id_ArrayList = new ArrayList<String>();
    private static ArrayList<String> products_Name_ArrayList = new ArrayList<String>();
    private static ArrayList<String> products_Details_ArrayList = new ArrayList<String>();

    private ListView products_List;
    private AlertDialog.Builder build;

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

        products_List = (ListView) findViewById(R.id.products_List);
        mHelper = new DbHelper(this);


        //add new record
        findViewById(R.id.btnAdd_DefineProduct).setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Intent i = new Intent(getApplicationContext(),
                        Add_Define_Product.class);

                i.putExtra("update", false);
                startActivity(i);

            }
        });


        //click to update data
        products_List.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {

                Intent i = new Intent(getApplicationContext(),
                        Add_Define_Product.class);
                i.putExtra("productsName", products_Name_ArrayList.get(arg2));
                i.putExtra("productsDetails", products_Details_ArrayList.get(arg2));
                i.putExtra("productsID", products_Id_ArrayList.get(arg2));
                i.putExtra("update", true);
                startActivity(i);

            }
        });


        //long click to delete data
        products_List.setOnItemLongClickListener(new OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    final int arg2, long arg3) {

                build = new AlertDialog.Builder(DefineProducts_Activity6.this);
                build.setTitle("Delete " + products_Name_ArrayList.get(arg2) + " "
                        + products_Details_ArrayList.get(arg2));
                build.setMessage("Do you want to delete ?");
                build.setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog,
                                    int which) {

                                Toast.makeText(
                                        getApplicationContext(),
                                        products_Name_ArrayList.get(arg2) + " "
                                                + products_Details_ArrayList.get(arg2)
                                                + " is deleted.", Toast.LENGTH_LONG).show();

                                dataBase.delete(
                                        DbHelper.TABLE_DEFINE_PRODUCT_NAME,
                                        DbHelper.KEY_ID + "="
                                                + products_Id_ArrayList.get(arg2), null);
                                displayData();
                                dialog.cancel();
                            }
                        });

                build.setNegativeButton("No",
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog,
                                    int which) {
                                dialog.cancel();
                            }
                        });
                AlertDialog alert = build.create();
                alert.show();

                return true;
            }
        });
    }



    @Override
    protected void onResume() {
        displayData();
        super.onResume();
    }

    /**
     * displays data from SQLite
     */
    private void displayData() {
        dataBase = mHelper.getWritableDatabase();
        Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
                + DbHelper.TABLE_DEFINE_PRODUCT_NAME, null);

        products_Id_ArrayList.clear();
        products_Name_ArrayList.clear();
        products_Details_ArrayList.clear();


        if (mCursor.moveToFirst()) 
        {
            do 
            {
                products_Id_ArrayList.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
                products_Name_ArrayList.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_PRODUCTS_NAME)));
                products_Details_ArrayList.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_PRODUCTS_DETAILS)));

            } while (mCursor.moveToNext());
        }


        SharedPreferences spdata =
            PreferenceManager.getDefaultSharedPreferences(this);
        String strDataSet1 = spdata.getString("LISTS_ID",",");
        String strDataSet2 = spdata.getString("LISTS_NAME", "");
        String strDataSet3 = spdata.getString("LISTS_Detail", "");


        Log.e(log,strDataSet1);
        Log.e(log,strDataSet2);
        Log.e(log,strDataSet3);

        list_Dataset = Arrays.asList(strDataSet1.split(","));
        list_Dataset = Arrays.asList(strDataSet3.split(","));
        list_Dataset = Arrays.asList(strDataSet2.split(","));

        str_Splitup1 = strDataSet1.split(",");
        str_Splitup2 = strDataSet2.split(",");
        str_Splitup3 = strDataSet3.split(",");


        List<String> items1 = Arrays.asList(strDataSet1.split(","));
        List<String> items2 = Arrays.asList(strDataSet2.split(","));
        List<String> items3 = Arrays.asList(strDataSet3.split(","));

        ArrayList<String> itemsarraylist = new ArrayList<String>();

        for (int j = 0; j < items2.size(); j++)
        {
            itemsarraylist.add(j, items2.get(j));

        }


disadpt = new Product_List_Adapter(DefineProducts_Activity6.this,products_Id_ArrayList, products_Name_ArrayList, products_Details_ArrayList);
        products_List.setAdapter(disadpt);
        disadpt.notifyDataSetChanged();
        mCursor.close();
    }



}

This is arrayList

ArrayList<HashMap<String, String>> rssItemList = new ArrayList<HashMap<String, String>>();  

This is asyncTask class

class loadStoreItems extends AsyncTask<String, Void, ArrayList<HashMap<String, String>>> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        rssItemList.clear();
    }

    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(
            String... args) {
        // updating UI from Background Thread
        FeedDBHandler rssDb = new FeedDBHandler(getApplicationContext());

        // listing all RSSItems from SQLite
        List<RSSItem> rssList = rssDb.getAllItems();

        // loop through each RSSItem
        for (int i = 0; i < rssList.size(); i++) {

            RSSItem s = rssList.get(i);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value

            map.put(TAG_TITLE, s.getTitle());
            map.put(TAG_LINK, s.getLink());
            map.put(TAG_CATEGORY, s.getCategory());
            map.put(TAG_DESRIPTION, s.getDescription());
            map.put(TAG_PUB_DATE, s.getPubdate());
            // adding HashList to ArrayList
            rssItemList.add(map);

        }
        return rssItemList;
    }

This can be helpful to you.

You can go through this code.

Add content to ListView and then use the onItemClickListener for each ListItem Value. You can achieve your goal by below code.

Use this for your global variable instead of string array

Global Class

    class GlobalClass extends Application {
    public static List<String> myVal = new ArrayList<String>() ;
    }

HomeActivity

OnItemClickListener

    listView.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {

         String clickedvalue =(String) parent.getItemAtPosition(position); 
         myVal.add(clickedvalue);

         }
    }); 
}

Now All Clicked Values will be in your ListArray.

and then you can send it to via ..

    intent.putParcelableArrayListExtra( "addresses", addyExtras );

I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM