从URL中存储Sqlite中的图像

时间:2015-04-04 16:47:31

标签: android mysql sqlite

我正在尝试将数据导入sqlite数据库,它们都是从mysql数据库获取的名称,消息和图像。问题是如何使用Blob昆虫图像..图像来自网址。我想把它放在sqite表中....我知道他们说最好将它保存在SD卡上并将位置放在sqlite表中....但唯一的问题是用户可以删除一些图像或重命名我不想要的。

这是我的sqlite数据库类

public class DBTool extends SQLiteOpenHelper {
    private Context appContext;
     static final String firstname="firstname";
     static final String lastname="lastname";

    public DBTool(Context applicationContext){

        super(applicationContext, "friend.db", null, 1);
        this.appContext = applicationContext;

    }
    @Override
    public void onCreate(SQLiteDatabase database) {

                String query = "CREATE TABLE friends ( contactId INTEGER PRIMARY KEY, name TEXT, " +
                        "message TEXT, image BLOB)";
                database.execSQL(query);
    }

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

        String query = "DROP TABLE IF EXISTS friends";

        database.execSQL(query);
        onCreate(database);

    }

    public void insertContact(HashMap<String, String> queryValues){

        SQLiteDatabase database = this.getWritableDatabase();


        ContentValues values = new ContentValues();

        values.put("name", queryValues.get("name"));
        values.put("message", queryValues.get("message"));
        values.put("image", queryValues.get("image"));

        database.insert("friends", null, values);
        database.close();

    }

    public int updateContact(HashMap<String, String> queryValues){

        SQLiteDatabase database = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put("name", queryValues.get("name"));
        values.put("message", queryValues.get("message"));
        values.put("image", queryValues.get("image"));


        return database.update("friends", values, 
                "contactId" + " = ?", new String[] {queryValues.get("contactId") });

    }

    public void deleteContact(){

        SQLiteDatabase database = this.getWritableDatabase();

        String deleteQuery = "DELETE FROM friends ";

        database.execSQL(deleteQuery);

    }

    public ArrayList<HashMap<String, String>> getAllContacts(){

        ArrayList<HashMap<String, String>> contactArrayList = new ArrayList<HashMap<String, String>>();


         String selectQuery = "SELECT * FROM friends ";
        SQLiteDatabase database = this.getWritableDatabase();

        Cursor cursor = database.rawQuery(selectQuery, null);


        if(cursor.moveToFirst()){

            do{

                HashMap<String, String> contactMap = new HashMap<String, String>();

                contactMap.put("name", cursor.getString(0));
                contactMap.put("message", cursor.getString(1));
                contactMap.put("image", cursor.getString(2));


                contactArrayList.add(contactMap);

            } while(cursor.moveToNext());

        }
        return contactArrayList;

    }

    public HashMap<String, String> getContactInfo(String id){

        HashMap<String, String> contactMap = new HashMap<String, String>();

        SQLiteDatabase database = this.getReadableDatabase();

        String selectQuery = "SELECT * FROM friends WHERE contactId='" + id + "'";

        Cursor cursor = database.rawQuery(selectQuery, null);

        if(cursor.moveToFirst()){

            do{

                contactMap.put("name", cursor.getString(0));
                contactMap.put("message", cursor.getString(1));
                contactMap.put("image", cursor.getString(2));

            } while(cursor.moveToNext());

        }

        return contactMap;

    }

}

这是我的班级获取数据和昆虫

public class Chat extends SherlockListFragment {
    JSONParser jsonParser = new JSONParser();
    private static final String TAG_POSTS = "posts";
    public static final String TAG_ID = "id";
    public static final String TAG_NAME = "name";
    public static final String TAG_pic = "pic";
    public static final String TAG_MESSAGE = "message";
    public static final String TAG_CATEGORIES_LOGO = "categories_logo";
    DBTool dbTool = new DBTool(getActivity());
    /*
  user details
    private static final String NAME = "name";
    private static final String AGE = "age";
    private static final String STATUS = "status";
    private static final String PIC = "pic";
    private static final String SEX = "sex"; String friendname,status;

    private static final String TAG_SUCCESS = "success";*/
        //user
    private static final String URL_CATEGORY = "http://10.0.2.2/ochat/selectchat.php";

        private ListView lv;
        SharedPreferences sp ;
        Bundle bon = new Bundle();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.friends, container, false);
        return rootView;
    }
     @Override 
        public void onActivityCreated(Bundle savedInstanceState) {  
            super.onActivityCreated(savedInstanceState);  

            new LoadComments().execute(); 
 }

       class LoadComments extends AsyncTask<Void, Void, ArrayList<HashMap<String,String>>> {
            private ProgressDialog pDialog;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(getActivity());

                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);

            }

            @Override
            protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {

                  ArrayList<HashMap<String, String>> categoryList = new ArrayList<HashMap<String, String>>();

                SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
              String username = sp.getString("username", "anon");
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("username", username));
                  JSONObject json = jsonParser.makeHttpRequest(URL_CATEGORY, "POST",
                            params);

                  try {

                      JSONArray categories = json.getJSONArray(TAG_POSTS);
                      for (int i = 0; i < categories.length(); i++) {
                          String id = categories.getJSONObject(i).getString("TAG_ID");
                          String name = categories.getJSONObject(i).getString("TAG_NAME");
                          String pic = categories.getJSONObject(i).getString("TAG_pic");
                          String message = categories.getJSONObject(i).getString("TAG_MESSAGE");

                        HashMap<String, String> queryValuesMap =  new  HashMap<String, String>();

                        queryValuesMap.put("name", name);

                        queryValuesMap.put("message",message);

                        DefaultHttpClient mHttpClient = new DefaultHttpClient();
                        HttpGet mHttpGet = new HttpGet(pic);
                        HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
                        if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                          HttpEntity entity = mHttpResponse.getEntity();
                            if ( entity != null) {
                              // insert to database
                            queryValuesMap.put("image", EntityUtils.toByteArray(entity));

                            }
                        }


                            dbTool.insertContact(queryValuesMap);

                      }
                  }catch (Throwable e){
                      e.printStackTrace();
                  }
                  return categoryList;
              }

            @Override
            protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
                super.onPostExecute(result);


            }
        }
    }

问题来自

  

queryValuesMap.put(&#34; image&#34;,EntityUtils.toByteArray(entity));

正在说

  

方法put(String,String)在HashMap类型中不适用于参数(String,byte [])

我不知道这是我安排它的方式还是有更好的方法来做到这一点..  实现这个想法from this site

1 个答案:

答案 0 :(得分:0)

问题是函数EntityUtils.toByteArray()正好返回:byte[],但你的HashMap期待一个字符串。

尝试将此行更改为

queryValuesMap.put("image", new String(EntityUtils.toByteArray(entity)));

构造函数String(byte[]) will create a new string from your bytes