0

I've a gridview which displays images and text from web service using pojo. I want to add an image (with no text) before all the other images (as 1st item). This image should be available even when there are no images from web service i.e. if server database has no images.

GridView Adapter

public class GridViewAdapter extends ArrayAdapter<GridItem> {

    private Context mContext;
    private int resource;
    private ArrayList<GridItem> mGridData = new ArrayList<GridItem>();

    public GridViewAdapter(Context mContext, int resource, ArrayList<GridItem> mGridData) {
        super(mContext, resource, mGridData);
        this.resource = resource;
        this.mContext = mContext;
        this.mGridData = mGridData;
    }

    public void setGridData(ArrayList<GridItem> mGridData) {
        this.mGridData = mGridData;
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        ViewHolder holder = null;
        if (v == null) {

            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
            v = inflater.inflate(resource, parent, false);
            holder = new ViewHolder();

            holder.image = (ImageView) v.findViewById(R.id.item_image);
            holder.date = (TextView) v.findViewById(R.id.item_date);
            holder.month = (TextView) v.findViewById(R.id.item_month);

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

        }

        GridItem item = mGridData.get(position);

        Picasso
                .with(mContext)
                .load(item.getImage())
                .placeholder(R.drawable.placeholder)
                .fit()
                .into(holder.image);

        holder.date.setText(item.getDate());
        holder.month.setText(item.getMonth());

        return v;
    }

    class ViewHolder {
        ImageView image;
        TextView date;
        TextView month;
    }

}
POJO

public class GridItem {

    private String textDateUrls, textMonthUrls;
    private String imageUrls;

    public GridItem() {
        super();
    }

    public String getImage() {
        return imageUrls;
    }

    public void setImage(String imageUrls) {
        this.imageUrls = imageUrls;
    }

    public String getDate() {
        return textDateUrls;
    }

    public void setDate(String textDateUrls) {
        this.textDateUrls = textDateUrls;
    }

    public String getMonth() {
        return textMonthUrls;
    }

    public void setMonth(String textMonthUrls) {
        this.textMonthUrls = textMonthUrls;
    }

}
Main Activity

public class MainActivity extends AppCompatActivity {

    private GridView mGridView;
    private GridItem newItem;
    private GridViewAdapter mGridAdapter;
    private ArrayList<GridItem> mGridData;
    public static final String KEY_USERID = "user_id";
    private static final String REGISTER_URL = "http://staging.techunits.com/android_login_api/Services.php?action=fetchUserLog";


    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mGridView = (GridView)findViewById(R.id.gridView);
        registerUser();

        mGridData = new ArrayList<>();
        mGridAdapter = new GridViewAdapter(this, R.layout.profile_gridview_item, mGridData);
        mGridView.setAdapter(mGridAdapter);
        newItem = new GridItem();
        String imageUri = "drawable://" + R.mipmap.ic_add;
        //mGridData.add(0, newItem);


    }


    private void registerUser(){

        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jObj = new JSONObject(response);
                            String status = jObj.getString("status");

                            // Now check status value
                            if (status.equals("0")) {

                                Toast.makeText(getApplicationContext(), "There was some error! Please try again.", Toast.LENGTH_LONG).show();

                            }else if(status.equals("1")){

                                mGridAdapter.setGridData(mGridData);

                                JSONArray result = jObj.getJSONArray("results");
                                GridItem item;
                                for(int i = 0 ; i <result.length() ; i++){
                                    JSONObject json_data = result.getJSONObject(i);

                                    String image = json_data.getString("images");
                                    String date = json_data.getString("date");

                                    item = new GridItem();
                                    item.setImage(image);
                                    item.setDate(date);
                                    mGridData.add(item);
                                }





                            } else {
                                // Error in login. Get the error message
                                String errorMsg = jObj.getString("error_msg");
                                Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            // JSON error
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }



                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put(KEY_USERID, "21");
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }




}
Sam
  • 49
  • 1
  • 8
  • If you are writing the code from scratch I would strongly suggest using `RecyclerView` instead of listview. This would be simple to achieve in `RecyclerView`. – Shubham Feb 17 '16 at 08:59
  • How to add image at 0 position in Recyclerview? @Shubham – Sam Feb 17 '16 at 09:05
  • Please go through the documentation of `RecyclerView`. You will need to use two custom views for that. A word of warning: Recycler does not provide with header, footer and item click listeners. You need to implement all these yourself. But once you understand and implement it the first time, things are fairly easy. – Shubham Feb 17 '16 at 09:10

1 Answers1

0

There is simple hack to achieve this. Create a dummy GridItem like this:

String myPermanentUri = "your_uri_here";
GridItem myPermanentGridItem = new GridItem();
myPermanentGridItem.setImage(myPermanentUri);
//Initialize other properties as well
myPermanentGridItem.setDate("");
myPermanentGridItem.setMonth("");

Now add this to your list irrespective of the fact whether you are getting anythign from your server or not.

ArrayList<GridItem> mGridItems = getFromServer(); //Just modify the implementation as per your code
if(mGridItems == null){
  mGridItems = new ArrayList<>();
}
mGridItems.add(0, myPermanentGridItem);

Now pass this to your adapter. Let me know if you have any queries.

UPDATE:

You can change your getView method to use another layout if position == 0. e.g.:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    ViewHolder holder = null;
    if (v == null) {

        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();

        if(position == 0){
          resource = R.layout.my_permanent_item_layout;
        }

        v = inflater.inflate(resource, parent, false);
        holder = new ViewHolder();

        //Modify this code accordingly
        holder.image = (ImageView) v.findViewById(R.id.item_image);
        holder.date = (TextView) v.findViewById(R.id.item_date);
        holder.month = (TextView) v.findViewById(R.id.item_month);

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

    //Rest of the code

UPDATE 2:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    ViewHolder holder = null;
    if (v == null) {

        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();

        v = inflater.inflate(resource, parent, false);
        holder = new ViewHolder();

        holder.image = (ImageView) v.findViewById(R.id.item_image);
        holder.date = (TextView) v.findViewById(R.id.item_date);
        holder.month = (TextView) v.findViewById(R.id.item_month);

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

    //Rest of the code
    if(position == 0){
         holder.date.setVisibility(View.GONE);
         holder.month.setVisibility(View.GONE);
    }else{
         holder.date.setVisibility(View.VISIBLE);
         holder.month.setVisibility(View.VISIBLE);
         //Set the values:
         holder.date.setText("your_value");
         holder.month.setText("your_value");
    }
avin
  • 459
  • 5
  • 14
  • Thanks for the reply. There is one prob. "Cannot resolve insertAt()" @Wanted – Sam Feb 17 '16 at 07:44
  • My bad, use mGridItems.add(0, myPermanentGridItem); Will modify the answer as well – avin Feb 17 '16 at 07:46
  • Yes. I figured it out. – Sam Feb 17 '16 at 07:46
  • Glad it helped. If this solved your problem, can you please mark it as the accepted answer? – avin Feb 17 '16 at 07:47
  • Its working but its using the custom layout I added for other images. But it has some background drawable that I don't want. – Sam Feb 17 '16 at 07:50
  • So, you dont want to use "profile_gridview_item" for your first item? – avin Feb 17 '16 at 07:54
  • Yes. The first item will not be like those images from server. There won't be any text. It will only have an image which will act as button on clicked. – Sam Feb 17 '16 at 07:57
  • I've updated the answer - way to use another layout for the first item. btw, since we are setting the following parameters: myPermanentGridItem.setDate(""); myPermanentGridItem.setMonth(""); The text should not come even in your previous implementation. But it totally depends on the layout you are using. – avin Feb 17 '16 at 08:02
  • NullPointerException GridViewAdapter.getView – Sam Feb 17 '16 at 08:10
  • Can you please post your layout file as well. Also your code. – avin Feb 17 '16 at 08:16
  • You need to put a null check in your getview, since the pos==0 itemview doesn't have the respective textviews. So, holder.itemdate and holder.itemmonth will return null.. Please refer to http://hastebin.com/userezosil.avrasm and modify the code similarly in all the respective places. – avin Feb 17 '16 at 08:34
  • I don't know why but now each cell's text is empty like they are using second layout meant for position 0. – Sam Feb 17 '16 at 08:47
  • Ok, no need to complicate things. Keep two views in your original item layout file. And toggle it depending upon the position. Or just toggle the visiblity of the textviews in case of the pos == 0. Will update the answer as well – avin Feb 17 '16 at 08:50