有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用下面的代码在sqlite中存储图像时,我只得到第一个图像,应用程序不会通过id将其他图像还原给我

当我使用此代码存储图像并从SQLite恢复它时。它只插入一个图像(第一个),当我通过id恢复图像时,它也只恢复第一个图像

主要活动。xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:tools="http://schemas.安卓.com/tools" 安卓:layout_width="match_parent"
    安卓:layout_height="match_parent" 安卓:paddingLeft="@dimen/activity_horizontal_margin"
    安卓:paddingRight="@dimen/activity_horizontal_margin"
    安卓:paddingTop="@dimen/activity_vertical_margin"
    安卓:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <EditText
    安卓:layout_width="match_parent"
    安卓:layout_height="50dp"
    安卓:textSize="24dp"
    安卓:hint="enter name"
    安卓:id="@+id/nametxt"
    安卓:layout_marginTop="350dp"
    />
    <EditText
        安卓:layout_width="match_parent"
        安卓:layout_height="50dp"
        安卓:textSize="24dp"
        安卓:hint="enter id"
        安卓:id="@+id/idtxt"
        安卓:layout_marginTop="420dp"
        />
    <Button
        安卓:textSize="20dp"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="Save Image Sqlite"
        安卓:id="@+id/button"
        安卓:layout_below="@+id/imageView"
        安卓:layout_marginTop="75dp"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true"
        安卓:layout_alignParentRight="true"
        安卓:layout_alignParentEnd="true" />

    <Button
        安卓:textSize="20dp"

        安卓:layout_width="match_parent"
        安卓:layout_height="wrap_content"
        安卓:text="Get Image From Sqlite"
        安卓:id="@+id/button2"
        安卓:layout_below="@+id/button"
        安卓:layout_marginTop="42dp"
        安卓:layout_alignParentRight="true"
        安卓:layout_alignParentEnd="true" />

    <ImageView
        安卓:background="@color/colorPrimaryDark"
        安卓:layout_width="120dp"
        安卓:layout_height="120dp"
        安卓:id="@+id/imageView2"
        安卓:layout_alignParentTop="true"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true" />

    <ImageView
        安卓:background="@color/colorAccent"
        安卓:layout_width="120dp"
        安卓:layout_height="120dp"
        安卓:id="@+id/imageView"
        安卓:scaleType="fitCenter"
        安卓:maxHeight="120dp"
        安卓:maxWidth="120dp"
        安卓:layout_alignParentTop="true"
        安卓:layout_alignParentRight="true"
        安卓:layout_alignParentEnd="true" />
</RelativeLayout>

主要活动。爪哇

package com.example.mahmoudbelal.navigator;

import 安卓.content.Intent;
import 安卓.database.Cursor;
import 安卓.database.sqlite.SQLiteDatabase;
import 安卓.graphics.Bitmap;
import 安卓.graphics.BitmapFactory;
import 安卓.net.Uri;
import 安卓.os.Bundle;
import 安卓.provider.MediaStore;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.view.View;
import 安卓.widget.Button;
import 安卓.widget.EditText;
import 安卓.widget.ImageView;
import 安卓.widget.Toast;

import java.io.ByteArrayOutputStream;

public class MainActivity extends AppCompatActivity {
    private static int RESULT_LOAD_IMG = 1;
    String imgDecodableString;
static  EditText name,id;   

  static   ImageView Img,Img2;
    Button Save,Get;
    SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
id= (EditText) findViewById(R.id.idtxt);
        Img = (ImageView) findViewById(R.id.imageView);
        Img2 = (ImageView) findViewById(R.id.imageView2);
        Save = (Button) findViewById(R.id.button);
        Get = (Button) findViewById(R.id.button2);
        name= (EditText) findViewById(R.id.nametxt);

        Img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                        安卓.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // Start the Intent
                startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
            }
        });

        Save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               try {    

                   Img.buildDrawingCache();
                   Bitmap bitmap=Img.getDrawingCache();

                   ByteArrayOutputStream bos = new ByteArrayOutputStream();
                   bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
                   byte[] img = bos.toByteArray();

                  DBAdapter D=new DBAdapter();
                   D.open(MainActivity.this);
                   String myname=name.getText().toString();
                   String myid=id.getText().toString();

                   D.insert_user_data(myid,myname,img);

                   Toast.makeText(MainActivity.this, "Inserted Data well !", Toast.LENGTH_SHORT).show();

                   name.setText(" ");
                   id.setText(" ");

               }catch (Exception e){
                   Toast.makeText(MainActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();    
               }
            }
        });    
//------------------------------------------------------------------------------------//\

        Get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DBAdapter D=new DBAdapter();
                D.open(MainActivity.this);
               String use_id=id.getText().toString();
                D.Get_user_data(use_id);
                if (DBAdapter.ok.equals("1")){
                  //  Img2.setImageBitmap(DBAdapter.bmp);
                   // Toast.makeText(MainActivity.this, "name is  =  "+DBAdapter.s, Toast.LENGTH_SHORT).show();
                    name.setText(""+DBAdapter.s);

                }else
                {

                    Toast.makeText(MainActivity.this, "Error y m3lm ", Toast.LENGTH_SHORT).show();
                }            }
        });
    }    

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);   

        // When an Image is picked
        if (requestCode == RESULT_LOAD_IMG && resultCode == this.RESULT_OK
                && null != data) {
            // Get the Image from data

            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);

            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);    
//-0-------------------------------------------------------------------------------------------------------------
            Uri photoUri = data.getData();
            String[] proj = {MediaStore.Images.Media.DATA};

            Cursor actualimagecursor = managedQuery(photoUri, proj, null, null, null);
            int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();    
            //--------------------------------------------------------------------------------------------
            cursor.close();    
            Img.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));

            Toast.makeText(MainActivity.this, "Image Uploaded", Toast.LENGTH_LONG).show();    

        } else {
            Toast.makeText(MainActivity.this, "You haven't picked Image", Toast.LENGTH_LONG).show();
        }}    
    }

DBAdapter。爪哇

package com.example.mahmoudbelal.navigator;

import 安卓.content.ContentValues;
import 安卓.content.Context;
import 安卓.database.Cursor;
import 安卓.database.sqlite.SQLiteDatabase;
import 安卓.database.sqlite.SQLiteOpenHelper;
import 安卓.graphics.Bitmap;
import 安卓.graphics.BitmapFactory;

public class DBAdapter {
    // first step:create table
  static   Bitmap bmp;
   static String s="";
    private int version=1;
    private String DatabaseName="DNAA";
    private String TableName="user";
    static  String ok;
//                             --------------------------------------------------                             //    
    private String create_table = "CREATE TABLE IF NOT EXISTS user(id varchar,name varchar,img blob);";   

    // second step:helper class
    class DbHellper extends SQLiteOpenHelper{    

        public DbHellper(Context context){
            super(context , DatabaseName , null , version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(create_table);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {    
            db.execSQL("Drop table If Exists "+TableName);
            onCreate(db);    
        }
    }    

    private DbHellper DB_helper;
    private SQLiteDatabase db;

    public DBAdapter open(Context conn){
        DB_helper = new DbHellper(conn);
        db = DB_helper.getWritableDatabase();
        return this;

        // activity
    }

    private void close (){
        db.close();
    }
    int i = 0;

    public void insert_user_data (String id, String name, byte[] ii){
        ContentValues cv = new ContentValues();    

        cv.put("id" , id);
        cv.put("name" , name);
        cv.put("img" , ii);

        db.insert(TableName, null, cv);    
    }

    public void updateSection(String username , String password , int rowId){
        ContentValues cv = new ContentValues();
        cv.put("username" , username);
        cv.put("password" , password);
        db.update(TableName, cv, "_id =" + rowId, null);
    }

    // Login method
    public  void  Get_user_data (String id){

    Cursor c = db.rawQuery("SELECT name,img FROM user where id='"+id+"'", null);
        if (c.moveToFirst()) {
             s= c.getString(0);
            byte[] i=c.getBlob(1);

             bmp= BitmapFactory.decodeByteArray(i,0,i.length);
            MainActivity.Img2.setImageBitmap(bmp);

          ok="1";
        } else {
            ok="0";
        }
    }
    // delete data
    public void deleteSection(int rowId){
        db.delete(TableName, "_id =" + rowId, null);
    }

    public Cursor getAllSections (){
        return db.query(TableName,new String []{"username","password"},null,null,null,null,null);
    }

    public Cursor getSection (String whereClause){
        return db.query(TableName,new String []{"_id","name","devices"},whereClause,null,null,null,null);
    }
}

共 (1) 个答案

  1. # 1 楼答案

    这可能对你有帮助

    字符串[]列= {MediaStore.Images.Media.DATA,MediaStore.Images.Media._ID}

        final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
    
        Cursor imagecursor = managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,null,null, orderBy + " DESC");
    
        this.imageUrls = new ArrayList<String>();
    
        for (int i = 0; i < imagecursor.getCount(); i++) {
            imagecursor.moveToPosition(i);
            int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
            imageUrls.add(imagecursor.getString(dataColumnIndex));
    
            System.out.println("==here you will get all the images path ;=> "+imageUrls.get(i));
        }
    

    请查看以下内容以供参考: http://www.technotalkative.com/android-select-multiple-photos-from-gallery/