如何在gridview中显示数据库提取的数据?

时间:2013-11-15 11:42:03

标签: android

我想通过从数据库中获取数据来显示网格视图中的数据(图像和文本)。我想首先在数据库表中插入数据并尝试从数据库中获取数据并在gridview中显示它。

这是我的主要活动

    public class MainActivity extends Activity {

        private RelativeLayout rl;

        private Tab TabOrder;



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


            rl = (RelativeLayout) findViewById(R.id.mainLayout);

            ActionBar actionbar = getActionBar();
            actionbar.setTitle("Select To Order");
            actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

            TabOrder = actionbar.newTab().setText("ORDER");


            Fragment FragmentOrder = new FragmentOrder();

            TabOrder.setTabListener(new MyTablistenerClass(FragmentOrder));

            actionbar.addTab(TabOrder);

        }

        @SuppressLint("ValidFragment")
        public class FragmentOrder extends Fragment{


            private Context context;
            private int layoutResourceId;
            private ArrayList<Category> data;
            ArrayList<Category> imageArry = new ArrayList<Category>();
            OrderAdapter adapter;
            private ArrayList<Category> categories;


            @SuppressLint("NewApi")
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
                View view = inflater.inflate(R.layout.griddeal, null);




                DatabaseManager db = new DatabaseManager(MainActivity.this);
                // get image from drawable
    //          Bitmap image = BitmapFactory.decodeResource(getResources(),
    //                  R.drawable.car);
    //
    //          // convert bitmap to byte
    //          ByteArrayOutputStream stream = new ByteArrayOutputStream();
    //          image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    //          byte imageInByte[] = stream.toByteArray();
                /**
                 * CRUD Operations
                 * */
                // Inserting Contacts
                Log.d("Insert: ", "Inserting ..");


                Category c1 = new Category();
                c1.setCategorydescription("vegetables");


                Bitmap image = BitmapFactory.decodeResource(getResources(),
                        R.drawable.car);

                // convert bitmap to byte
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte imageInByte[] = stream.toByteArray();
                db.insertCategoriesDetail(c1);
                //db.insertCategoriesDetail(new Category("Vegetables", imageInByte));
                // display main List view bcard and contact name

                // Reading all contacts from database
                List<Category> categories = db.getCategoriesDetail();
                for (Category cn : categories) {
                    String log = "ID:" + cn.getId() + " Name: " + cn.getCategorydescription()
                            + " ,Image: " + cn.getCategoryimage();

                    // Writing Contacts to log
                    Log.d("Result: ", log);
                    //add contacts data in arrayList
                    imageArry.add(cn);

                }
                adapter = new  OrderAdapter(MainActivity.this, R.layout.griddealitems,
                        imageArry);
                GridView dataList = (GridView) findViewById(R.id.GridDeal);
                dataList.setAdapter(adapter);

                dataList.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                            int arg2, long arg3) {
                        // TODO Auto-generated method stub

                    }
                });
                return view;
            }
        }

        public class OrderAdapter extends ArrayAdapter<Category>{
              Context context;
                int layoutResourceId;   
               // BcardImage data[] = null;
                ArrayList<Category> data=new ArrayList<Category>();

                public OrderAdapter(Context context, int layoutResourceId, ArrayList<Category> data) {
                    // TODO Auto-generated constructor stub
                    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.grid_deal_text = (TextView)row.findViewById(R.id.grid_deal_text);
                        holder.imgIcon = (ImageView)row.findViewById(R.id.grid_deal_image);
                        row.setTag(holder);
                    }
                    else
                    {
                        holder = (ImageHolder)row.getTag();
                    }

                    Category picture = data.get(position);
                    holder.grid_deal_text.setText(picture.categorydescription);
                    //convert byte to bitmap take from contact class

                    byte[] outImage=picture.categoryimage;
                    ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
                    Bitmap theImage = BitmapFactory.decodeStream(imageStream);
                    holder.imgIcon.setImageBitmap(theImage);
                   return row;

                }

                public class ImageHolder
                {
                    ImageView imgIcon;
                    TextView grid_deal_text;
                }
        }


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }



        public class MyTablistenerClass implements android.app.ActionBar.TabListener {

            Fragment fragment1;

            @SuppressLint("NewApi")
            public MyTablistenerClass(Fragment fragment){
                this.fragment1 = fragment;
            }


            @Override
            public void onTabReselected(Tab tab, FragmentTransaction ft) {
                // TODO Auto-generated method stub

            }
            @SuppressLint("NewApi")
            @Override
            public void onTabSelected(Tab tab, FragmentTransaction ft) {
                // TODO Auto-generated method stub


                FragmentTransaction fragMentTra;


                    ActionBar actionBar = getActionBar();
                    actionBar.show();
                    actionBar.setTitle("Select Category");

                    //actionBar.setIcon(R.id.search);
                    FragmentOrder Fram2 = new FragmentOrder();
                    //fragMentTra.addToBackStack(null);
                    fragMentTra = getFragmentManager().beginTransaction();
                    fragMentTra.add(rl.getId(), Fram2);
                    fragMentTra.commit();


            }

            @Override
            public void onTabUnselected(Tab tab, FragmentTransaction ft) {

            }

        }

    }

这是我的databaseManager类:

    public class DatabaseManager {

        private Context context = null;
        private SQLiteDatabase database=null;
        private DatabaseHelper dbHelper=null;


        public DatabaseManager(Context context) {
            this.context = context;
            dbHelper = new DatabaseHelper(context);
        }

        public void open() throws SQLException {
            if (dbHelper==null) {
                dbHelper = new DatabaseHelper(context);
            }
            if (database==null) {
                database = dbHelper.getWritableDatabase();
            }
        }

        public void close() {
            dbHelper.close();
            database = null;
            dbHelper = null;       
        }   

        public long insertCategoriesDetail(Category categorydetail){

            long result = 0;

            try{

                if (database==null) {
                    open();
                }
                ContentValues values = new ContentValues();
                values.put(DatabaseContract.RetailDatabaseEntry.COLUMN_CATEGORYDESCRIPTION, categorydetail.getCategorydescription());
                values.put(DatabaseContract.RetailDatabaseEntry.COLUMN_CATEGORYIMAGE, categorydetail.getCategoryimage());

                result = database.insert(DatabaseContract.RetailDatabaseEntry.TABLE_NAME_CATEGORY, null, values);
                Toast.makeText(context, "Res : " + result, Toast.LENGTH_SHORT).show();
                close();
            }catch(Exception ex){
                Toast.makeText(context, "crashed" + ex.toString(), Toast.LENGTH_SHORT).show();

            }

            return result;

        }   


        public List<Category> getCategoriesDetail() {

            if (database==null) {
                open();
            }

            List<Category> categoriesdetailsList = new ArrayList<Category>();
            // Select All Query
            String selectQuery = "SELECT  * FROM " + DatabaseContract.RetailDatabaseEntry.TABLE_NAME_CATEGORY;

            Cursor cursor = database.rawQuery(selectQuery, null);

            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    Category detailList = new Category();

                    detailList.setId(Integer.parseInt(cursor.getString(0)));
                    detailList.setCategorydescription(cursor.getString(1));

                    detailList.setCategoryimage(cursor.getBlob(2));

                    categoriesdetailsList.add(detailList);

                } while (cursor.moveToNext());
            }

            close();
            return categoriesdetailsList;
        }   

    }

logcat的:

11-15 16:57:39.127: E/AndroidRuntime(703): FATAL EXCEPTION: main
11-15 16:57:39.127: E/AndroidRuntime(703): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.orderdatabase/com.example.orderdatabase.MainActivity}: java.lang.NullPointerException
11-15 16:57:39.127: E/AndroidRuntime(703):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)

无论我做什么都行不通。我得到了nullpointerexception。 请有人告诉我哪里错了。

感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用下面给出的示例来解决您的问题。

public List<UserInfo> getUerInfoDetails() {
            SQLiteDatabase db;
          db=getReadableDatabase();

          List<UserInfo> userInfoList=new ArrayList<UserInfo>();

          // Select All Query
          String selectQuery = "SELECT * FROM mainToDo";

          Cursor cursor =db.rawQuery(selectQuery, null);

          // looping through all rows and adding to list
          while(cursor.moveToNext())
          {
              UserInfo obj=new UserInfo();

            obj.setId(cursor.getInt(0));
            obj.setName(cursor.getString(1));
            userInfoList.add(obj);

          }
                   close();

         return userInfoList;
      }