Iqra Rajpoot
Iqra Rajpoot

Reputation: 11

Displaying data from a db

How to retrieve random pic of gallery from android SQLite database and display it in another Activity with name and price? When I click on "profile" button my app crashes but data is added successfully.

My code is:

MainActivity class:

public class MainActivity extends AppCompatActivity {

    EditText edtName, edtPrice;
    Button btnChoose, btnAdd, btnList;
    ImageView imageView;
    Uri imageuri;
    final int REQUEST_CODE_GALLERY = 999;
    private static final int pick_image = 100;

    public static SQLiteHelper sqLiteHelper;

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

        edtName = (EditText) findViewById(R.id.edtName);
        edtPrice = (EditText) findViewById(R.id.edtPrice);
        btnChoose = (Button) findViewById(R.id.btnChoose);
        btnAdd = (Button) findViewById(R.id.btnAdd);
        btnList = (Button) findViewById(R.id.btnList);
        imageView = (ImageView) findViewById(R.id.imageView);

        sqLiteHelper = new SQLiteHelper(this, "FoodDB.sqlite", null, 1);

        sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS FOOD(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, price VARCHAR, image BLOB)");

        btnChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(gallery,pick_image);
            }
        });

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try{
                    sqLiteHelper.insertData(
                            edtName.getText().toString().trim(),
                            edtPrice.getText().toString().trim(),
                            imageViewToByte(imageView)
                    );
                    Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
                   // edtName.setText("");
                    //edtPrice.setText("");
                   // imageView.setImageResource(R.mipmap.ic_launcher);
                    String s = "iqra";   //why we take string whrn we take only next button,is it necessary to take the string?
                    Intent i = new Intent(MainActivity.this, foodprofile.class);
                    Bundle bun = new Bundle();
                    bun.putString("name", s);
                    i.putExtras(bun);
                    startActivity(i);
                }
                catch (Exception e){
                    e.printStackTrace();

                }

            }
  });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == pick_image){
            imageuri = data.getData();
            imageView.setImageURI(imageuri);
        }
    }

    public static byte[] imageViewToByte(ImageView image) {
        Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        //bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 0, stream);
        byte[] byteArray = stream.toByteArray();
        return byteArray;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == REQUEST_CODE_GALLERY){
            if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_CODE_GALLERY);
            }
            else {
                Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


}

SQLitehelper class:

public class SQLiteHelper extends SQLiteOpenHelper {
    public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    public void queryData(String sql){
        SQLiteDatabase database = getWritableDatabase();
        database.execSQL(sql);
    }

    public void insertData(String name, String price, byte[] image){
        SQLiteDatabase database = getWritableDatabase();
        String sql = "INSERT INTO FOOD VALUES (NULL, ?, ?, ?)";

        SQLiteStatement statement = database.compileStatement(sql);
        statement.clearBindings();

        statement.bindString(1, name);
        statement.bindString(2, price);
        statement.bindBlob(3, image);

        statement.executeInsert();
    }

    public void updateData(String name, String price, byte[] image, int id) {
        SQLiteDatabase database = getWritableDatabase();

        String sql = "UPDATE FOOD SET name = ?, price = ?, image = ? WHERE id = ?";
        SQLiteStatement statement = database.compileStatement(sql);

        statement.bindString(1, name);
        statement.bindString(2, price);
        statement.bindBlob(3, image);
        statement.bindDouble(4, (double)id);

        statement.execute();
        database.close();
    }

    public  void deleteData(int id) {
        SQLiteDatabase database = getWritableDatabase();

        String sql = "DELETE FROM FOOD WHERE id = ?";
        SQLiteStatement statement = database.compileStatement(sql);
        statement.clearBindings();
        statement.bindDouble(1, (double)id);

        statement.execute();
        database.close();
    }

    public Cursor getData(){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("Select * from food ",null);
        return res;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

    foodprofile
public class foodprofile extends AppCompatActivity {
     SQLiteHelper sqLiteHelper;
    Button profile;
    TextView txtresult1,txtresult2,txtresult6;
    ImageView imgvresult;
    Uri imageuri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_foodprofile);
        txtresult1 = (TextView) findViewById(R.id.name);
        txtresult2 = (TextView) findViewById(R.id.price);
        imgvresult = (ImageView) findViewById(R.id.image) ;
        profile = (Button) findViewById(R.id.btnprofile);
    }
    public void profile(View v) {
        if(v.getId()==R.id.btnprofile) {
            Cursor res = sqLiteHelper.getData();
            StringBuffer stringbuffer = new StringBuffer();
            Toast pass =  Toast.makeText(foodprofile.this,"inserted successfully", Toast.LENGTH_SHORT);
            pass.show();


                    txtresult1.setText("  " + res.getString(0) );
                    txtresult2.setText("  "   + res.getString(1) );
                    imgvresult.setImageURI(imageuri);
                  //  imgvresult.setImageResource(res.getString(2),R.mipmap.ic_launcher);
                     //imgvresult.setImageResource(res.getBlob(0x2));
                    txtresult6.setText("-------------------------"  + "\n");


                //txtresult.setText(stringbuffer.toString());
                Toast pass1= Toast.makeText(foodprofile.this, "retrieve successfully", Toast.LENGTH_SHORT);
                pass1.show();
            }


    }
}

foodprofile.xml:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff" >
        <Button
            android:id="@+id/btnprofile"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="profile"
            android:background="@color/colorPrimaryDark"

            android:onClick="profile"/>
       <ImageView
           android:id="@+id/image"
           android:layout_marginTop="55dp"
           android:layout_width="match_parent"
           android:layout_height="200dp" />
        <TextView
            android:id="@+id/name"
            android:textColor="#000"
            android:textStyle="bold"
            android:textSize="30dp"
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="300dp"/>
        <TextView
            android:id="@+id/price"
            android:textColor="#000"
            android:textStyle="bold"
            android:textSize="30dp"
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="350dp"/>


    </RelativeLayout>

</ScrollView>

Upvotes: 1

Views: 60

Answers (1)

MikeT
MikeT

Reputation: 56948

You need to :-

  • a) get a byte array via the getBlob() and then
  • b) convert the byte array to a Bitmap and then
  • c) set the ImageView using the Bitmap

Something along the lines of :-

public void profile(View v) {
    if(v.getId()==R.id.btnprofile) {
        Cursor res = sqLiteHelper.getData();
        StringBuffer stringbuffer = new StringBuffer();
        Toast pass =  Toast.makeText(foodprofile.this,"inserted successfully", Toast.LENGTH_SHORT);
        pass.show();
        txtresult1.setText("  " + res.getString(0) );
        txtresult2.setText("  "   + res.getString(1) );
        // get the Blob
        byte[] my_bytearray = res.getBlob(2);
        // convert byte array into a bitmap
        Bitmap bmp = BitmapFactory.decodeByteArray(my_bytearray, 0, my_bytearray.length);
        // apply the image to the image view
        imgvresult.setImageBitmap(Bitmap.createScaledBitmap(bmp, image.getWidth(),
            image.getHeight(), false)));
        Toast pass1= Toast.makeText(foodprofile.this, "retrieve successfully", Toast.LENGTH_SHORT);
            pass1.show();
        }
}

Notes

  • Storing images can be problematic and inefficient. If the images are greater than about 100k it is advisable to store the images as files and to then store the path to the image in the database.
  • The above codes is in-principle it has not been tested and may therefore have typing errors.

Upvotes: 0

Related Questions