0

可能重复:
如何将图像存储在 sqlite 数据库中

这是我用于插入数据并保存在 sql lite 数据库中并显示显示的代码我如何创建新表来保存图像并在输出中使用此代码显示?这段代码工作正常我只想创建新表“IMAGETABLE”,它从用户上传图像中获取输入并保存到数据库

我的活动课。

 import android.app.Activity;
 import android.app.AlertDialog;
 import android.os.AsyncTask;
 import android.os.Bundle;
import android.view.View;
 import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

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;

   @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);

      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() 
   {
      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()




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


         );
      }
   }
}

ListView 的 ListActivity

 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.app.ListActivity;
  import android.content.Intent;
 import android.database.Cursor;
 import android.view.Menu;
 import android.view.MenuInflater;
  import android.view.MenuItem;
 import android.view.View;
 import android.widget.AdapterView;
   import android.widget.CursorAdapter;
  import android.widget.ListView;
 import android.widget.SimpleCursorAdapter;
  import android.widget.AdapterView.OnItemClickListener;

  public class CountryList extends ListActivity {

 public static final String ROW_ID = "row_id";
 private ListView conListView;
 private CursorAdapter conAdapter;

 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    conListView=getListView();
    conListView.setOnItemClickListener(viewConListener);

    // map each name to a TextView
    String[] from = new String[] { "name" };
    int[] to = new int[] { R.id.countryTextView };
    conAdapter = new SimpleCursorAdapter(CountryList.this, R.layout.country_list,  
   null, from, to);
    setListAdapter(conAdapter); // set adapter
 }


 @Override
 protected void onResume() 
 {
   super.onResume();  
   new GetContacts().execute((Object[]) null);
  } 


 @Override
 protected void onStop() 
 {
   Cursor cursor = conAdapter.getCursor();

   if (cursor != null) 
      cursor.deactivate();

   conAdapter.changeCursor(null);
   super.onStop();
 }    


   private class GetContacts extends AsyncTask<Object, Object, Cursor> 
   {
   DatabaseConnector dbConnector = new DatabaseConnector(CountryList.this);

   @Override
   protected Cursor doInBackground(Object... params)
   {
      dbConnector.open();
      return dbConnector.getAllContacts(); 
   } 

   @Override
   protected void onPostExecute(Cursor result)
   {
      conAdapter.changeCursor(result); // set the adapter's Cursor
      dbConnector.close();
   } 
   } 

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

 @Override
 public boolean onOptionsItemSelected(MenuItem item) 
 {
   Intent addContact = new Intent(CountryList.this, AddEditCountry.class);
   startActivity(addContact);
   return super.onOptionsItemSelected(item);
 }

  OnItemClickListener viewConListener = new OnItemClickListener() 
 {
   public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
   {         
      Intent viewCon = new Intent(CountryList.this, ViewCountry.class);
      viewCon.putExtra(ROW_ID, arg3);
      startActivity(viewCon);
   }
   };    

  }

我的数据库类:

           import android.content.ContentValues;
  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) 
           {
              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);

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


           public void updateContact(long id, String name, String  
    cap,String code,String LocationEd, String Notes, String Person) 
           {
              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);

              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);";              
    db.execSQL(createQuery);        
}

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

}

  }















            import android.app.Activity;
  import android.app.AlertDialog;
   import android.content.DialogInterface;
    import android.content.Intent;
     import android.database.Cursor;
import android.os.AsyncTask;
 import android.os.Bundle;
 import android.view.Menu;
 import android.view.MenuInflater;
 import android.view.MenuItem;
   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; 

   @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);



   }

   @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");

         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));


         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());

            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();
   }
}
4

1 回答 1

0

只需在数据库中创建 blob 字段。

首先将图像或位图转换为 base64 字符串并将其插入到您数据库中的 blob 字段中。

然后从数据库返回时

获取base64字符串,然后转换成图像..

我试过这个概念它有效

于 2012-12-12T10:15:35.417 回答