lundi 7 décembre 2015

Images from SQlite database not dislplayed

I want to display images and its title in a gridview. I am getting these images from URL. each image has a different URL. First I am storing these images and title in database and then retrieving it. The titles are displayed inn grid view but not the images. I have columns in each row of grid view. Every row has same titles in grid view items. i.e first row grid elements shows Example1, Example1 and Example1. And the second row shows Example2 Example2 Example2. This is my code where I am storing Images

  @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        try {

        HttpClient httpClient = new DefaultHttpClient();
        String url = Config.CITIESCATEGORIES;
        HttpPost httpRequest = new HttpPost(url);

        httpRequest.setHeader("Content-Type", "application/json");

        JSONObject json = new JSONObject();

            StringEntity se = new StringEntity(json.toString());
            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");
            httpRequest.setEntity(se);
            HttpResponse httpRes = httpClient.execute(httpRequest);
            java.io.InputStream inputStream = httpRes.getEntity()
                    .getContent();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream);
            BufferedReader reader = new BufferedReader(inputStreamReader);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            inputStream.close();
            strServerResponse = sb.toString();
            Log.e("Server Response", "" + strServerResponse.toString());
            if (strServerResponse != null) {

                List<String> listTem = cityal;
                List<String> listTemId = cityalid;

                Set<String> tem = new HashSet<String>(listTem);
                Set<String> temid = new HashSet<String>(listTemId);
                SharedPreferences.Editor editr = getSharedPreferences("City", MODE_PRIVATE).edit();
                tem.addAll(listTem);
                temid.addAll(listTemId);
                editr.putStringSet("cityname", tem);
                editr.putStringSet("cityid", temid);
                editr.commit();

                JSONArray ff = new JSONArray(objCategory);

                Bitmap bitmap=null;
                for (int j=0; j < ff.length(); j++){
                    pojo = new Pojo();
                    JSONObject jobj3 = ff.getJSONObject(j);
                    String catId = jobj3.optString("id");
                    String imagename = jobj3.optString("image");
                    String catname = jobj3.optString("name");

                    // for adding in database

                    URL urll = new URL(Config.BASEURL+""+"/"+""+imagename);
                    Log.e("Main activityt url", ""+urll);
                    HttpURLConnection connection = (HttpURLConnection) urll.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream is = connection.getInputStream();
                    // Decode image to get smaller image to save memory
                    final BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = false;
                    options.inSampleSize=4;
                    bitmap = BitmapFactory.decodeStream(is,null, options);
                    is.close();

                    db = new DataHelper(MainActivity.this);
                    // convert bitmap to byte
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    Log.e("After byte array","fgdgfd");
                   // bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                    byte imageInByte[] = stream.toByteArray();
                    Log.e("Insert: ", "Inserting ..");
                    db.addContact(new Categories(""+catname, imageInByte,""+catId));

                }

                List<Categories> contacts = db.getAllContacts();
                Log.e("After list","fgdgfd");
                for (Categories cn : contacts) {
                    String log = "ID:" + cn.getID() + " Name: " + cn.getName()
                            + " ,Image: " + cn.getImage();
                    // Writing Contacts to log
                    imageArry.add(cn);
                }

            } else {
               Log.e("ServiceHandler",
                        "Couldn't get any data from the url");
           }

In postExecute()

   adapter = new CategoriesAdapter(MainActivity.this, R.layout.grid_item,
                imageArry);
   gridview.setAdapter(adapter);

CategoriesAdapter

 public class CategoriesAdapter extends ArrayAdapter<Categories>{
Context context;
int layoutResourceId;
ArrayList<Categories> data=new ArrayList<Categories>();
public CategoriesAdapter(Context context, int layoutResourceId, ArrayList<Categories> data) {
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    ImageHolder holder = null;
    if(row == null)
    {
        LayoutInflater inflater = ((Activity)context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ImageHolder();
        holder.txtTitle = (TextView)row.findViewById(R.id.textView);
        holder.imgIcon = (ImageView)row.findViewById(R.id.imageView);
        row.setTag(holder);
    }
    else
    {
        holder = (ImageHolder)row.getTag();
    }
    Categories picture = data.get(position);
    holder.txtTitle.setText(picture ._name);
//convert byte to bitmap take from contact class
    byte[] outImage=picture._image;
    ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
    Bitmap theImage = BitmapFactory.decodeStream(imageStream);
    holder.imgIcon.setImageBitmap(theImage);
    return row;
}
static class ImageHolder
{
    ImageView imgIcon;
    TextView txtTitle;
}
}

DataHelper class

 public class DataHelper extends SQLiteOpenHelper {
 private static final int DATABASE_VERSION = 1;
 private static final String DATABASE_NAME = "catdb";
 private static final String TABLE_CATEGORIES = "categories";
 private static final String KEY_ID = "id";
 private static final String KEY_NAME = "name";
 private static final String KEY_IMAGE = "image";
 private static final String KEY_CAT_ID = "catid";

 public DataHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
 }

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CATEGORIES + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_IMAGE + " BLOB," +
            KEY_CAT_ID + " TEXT"+ ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)     {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORIES);
    onCreate(db);
}

public void addContact(Categories categories) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, categories._name); 
    values.put(KEY_IMAGE, categories._image);
    values.put(KEY_CAT_ID, categories.cat_id);
    db.insert(TABLE_CATEGORIES, null, values);
    db.close(); // Closing database connection
}

public List<Categories> getAllContacts() {
    List<Categories> contactList = new ArrayList<Categories>();
    String selectQuery = "SELECT * FROM categories ORDER BY name";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            Categories contact = new Categories();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setImage(cursor.getBlob(2));
            contact.setCatId(cursor.getString(1));
            contactList.add(contact);
        } while (cursor.moveToNext());
    }
    db.close();
    return contactList;
}
}

Please help me how to do this...

Aucun commentaire:

Enregistrer un commentaire