EditText in GridView : How to get value from Multiple EditText

耗尽温柔 提交于 2020-01-09 23:55:24

问题


I have created GridView using following XML code:

grid_layout.xml

<GridView
    android:id="@+id/productList"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="5dp"
    android:layout_marginBottom="10dp"
    android:drawSelectorOnTop="true"
    android:fastScrollEnabled="true"
    android:horizontalSpacing="10dp"
    android:listSelector="@drawable/list_view_selector"
    android:numColumns="3"
    android:stretchMode="columnWidth"
    android:verticalSpacing="10dp" >
</GridView>

<!-- android:listSelector="@drawable/list_view_selector" is not affecting -->

and I have bind that GridView with following layout:

grid_inner_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/productChildView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="@drawable/login_bg"
    android:gravity="center"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/productImage"
        android:layout_width="100dp"
        android:layout_height="150dp"
        android:layout_alignLeft="@+id/productName"
        android:layout_alignRight="@+id/productName"
        android:contentDescription="@string/date_desc"
        android:src="@drawable/ic_date" />

    <TextView
        android:id="@+id/productName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/productImage"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:ellipsize="marquee"
        android:gravity="center_horizontal"
        android:singleLine="true"
        android:text="@string/product_name"
        android:textColor="@android:color/black"
        android:textSize="@dimen/list_item_text_size" />

    <LinearLayout
        android:id="@+id/productEditTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/productName" >

        <EditText
            android:id="@+id/productRateValue"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/edit_text_holo_light"
            android:gravity="right"
            android:hint="@string/hint_rate"
            android:inputType="number"
            android:nextFocusRight="@+id/productDiscountValue"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@android:color/black" >
        </EditText>

        <EditText
            android:id="@+id/productDiscountValue"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/edit_text_holo_light"
            android:gravity="right"
            android:hint="@string/hint_disc"
            android:inputType="number"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@android:color/black" />
    </LinearLayout>

    <EditText
        android:id="@+id/productQuantityValue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/productEditTextView"
        android:layout_marginRight="5dp"
        android:background="@drawable/edit_text_holo_light"
        android:gravity="right"
        android:hint="@string/hint_quantity"
        android:inputType="number"
        android:nextFocusRight="@+id/productRateValue"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/black" >

        <requestFocus />
    </EditText>

</RelativeLayout>

and i got finally this view:

my Adapter Class is like:

public class MyGridViewAdapter extends SimpleCursorAdapter {

    Cursor cursor;

    double productRateValue;
    double productDiscountValue;

    ImageLoader mImageLoader = new ImageLoader(context);

    public MyGridViewAdapter(Context context, int layout, Cursor c,
            String[] from, int[] to, int flags) {
        super(context, layout, c, from, to, flags);
        // TODO Auto-generated constructor stub
        //get reference to the row
        this.cursor = c;

    }

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) {  

        View view = convertView;  
        ViewHolder holder;

        if(convertView == null)
        {
            //get reference to the row
            view = super.getView(position, convertView, parent); 

            holder = new ViewHolder();

            productRateValue = cursor.getDouble(productCursor.getColumnIndex("rate"));
            productDiscountValue = cursor.getDouble(productCursor.getColumnIndex("discount"));

            //*** Image ***//
            holder.prodImage = (ImageView) view.findViewById(R.id.productImage);
            String path = productCursor.getString(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_IMAGES));
            mImageLoader.DisplayImage(path, holder.prodImage);

            holder.prodName = (TextView) view.findViewById(R.id.productName);
            holder.prodName.setText(productCursor.getString(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_NAME)));

            holder.prodQty = (EditText) view.findViewById(R.id.productQuantityValue);
            holder.prodQty.setText("");

            holder.prodRate = (EditText) view.findViewById(R.id.productRateValue);
            holder.prodRate.setText(String.valueOf(productRateValue));

            holder.prodDisc = (EditText) view.findViewById(R.id.productDiscountValue);
            holder.prodDisc.setText(String.valueOf(productDiscountValue));

            holder.prodRate.setFocusable(isRateEditable);
            holder.prodRate.setEnabled(isRateEditable);

            holder.prodDisc.setFocusable(isDiscountEditable);
            holder.prodDisc.setEnabled(isDiscountEditable);

            /* For set Focus on Next */
            if(isRateEditable)
                holder.prodQty.setNextFocusDownId(R.id.productRateValue);
            else if(isDiscountEditable)
                holder.prodQty.setNextFocusDownId(R.id.productDiscountValue);

            if(isDiscountEditable)
                holder.prodRate.setNextFocusDownId(R.id.productDiscountValue);

            holder.prodDisc.setNextFocusDownId(R.id.productQuantityValue);

            view.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) view.getTag();
        }

        return view;  
    }

    public class ViewHolder{
        ImageView prodImage;
        TextView prodName;  
        EditText prodRate;
        EditText prodQty;
        EditText prodDisc;
    }
}

Now my question is when I click on ORDER Tab, i want to save all the data in which "Quantity" is entered, i have override onPause() and onStop() method to call saveData() but what can i do in saveData() method

as per my view i want to create JSONObject and store all value as an Array of JSON.

Please Help...

Thanks in advance...


回答1:


Do this way..

JSONObject output = new JSONObject();

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View view = convertView;
    ViewHolder holder;

    if (convertView == null) {
        // get reference to the row
        view = super.getView(position, convertView, parent);

        holder = new ViewHolder();
        holder.prodImage = (ImageView) view.findViewById(R.id.productImage);
        holder.prodName = (TextView) view.findViewById(R.id.productName);
        holder.prodQty = (EditText) view.findViewById(R.id.productQuantityValue);
        holder.prodRate = (EditText) view.findViewById(R.id.productRateValue);
        holder.prodDisc = (EditText) view.findViewById(R.id.productDiscountValue);

        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    productRateValue = cursor.getDouble(productCursor.getColumnIndex("rate"));
    productDiscountValue = cursor.getDouble(productCursor.getColumnIndex("discount"));
    String path = productCursor.getString(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_IMAGES));
    mImageLoader.DisplayImage(path, holder.prodImage);

    holder.prodName.setText(productCursor.getString(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_NAME)));
    holder.prodQty.setText("");
    holder.prodRate.setText(String.valueOf(productRateValue));
    holder.prodDisc.setText(String.valueOf(productDiscountValue));
    holder.prodRate.setFocusable(isRateEditable);
    holder.prodRate.setEnabled(isRateEditable);
    holder.prodDisc.setFocusable(isDiscountEditable);
    holder.prodDisc.setEnabled(isDiscountEditable);

    /* For set Focus on Next */
    if (isRateEditable)
        holder.prodQty.setNextFocusDownId(R.id.productRateValue);
    else if (isDiscountEditable)
        holder.prodQty.setNextFocusDownId(R.id.productDiscountValue);

    if (isDiscountEditable)
        holder.prodRate.setNextFocusDownId(R.id.productDiscountValue);

    holder.prodDisc.setNextFocusDownId(R.id.productQuantityValue);
    holder.prodQty.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

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

        @Override
        public void afterTextChanged(Editable s) {
            output.put(productCursor.getString(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_NAME)),s);
        }
    });
    return view;
}

public class ViewHolder {
    ImageView prodImage;
    TextView prodName;
    EditText prodRate;
    EditText prodQty;
    EditText prodDisc;
}

you will get output jsonobject with prodname and it's entered qty here.




回答2:


With My Question i am success to save data in JSONArray but got Again This Problem

and Finally i found solution:

I have used BaseAdapter instead of SimpleCursorAdapter

MyGridViewAdapter.java

class MyGridViewAdapter extends BaseAdapter {

    private ArrayList<ProductItems> productItemList;
    private LayoutInflater inflater = null;

    ViewHolder holder;

    ImageLoader mImageLoader;

    int concatid;

    String productQtyValue;
    Double productRateValue;
    Double productDiscountValue;

    int tempId = 0;

    public MyGridViewAdapter(ArrayList<ProductItems> productItemsList) {
        // TODO Auto-generated constructor stub
        this.productItemList = productItemsList;
        mImageLoader = new ImageLoader(context);
        inflater =(LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View view = convertView;

        if(convertView == null)
        {
            view = inflater.inflate(R.layout.list_product_view, null);
            holder = new ViewHolder();

        }else
        {
            holder = (ViewHolder) view.getTag();
        }

        ProductItems currentProductItem = productItemList.get(position);

        holder.prodId = currentProductItem.getProdId();
        holder.prodImagePath = currentProductItem.getProdImagePath();
        holder.prodDesc = currentProductItem.getProdDesc();

        //Image
        holder.prodImage = (ImageView) view.findViewById(R.id.productImage);
        mImageLoader.DisplayImage(holder.prodImagePath, holder.prodImage);
        holder.prodImage.setTag(holder);

        holder.prodImage.setOnClickListener(new OnClickListener() {

            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                ViewHolder tempHolder = (ViewHolder)v.getTag();

                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
                alertDialog.setTitle(tempHolder.prodName.getText());
                LayoutInflater inflater = getActivity().getLayoutInflater();

                // Inflate and set the layout for the dialog
                // Pass null as the parent view because its going in the dialog
                // layout
                View view = inflater.inflate(R.layout.custom_image, null);

                ImageView image = (ImageView) view.findViewById(R.id.dialogImageView);
                mImageLoader.DisplayImage(tempHolder.prodImagePath, image);

                ((TextView)view.findViewById(R.id.dialogTextViewDesc)).setText(tempHolder.prodDesc);

                alertDialog.setView(view);

                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // here you can add functions
                        dialog.dismiss();
                    }
                });

                alertDialog.show();
            }
        });

        holder.prodName = (TextView) view.findViewById(R.id.productName);
        holder.prodName.setText(currentProductItem.getProdName());

        holder.prodQty = (EditText) view.findViewById(R.id.productQuantityValue);
        holder.prodQty.setTag(holder);

        holder.prodQty.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub
                if(!hasFocus)
                {
                    ViewHolder viewHolder = (ViewHolder) v.getTag();
                    saveData(viewHolder);
                }
            }
        });

        holder.prodRate = (EditText) view.findViewById(R.id.productRateValue);
        holder.prodRate.setTag(holder);

        holder.prodDisc = (EditText) view.findViewById(R.id.productDiscountValue);
        holder.prodDisc.setTag(holder);

        /** First check whether value of Saved product Array is >0 or not..*/
        Log.d("msg", "Saved Prod : "+allProductArray.length());
        if(allProductArray.length() <= 0)
        {
            productRateValue = currentProductItem.getProdRate();
            productDiscountValue = currentProductItem.getProdDisc();
        }

        /* Filling up value if previously entered... */
        for (int array = 0; array < allProductArray.length(); array++) {
            try {
                if(allProductArray.getJSONObject(array).getInt("prodid") == holder.prodId)
                {
                    productRateValue = allProductArray.getJSONObject(array).getDouble("rate");
                    productDiscountValue = allProductArray.getJSONObject(array).getDouble("discount");
                    productQtyValue = allProductArray.getJSONObject(array).getString("qty");
                    holder.prodQty.setText(String.valueOf(productQtyValue));
                    break;
                }else
                {
                    productRateValue = currentProductItem.getProdRate();
                    productDiscountValue = currentProductItem.getProdDisc();

                    holder.prodQty.setText("");
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                Log.e("msg", "JSON error in bindView : " + e.getMessage());
            }
        }

        //holder.prodQty.setText("");
        holder.prodRate.setText(String.valueOf(productRateValue));
        holder.prodDisc.setText(String.valueOf(productDiscountValue));

        holder.prodRate.setFocusable(isRateEditable);
        holder.prodRate.setEnabled(isRateEditable);

        holder.prodDisc.setFocusable(isDiscountEditable);
        holder.prodDisc.setEnabled(isDiscountEditable);

        // For set Focus on Next
        if(isRateEditable)
            holder.prodQty.setNextFocusDownId(R.id.productRateValue);
        else if(isDiscountEditable)
            holder.prodQty.setNextFocusDownId(R.id.productDiscountValue);

        if(isDiscountEditable)
            holder.prodRate.setNextFocusDownId(R.id.productDiscountValue);

        holder.prodDisc.setNextFocusDownId(R.id.productQuantityValue);

        int catid = currentProductItem.getProdId();
        concatid = Integer.parseInt(catid + "" + tempId++);

        Log.d("msg", "Inner Concat ID :"+concatid);

        view.setId(concatid);
        view.setTag(holder);

        return view;
    }

    public class ViewHolder{
        int prodId;
        String prodImagePath;
        String prodDesc;
        ImageView prodImage;
        TextView prodName;
        EditText prodRate;
        EditText prodQty;
        EditText prodDisc;
    }
}

I have converted Cursor in to ArrayList<ProductItems>:

if (!dbHelper.db.isOpen())
dbHelper.open();

productCursor = dbHelper.getProduct(companyid, categoryid, isDistributor);

//                  String[] cols = new String[] { DatabaseHelper.PRODUCT_IMAGES, DatabaseHelper.PRODUCT_NAME, "rate", "discount"};
//                  int[]   views = new int[] { R.id.productImage, R.id.productName, R.id.productRateValue, R.id.productDiscountValue};

Log.d("msg", "Count of Product : "+productCursor.getCount());

prodItemsArrayList.clear();

if (productCursor != null && productCursor.getCount() > 0) {

    ProductItems items;

    for(productCursor.moveToFirst(); !productCursor.isAfterLast(); productCursor.moveToNext())
    {
        items = new ProductItems();

        items.setProdId(productCursor.getInt(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_SERVER_ID)));
        items.setProdName(productCursor.getString(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_NAME)));
        items.setProdImagePath(productCursor.getString(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_IMAGES)));
        items.setProdQty("");
        items.setProdRate(productCursor.getDouble(productCursor.getColumnIndex("rate")));
        items.setProdDisc(productCursor.getDouble(productCursor.getColumnIndex("discount")));
        items.setProdDesc(productCursor.getString(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_DESC)).equals("null") ? "" : productCursor.getString(productCursor.getColumnIndex(DatabaseHelper.PRODUCT_DESC)));

        prodItemsArrayList.add(items);
    }

    //Now create an array adapter and set it to display using our row
    //passing cursor with zero rows and displaying error message
    adapter = new MyGridViewAdapter(prodItemsArrayList);
    adapter.notifyDataSetChanged();
    productTable.setAdapter(adapter);

    /* HIDE ERROR MSG */
    (view.findViewById(R.id.productIfNoAvailable)).setVisibility(View.GONE);
} else {
    /* SHOW ERROR MSG */
    (view.findViewById(R.id.productIfNoAvailable)).setVisibility(View.VISIBLE);
    adapter.notifyDataSetChanged();
    adapter.notifyDataSetInvalidated();
}

Any Suggestion would be Appreciated :)

Thanks...



来源:https://stackoverflow.com/questions/19196322/edittext-in-gridview-how-to-get-value-from-multiple-edittext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!