首页 > 解决方案 > 如何从sqlite数据库中获取图像并在android studio的列表视图中显示第二页

问题描述

我在显示数据库中的图像时遇到了很多麻烦。该图像存储在 SQLite 数据库中,但未显示在第二页的列表视图中。采用了很多方法,但都不起作用。

我的代码在这里 activity_registration.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Registration">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/ic_launcher_background"
        android:id="@+id/avatarid"/>

    <EditText
        android:id="@+id/edtfname"

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="Full Name"
        android:inputType="text" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_submit"

            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"

            android:text="submit"/>

        <Button
            android:id="@+id/btn_edit"

            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"

            android:text="Edit"
            android:visibility="gone"
            />

        <Button
            android:id="@+id/btn_display"

            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"

            android:text="display"/>
    </LinearLayout>

</LinearLayout>

注册.java

public class Registration extends AppCompatActivity {

    EditText efname;
    Button submit,display,edit;
    DBmain dbmainobj;
    SQLiteDatabase db;
    int id=0;

    private ImageView avatar;

    public static final int Gallerypic=1;
    public static final int CAMERA_REQUEST=100;
    public static final int STORAGE_REQUEST=200;
    public static final int IMAGE_PICKCAMERA_REOUEST=300;
    public static final int IMAGE_PICKGALLERY_REQUEST=400;
    String cameraPermission[];
    String storagePermission[];
    Uri imageuri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_registration );
        findid();
        dbmainobj=new DBmain( Registration.this );
        getdata ();
        clear();
       editdata();
       avatar=findViewById ( R.id.avatarid );
       avatar.setOnClickListener ( new View.OnClickListener () {
           @Override
           public void onClick(View v) {
               showImagePicDialog ();
           }
       } );

    }
    private void showImagePicDialog() {
        String options[] = {"Camera", "Gallery"};
        android.app.AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Pick Image From");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    if (!checkCameraPermission()) {
                        requestCameraPermission();
                    } else {
                        pickFromGallery();
                    }
                } else if (which == 1) {
                    if (!checkStoragePermission()) {
                        requestStoragePermission();
                    } else {
                        pickFromGallery();
                    }
                }
            }
        });
        builder.create().show();
    }

    private void editdata() {

        if(getIntent().getBundleExtra( "userdata" )!=null)
        {
            Bundle bundle=getIntent().getBundleExtra( "userdata" );
            id=bundle.getInt( "id" );

            efname.setText( bundle.getString( "fname" ));

            edit.setVisibility(View.VISIBLE);
           submit.setVisibility(View.GONE);
        }
    }

    private void clear() {

        efname.setText( "" );

    }

    private void getdata() {

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

                ContentValues cv=new ContentValues(  );
                cv.put( "fname" ,efname.getText().toString());
                cv.put ("avatar",imageViewToByte(avatar) );

                db=dbmainobj.getWritableDatabase();
                Long recid=db.insert( "student",null,cv );
                if(recid!=null)
                {
                    Toast.makeText( Registration.this, "Data Insert Successfully", Toast.LENGTH_SHORT ).show();
                    clear();
                }
                else
                {
                    Toast.makeText( Registration.this, "Data Not Insert Successfully", Toast.LENGTH_SHORT ).show();
                }


            }
        } );

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

                startActivity( new Intent( Registration.this,Displaydata.class ) );
            }
        } );

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

                ContentValues cv=new ContentValues(  );
                cv.put( "fname" ,efname.getText().toString());
                cv.put ( "avatar",Registration.imageViewToByte ( avatar ) );

                db=dbmainobj.getWritableDatabase();
                long recid = db.update("student",cv,"id="+id,null);
                if(recid!=-1)
                {
                    Toast.makeText( Registration.this, "Data Update Successfully", Toast.LENGTH_SHORT ).show();
                    submit.setVisibility( View.VISIBLE );
                    edit.setVisibility( View.GONE );
                    clear();
                }
                else
                {
                    Toast.makeText( Registration.this, "Data Not Update Successfully", Toast.LENGTH_SHORT ).show();
                }


            }
        } );


    }

    private void findid() {

        efname=findViewById( R.id.edtfname );

        submit=findViewById( R.id.btn_submit );
        display=findViewById( R.id.btn_display );
        edit=findViewById( R.id.btn_edit);
    }

    private Boolean checkStoragePermission() {
        boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
        return result;
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestStoragePermission() {
        requestPermissions(storagePermission, STORAGE_REQUEST);
    }

    private Boolean checkCameraPermission() {
        boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
        boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
        return result && result1;
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestCameraPermission() {
        requestPermissions(cameraPermission, CAMERA_REQUEST);
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case CAMERA_REQUEST: {
                if (grantResults.length > 0) {
                    boolean camera_accepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean writeStorageaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                    if (camera_accepted && writeStorageaccepted) {
                        pickFromGallery();
                    } else {
                        Toast.makeText(this, "Please Enable Camera and Storage Permissions", Toast.LENGTH_LONG).show();
                    }
                }
            }
            break;
            case STORAGE_REQUEST: {
                if (grantResults.length > 0) {
                    boolean writeStorageaccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    if (writeStorageaccepted) {
                        pickFromGallery();
                    } else {
                        Toast.makeText(this, "Please Enable Storage Permissions", Toast.LENGTH_LONG).show();
                    }
                }
            }
            break;
        }
    }

    private void pickFromGallery() {
        CropImage.activity().start(Registration.this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                Uri resultUri = result.getUri();
                Picasso.with(this).load(resultUri).into(avatar);
            }
        }
    }

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

活动显示数据.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#83C9C7"
    tools:context=".Displaydata">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lv"></ListView>

</LinearLayout>

显示数据.java

public class Displaydata extends AppCompatActivity {
    DBmain dbmainobj;
    SQLiteDatabase db;
    ListView lv;
    String[] sfname;
    int[] id;
    byte[] avatar;
    ImageView savatar;
    private Bitmap bitmapImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_displaydata );
        findid ();
        dbmainobj = new DBmain ( Displaydata.this );
        dis ();
    }
    private void dis() {
        db = dbmainobj.getReadableDatabase ();
        Cursor cursor = db.rawQuery ( "select * from student", null );
        if (cursor.getCount () > 0) {
            id = new int[cursor.getCount ()];
            sfname = new String[cursor.getCount ()];
            byte[] savatar = new byte[cursor.getCount ()];

            int i = 0;
            while (cursor.moveToNext ()) {
                id[i] = cursor.getInt ( 0 );
                sfname[i] = cursor.getString ( 1 );
            //    byte[] avatar = cursor.getBlob ( 2 );
                avatar = cursor.getBlob(2);
                Bitmap bitmapImage = BitmapFactory.decodeByteArray ( avatar, 0, avatar.length );


                i++;
            }
            Custom adapter = new Custom ();
            lv.setAdapter ( adapter );
        }
    }
    private void findid() {
        lv = findViewById ( R.id.lv );
    }


    private class Custom extends BaseAdapter {
        @Override
        public int getCount() {
            return sfname.length;
        }
        @Override
        public Object getItem(int i) {
            return null;
        }
        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(final int position, View v, ViewGroup viewGroup) {
            TextView txtfname;
            Button edit, delete;
            ImageView imageobj;
            v = LayoutInflater.from ( Displaydata.this ).inflate ( R.layout.singledata, viewGroup, false );
            txtfname = v.findViewById ( R.id.txt_fname );
            imageobj = v.findViewById ( R.id.imageview );

            edit = v.findViewById ( R.id.btn_edit );
            delete = v.findViewById ( R.id.btn_delete );
            txtfname.setText ( sfname[position] );

            imageobj.setImageBitmap ( bitmapImage );
            edit.setOnClickListener ( new View.OnClickListener () {
                @Override
                public void onClick(View view) {
                    Bundle data = new Bundle ();
                    data.putInt ( "id", id[position] );
                    data.putString ( "fname", sfname[position] );
                    data.getByte ( "avatar", avatar[position] );
                    Intent i = new Intent ( Displaydata.this, Registration.class );
                    i.putExtra ( "userdata", data );
                    startActivity ( i );
                }
            } );
            delete.setOnClickListener ( new View.OnClickListener () {
                @Override
                public void onClick(View view) {
                    db = dbmainobj.getReadableDatabase ();
                    long recdelete = db.delete ( "student", "id=" + id[position], null );
                    if (recdelete != -1) {
                        Toast.makeText ( Displaydata.this, "Record Deleted Successfully", Toast.LENGTH_SHORT ).show ();
                        dis ();
                    }
                }
            } );
            return v;
        }
    }
}

单数据.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_marginStart="154dp"
        android:layout_marginEnd="149dp"
        android:src="@drawable/ic_launcher_background" />

    <TextView
        android:id="@+id/txt_fname"
        android:layout_width="147dp"
        android:layout_height="53dp"
        android:layout_below="@+id/imageview"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="47dp"
        android:layout_marginEnd="139dp" />

    <Button
        android:id="@+id/btn_edit"
        android:layout_below="@+id/txt_fname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="38dp"
        android:text="Edit" />

    <Button
        android:id="@+id/btn_delete"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn_edit"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="-50dp"
        android:layout_marginEnd="0dp"
        android:text="Delete" />

</RelativeLayout>

数据库文件 DBmain.java

public class DBmain extends SQLiteOpenHelper {
    String sql;
    public DBmain(@Nullable Context context) {
        super( context, "studentdb", null, 1 );
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        sql="create table student(id integer primary key,fname text,avatar blob)";
        db.execSQL( sql );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        sql="drop table student";
        db.execSQL( sql );
        onCreate( db );

    }
}

裁剪图像依赖项

    // This library is used for crop image feature

    api 'com.theartofdev.edmodo:android-image-cropper:2.8.0'

// This library is used for loading the

// cropped image into ImageView.


    implementation 'com.squareup.picasso:picasso:2.5.2'

标签: javaxmlandroid-studioandroid-layoutandroid-sqlite

解决方案


推荐阅读