2012-12-15 106 views
0

我的代碼沒有在數據庫中插入圖像。我如何在數據庫中插入選定的圖像,並檢索它?我下面這個教程:如何在SqlLite數據庫中插入選定的圖像?

http://vimaltuts.com/android-tutorial-for-beginners/android-sqlite-database-example

哪些修改下面的代碼需要在數據庫中插入選定的圖像?

import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.Intent; 
import android.database.Cursor; 
import android.graphics.Bitmap; 
import android.graphics.Bitmap.CompressFormat; 
import android.graphics.BitmapFactory; 
import android.graphics.drawable.BitmapDrawable; 
import android.net.Uri; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.provider.MediaStore; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ImageView; 
import android.widget.Toast; 

    public class AddEditCountry extends Activity { 

private long rowID; 
private EditText nameEt; 
private EditText capEt; 
private EditText codeEt; 

private EditText Donedate; 
private EditText Notes; 
private EditText Person; 
private ImageView imageView1; 
Bitmap yourSelectedImage; 



    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.add_country); 

     nameEt = (EditText) findViewById(R.id.Address); 
     capEt = (EditText) findViewById(R.id.Stage); 
     codeEt = (EditText) findViewById(R.id.Dueby); 

     Donedate = (EditText) findViewById(R.id.Donedate); 

     Notes = (EditText) findViewById(R.id.Notes); 
     Person = (EditText) findViewById(R.id.Person); 

     imageView1 = (ImageView) findViewById(R.id.imageView1); 
     Button Browse = (Button) findViewById(R.id.Browse); 


     Browse.setOnClickListener(new View.OnClickListener() 
     { 
      public void onClick(View v) 
      {    
       Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
       intent.setType("image/*"); 
       startActivityForResult(intent, 0); 
      } 
     });   



     Bundle extras = getIntent().getExtras(); 

     if (extras != null) 
     { 
     rowID = extras.getLong("row_id"); 
     nameEt.setText(extras.getString("name")); 
     capEt.setText(extras.getString("cap")); 
     codeEt.setText(extras.getString("code")); 
     Donedate.setText(extras.getString("Location")); 
     Notes.setText(extras.getString("Notes")); 
     Person.setText(extras.getString("Person")); 



     } 


     Button saveButton =(Button) findViewById(R.id.saveBtn); 
     saveButton.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) 
      { 
      if (nameEt.getText().length() != 0) 
      { 
       AsyncTask<Object, Object, Object> saveContactTask = 
        new AsyncTask<Object, Object, Object>() 
        { 
         @Override 
         protected Object doInBackground(Object... params) 
         { 
         saveContact(); 
         return null; 
         } 

         @Override 
         protected void onPostExecute(Object result) 
         { 
         finish(); 
         } 
        }; 

       saveContactTask.execute((Object[]) null); 
      } 

      else 
      { 
       AlertDialog.Builder alert = new 
AlertDialog.Builder(AddEditCountry.this); 
       alert.setTitle(R.string.errorTitle); 
       alert.setMessage(R.string.errorMessage); 
       alert.setPositiveButton(R.string.errorButton, null); 
       alert.show(); 
      } 
      } 
    }); 
    } 



    private void saveContact() 
    { 


    // ByteArrayOutputStream outStr = new ByteArrayOutputStream(); 
    // yourSelectedImage.compress(CompressFormat.PNG, 100, outStr); 
    // byte[] blob = outStr.toByteArray(); 





     DatabaseConnector dbConnector = new DatabaseConnector(this); 

     if (getIntent().getExtras() == null) 
     { 
      dbConnector.insertContact(nameEt.getText().toString(), 
        capEt.getText().toString(), 
        codeEt.getText().toString(), 
        Donedate.getText().toString(), 
        Notes.getText().toString(), 
        Person.getText().toString() 
        //,blob 

      ); 
     } 
     else 
     { 
     dbConnector.updateContact(rowID, 
      nameEt.getText().toString(), 
      capEt.getText().toString(), 
      codeEt.getText().toString(), 
      Donedate.getText().toString(), 
     Notes.getText().toString(), 
      Person.getText().toString() 
      //, blob 


     ); 
     } 
    } 










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

     switch(requestCode) { 
     case 0: 
      if(resultCode == RESULT_OK){ 
       Uri selectedImage = imageReturnedIntent.getData(); 
       String[] filePathColumn = {MediaStore.Images.Media.DATA}; 

       Cursor cursor = getContentResolver().query(selectedImage, 
    filePathColumn, null, null, null); 
       cursor.moveToFirst(); 

       int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
       String filePath = cursor.getString(columnIndex); // file path 
    of selected image 
       cursor.close(); 
         // Convert file path into bitmap image using below 
line. 
       yourSelectedImage = BitmapFactory.decodeFile(filePath); 

         // put bitmapimage in your imageview 
       imageView1.setImageBitmap(yourSelectedImage); 
      } 
     } 
    } 






     } 










     import android.content.Context; 
    import android.database.Cursor; 
    import android.database.SQLException; 
    import android.database.sqlite.SQLiteDatabase; 


    public class DatabaseConnector { 

private static final String DB_NAME = "WorldCountries"; 
private SQLiteDatabase database; 
private DatabaseOpenHelper dbOpenHelper; 

public DatabaseConnector(Context context) { 
    dbOpenHelper = new DatabaseOpenHelper(context, DB_NAME, null, 1); 
} 

    public void open() throws SQLException 
    { 
     //open database in reading/writing mode 
     database = dbOpenHelper.getWritableDatabase(); 
    } 

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

    public void insertContact(String name, String cap, String code, String 
     LocationEd, String Notes, String Person) 
      ///,byte[] blob) 
      { 
       ContentValues newCon = new ContentValues(); 
       newCon.put("name", name); 
       newCon.put("cap", cap); 
       newCon.put("code", code); 

       newCon.put("Location",LocationEd); 
       newCon.put("Notes",Notes); 
       newCon.put("Person",Person); 
      // newCon.put("Image", blob); 

       open(); 
       database.insert("country", null, newCon); 
       close(); 
      } 


      public void updateContact(long id, String name, String 
    cap,String code,String LocationEd, String Notes, String Person) 
        //,byte[] blob) 
      { 
       ContentValues editCon = new ContentValues(); 
       editCon.put("name", name); 
       editCon.put("cap", cap); 
       editCon.put("code", code); 
       editCon.put("Location", LocationEd); 
       editCon.put("Notes", Notes); 
       editCon.put("Person", Person); 
      // editCon.put("Image", blob); 

       open(); 
       database.update("country", editCon, "_id=" + id, null); 
       close(); 
      } 


      public Cursor getAllContacts() 
      { 
       return database.query("country", new String[] {"_id", 
    "name"}, 
       null, null, null, null, "name"); 
      } 

      public Cursor getOneContact(long id) 
      { 
       return database.query("country", null, "_id=" + id, null, 
    null, null, null); 
      } 

      public void deleteContact(long id) 
      { 
       open(); 
       database.delete("country", "_id=" + id, null); 
       close(); 
      } 
    } 















    import android.content.Context; 
    import android.database.sqlite.SQLiteDatabase; 
    import android.database.sqlite.SQLiteDatabase.CursorFactory; 
    import android.database.sqlite.SQLiteOpenHelper; 

    public class DatabaseOpenHelper extends SQLiteOpenHelper { 

public DatabaseOpenHelper(Context context, String name, 
     CursorFactory factory, int version) { 
    super(context, name, factory, version); 
} 

@Override 
public void onCreate(SQLiteDatabase db) { 
    String createQuery = "CREATE TABLE country (_id integer primary key  
autoincrement,name text,cap text,code text,Location double,Notes text,Person 
    text,blob BLOB);";    
    db.execSQL(createQuery);  














} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 

} 

    } 












     import java.io.ByteArrayInputStream; 

    import android.app.Activity; 
    import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.database.Cursor; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.net.Uri; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.provider.MediaStore; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.Button; 
    import android.widget.ImageView; 
import android.widget.TextView; 

public class ViewCountry extends Activity { 

    private long rowID; 
    private TextView nameTv; 
    private TextView capTv; 
    private TextView codeTv; 


    private TextView Locationlb; 
    private TextView Noteslb; 
    private TextView Personlb; 

    byte[] byteImage2 = null; 

    private ImageView imageView2; 
    Bitmap yourSelectedImage; 


    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.view_country); 

     setUpViews(); 
     Bundle extras = getIntent().getExtras(); 
     rowID = extras.getLong(CountryList.ROW_ID); 
    } 

    private void setUpViews() { 
     nameTv = (TextView) findViewById(R.id.nameText); 
     capTv = (TextView) findViewById(R.id.capText); 
     codeTv = (TextView) findViewById(R.id.codeText); 

     Locationlb = (TextView) findViewById(R.id.Location_lbl); 



     Noteslb = (TextView) findViewById(R.id.Notes_lbl); 
     Personlb = (TextView) findViewById(R.id.Person_lbl); 


     imageView2= (ImageView) findViewById(R.id.imageView2); 
      Button Browse2 = (Button) findViewById(R.id.Browse2); 






      Browse2.setOnClickListener(new View.OnClickListener() 
      { 
       public void onClick(View v) 
       {    
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
        intent.setType("image/*"); 
        startActivityForResult(intent, 0); 
       } 
      });   























    } 

    @Override 
    protected void onResume() 
    { 
     super.onResume(); 
     new LoadContacts().execute(rowID); 
    } 

    private class LoadContacts extends AsyncTask<Long, Object, Cursor> 
    { 
     DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this); 

     @Override 
     protected Cursor doInBackground(Long... params) 
     { 
     dbConnector.open(); 
     return dbConnector.getOneContact(params[0]); 
     } 

     @Override 
     protected void onPostExecute(Cursor result) 
     { 
     super.onPostExecute(result); 

     result.moveToFirst(); 
     // get the column index for each data item 
     int nameIndex = result.getColumnIndex("name"); 
     int capIndex = result.getColumnIndex("cap"); 
     int codeIndex = result.getColumnIndex("code"); 

     int LocationIndex = result.getColumnIndex("Location"); 
     int NotesIndex = result.getColumnIndex("Notes"); 
     int PersonIndex = result.getColumnIndex("Person"); 

    //  byte[] blob = result.getBlob("image"); 
    //  byte[] data = result.getBlob(result.getColumnIndex("image")); 
     // byte[] blob result.getColumnIndex(MyBaseColumn.MyTable.ImageField)); 






     nameTv.setText(result.getString(nameIndex)); 
     capTv.setText(result.getString(capIndex)); 
     codeTv.setText(result.getString(codeIndex)); 
     Locationlb.setText(result.getString(LocationIndex)); 


     Noteslb.setText(result.getString(NotesIndex)); 
     Personlb.setText(result.getString(PersonIndex)); 

    //  ByteArrayInputStream input = new ByteArrayInputStream(byteImage2); 

    //  Bitmap bit = BitmapFactory.decodeStream(input); 
    // imageView2.setImageBitmap(bit); 
     // imageView2.setImageURI(byteImage2); 

     imageView2.setImageBitmap(yourSelectedImage); 



     result.close(); 
     dbConnector.close(); 
     } 
    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) 
    { 
     super.onCreateOptionsMenu(menu); 
     MenuInflater inflater = getMenuInflater(); 
     inflater.inflate(R.menu.view_country_menu, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) 
    { 
     switch (item.getItemId()) 
     { 
     case R.id.editItem: 
      Intent addEditContact = 
       new Intent(this, AddEditCountry.class); 

      addEditContact.putExtra(CountryList.ROW_ID, rowID); 
      addEditContact.putExtra("name", nameTv.getText()); 
      addEditContact.putExtra("cap", capTv.getText()); 
      addEditContact.putExtra("code", codeTv.getText()); 

      addEditContact.putExtra("Location", Locationlb.getText()); 


      addEditContact.putExtra("Notes", Noteslb.getText()); 

      addEditContact.putExtra("Person", Personlb.getText()); 


     // addEditContact.putExtra("blob", yourSelectedImage); 

      startActivity(addEditContact); 
      return true; 

     case R.id.deleteItem: 
      deleteContact(); 
      return true; 

     default: 
      return super.onOptionsItemSelected(item); 
     } 
    } 

    private void deleteContact() 
    { 

     AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this); 

     alert.setTitle(R.string.confirmTitle); 
     alert.setMessage(R.string.confirmMessage); 

     alert.setPositiveButton(R.string.delete_btn, 
     new DialogInterface.OnClickListener() 
     { 
      public void onClick(DialogInterface dialog, int button) 
      { 
       final DatabaseConnector dbConnector = 
        new DatabaseConnector(ViewCountry.this); 

       AsyncTask<Long, Object, Object> deleteTask = 
        new AsyncTask<Long, Object, Object>() 
        { 
        @Override 
        protected Object doInBackground(Long... params) 
        { 
         dbConnector.deleteContact(params[0]); 
         return null; 
        } 

        @Override 
        protected void onPostExecute(Object result) 
        { 
         finish(); 
        } 
        }; 

       deleteTask.execute(new Long[] { rowID });    
      } 
     } 
    ); 

     alert.setNegativeButton(R.string.cancel_btn, null).show(); 
    } 








    protected void onActivityResult(int requestCode, int resultCode, Intent 
    imageReturnedIntent) { 
     super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

     switch(requestCode) { 
     case 0: 
      if(resultCode == RESULT_OK){ 
       Uri selectedImage = imageReturnedIntent.getData(); 
       String[] filePathColumn = {MediaStore.Images.Media.DATA}; 

       Cursor cursor = getContentResolver().query(selectedImage, 
    filePathColumn, null, null, null); 
       cursor.moveToFirst(); 

       int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
       String filePath = cursor.getString(columnIndex); // file path 
    of selected image 
       cursor.close(); 
         // Convert file path into bitmap image using below 
    line. 
       yourSelectedImage = BitmapFactory.decodeFile(filePath); 

         // put bitmapimage in your imageview 
       imageView2.setImageBitmap(yourSelectedImage); 
      } 
     } 
    } 







} 

回答

1

不要將圖像放入數據庫。將文件保存在文件系統(SD卡或內部存儲器)上,並將其引用到數據庫中。但不要直接放置圖像。

+0

我想直接說是neseccary我plz幫我 –

+0

是的。我理解你的問題,但我仍然沒有任何理由強迫你這樣做。這將是無效的,緩慢和痛苦的。這是什麼原因,我可以問一下嗎? –

0

有沒有必要把一個二進制blob在數據庫中。數據庫的主要目標是查詢,即它組織數據,以便稍後查找它。圖像是一個字節序列,你不能根據它來過濾你的查詢,所以只需將圖像存儲在文件系統中,並且可能採用一個約定,它將按照該行的ID命名。

相關問題