2

I am using custom GridView inside ScrollView. I know it is not the right way. I do not have any other way to accomplished my app layout.

I am trying to get item id == row_id of database in GridView but it does not return right id. Instead of giving row_id it gives me position id of item that does not match with database row_id I know position id is row_id in Adapter, I do not know why id is not matching with database.

Here is GridView I used on layout

 <info.androidhive.slidingmenu.MyGridView
    android:id="@+id/gridview11"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="278dp"
    android:numColumns="2"
    android:verticalSpacing="2dp"
    android:horizontalSpacing="0dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    android:isScrollContainer="false"
    android:focusable="false"
    android:focusableInTouchMode="false"
 />

Here is Custom MyGridview code. I used this from Github

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.GridView;

/**
 * ScrollViewの中のGridViewでも高さを可変にする<br>
 * https://stackoverflow.com/questions/8481844/gridview-height-gets-cut
 */
public class MyGridView extends GridView
{

    boolean expanded = false;

    public MyGridView(Context context)
    {
        super(context);
    }

    public MyGridView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public MyGridView(Context context, AttributeSet attrs,
                                    int defStyle)
    {
        super(context, attrs, defStyle);
    }

    public boolean isExpanded()
    {
        return expanded;
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        // HACK! TAKE THAT ANDROID!
        if (isExpanded())
        {
            // Calculate entire height by providing a very large height hint.
            // View.MEASURED_SIZE_MASK represents the largest height possible.
            int expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK,
                    MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);

            ViewGroup.LayoutParams params = getLayoutParams();
            params.height = getMeasuredHeight();
        }
        else
        {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    public void setExpanded(boolean expanded)
    {
        this.expanded = expanded;
    }
}

Finally here is onlcikListener code that does not work properly

 try {
            // OnClick

            best_product_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    //get position index of item here.

                    String indexid = String.valueOf(position);
                    Log.d("Index of Selected ", indexid);

                    // calling function
                     globalVariable.product_id =  position;
                    ((MainActivity)getActivity()).product();

                }
            });

    } 
    catch (Exception e)
    {
      Log.d("Error BestPrduct View","" + e);
    }

Here is Adapter class

package info.androidhive.slidingmenu.AdpaterClass;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;

import info.androidhive.slidingmenu.R;
import info.androidhive.slidingmenu.library.Function_List;
import info.androidhive.slidingmenu.library.Global_JsonTags;
import info.androidhive.slidingmenu.library.Global_Variable;

/**
 * Created by clint19 on 1/21/2016.
 */
public class Best_Product extends BaseAdapter {
    View gridView;
    private Context context;
  /*  private DisplayImageOptions options;*/

    private LayoutInflater inflater;

    // josn vaules from json file library
    Global_JsonTags jsontags = new Global_JsonTags();
    Function_List lib_function =  new Function_List();
    Global_Variable globalVariable = new Global_Variable();
    private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

    public Best_Product(Context c,ArrayList<HashMap<String, String>> json_value) {
        // TODO Auto-generated method stub
        context = c;
        MyArr = json_value;

    }

    public int getCount() {
        // TODO Auto-generated method stub
        Log.d("size of item", "" + MyArr.size());
        return MyArr.size();
    }

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

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

    }


    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        View view = convertView;
        TextView product_name;
        TextView product_price;
        ImageView imageView;
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View gridView;
        if (view == null) {
            view = new View(context);
            view = inflater.inflate(R.layout.home_best_collection, parent, false);
            holder = new ViewHolder();
            assert view != null;
            imageView = (ImageView) view.findViewById(R.id.imageView26);
           // holder.imageView = (ImageView) view.findViewById(R.id.imageView26);
            holder.progressBar = (ProgressBar) view.findViewById(R.id.progress);
            product_name = (TextView) view.findViewById(R.id.textView21);
            product_price = (TextView) view.findViewById(R.id.textView23);

            String name = MyArr.get(position).get("product_name");
            int namelength = name.length();
            if(namelength >= 33)
            {
                product_name.setText(MyArr.get(position).get("product_name").substring(0, 29) + "...");
            }
            else{product_name.setText(MyArr.get(position).get("product_name"));}
            product_price.setText(MyArr.get(position).get("product_price"));
            String product_status = MyArr.get(position).get("product_status");

            if(product_status.equals("false"))
            {

                Button add_to_cart = (Button) view.findViewById(R.id.add_to_cart1);
                add_to_cart.setVisibility(View.GONE);
                View background_height = (View) view.findViewById(R.id.bestproduct1);
            }
            else
            {
                Button add_to_cart = (Button) view.findViewById(R.id.add_to_cart1);
                add_to_cart.setVisibility(View.VISIBLE);
            }
            Log.d("setting up text", "setting up text");

            Picasso.with(context)
                    .load(MyArr.get(position).get("product_image"))
                    .placeholder(R.drawable.ic_stub) // optional
                    .error(R.drawable.ic_error)         // optional
                    .into(imageView);

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


        return view;
    }


    static class ViewHolder {
        ImageView imageView;
        ProgressBar progressBar;
    }

}

I am trying to get id from 2 hour but no luck. I followed these question How to add gridview setOnItemClickListener and Android gridview OnItemClickListener and this one Get ID of View in GridView and may more.

Can anyone tell me what is wrong.

Community
  • 1
  • 1
Ashu Kumar
  • 832
  • 19
  • 38

3 Answers3

2

i m trying to get item id == row_id of database of GridView but it does not right id

That's because you didn't properly override getItemId in your Adapter. Assuming that the dataset you feeding the adapter with, is made of bean classes, what you will have to do is to override getItemId(int position), which returns a long, and let it return the correct id. E.g.

@Override
public long getItemId(int position) {
   return getItem(position).getId();
}

the correct value is passed as last parameter, long id, in onItemClick.

If you are subclassing the CursorAdapter(or one its concrete implementations), and you should, since you have a cursor based solution, you don't need to override it. The CursorAdapter already returns value of the _id columns of the cursor at position.

Edit

@Override
public long getItemId(int position) {
   HashMap<String, String> mapAtPostion = MyArr.get(position);
   return Long.valueOf(mapAtPostion.get("product_id"));
}
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
1

You are getting position of the item because that is what you are returning from your method getItemId. You need to return the database row_id from that method.

Change your method like this

@Override
public long getItemId(int position) {
   return Long.valueOf(MyArr.get(position).get("product_id"));
}
Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
-1
@Override
public long getItemId(int position) {

    return position;
}

CustmeAdapter Example

public class CustomAdapter extends BaseAdapter{

String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
    // TODO Auto-generated constructor stub
    result=prgmNameList;
    context=mainActivity;
    imageId=prgmImages;
     inflater = ( LayoutInflater )context.
             getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

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

@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;
}

public class Holder
{
    TextView tv;
    ImageView img;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    Holder holder=new Holder();
    View rowView;

         rowView = inflater.inflate(R.layout.program_list, null);
         holder.tv=(TextView) rowView.findViewById(R.id.textView1);
         holder.img=(ImageView) rowView.findViewById(R.id.imageView1);

     holder.tv.setText(result[position]);
     holder.img.setImageResource(imageId[position]);

     rowView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
        }
    });

    return rowView;
}

}

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
Ajay Keshri
  • 97
  • 1
  • 8