如何在sqlite数据库中存储图像路径并在listview中显示它们?

时间:2015-05-17 17:53:14

标签: java android sqlite listview

我编写了一个程序,用于在URL列表视图中显示json数据 https://itunes.apple.com/search?term=jack+johnson&limit=50 图像和文本完美地显示在列表视图中,但我想通过将详细信息存储在sqlite数据库中来脱机访问数据。 为此,我编写了一个代码,用于在sqlite数据库中插入图像URL和文本,并检索它们。

SqliteListHelper.java:artworkImage是我要在listview中显示的图像

public long insertData(String artworkImage, String wrapperType, String 
        artistName, String collectionName,
        String trackName, String collectionPrice, String trackId) {
    SQLiteDatabase db = helper.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(DbListHelper.ARTWORK_IMAGE, artworkImage);
    values.put(DbListHelper.WRAPPER_TYPE, wrapperType);
    values.put(DbListHelper.ARTIST_NAME, artistName);
    values.put(DbListHelper.COLLECTION_NAME, collectionName);
    values.put(DbListHelper.TRACK_NAME, trackName);
    values.put(DbListHelper.COLLECTION_PRICE, collectionPrice);
    values.put(DbListHelper.TRACK_ID, trackId);
    long id = db.insert(DbListHelper.TABLE_NAME, null, values);
    return id;
}

public Cursor getAllData() {

    SQLiteDatabase db = helper.getWritableDatabase();
    String[] columns = { DbListHelper.UID, DbListHelper.ARTWORK_IMAGE, 
            DbListHelper.WRAPPER_TYPE,
            DbListHelper.ARTIST_NAME, DbListHelper.COLLECTION_NAME, 
            DbListHelper.TRACK_NAME,
            DbListHelper.COLLECTION_PRICE };
    Cursor cursor = db.query(DbListHelper.TABLE_NAME, columns, null, null, 
    null, null, null);
    StringBuffer buffer = new StringBuffer();
    while (cursor.moveToNext()) {
        int index = cursor.getColumnIndex(DbListHelper.UID);
        int cid = cursor.getInt(index);
        int index0 = cursor.getColumnIndex(DbListHelper.ARTWORK_IMAGE);
        String cid0 = cursor.getString(index0);
        int index1 = cursor.getColumnIndex(DbListHelper.WRAPPER_TYPE);
        String cid1 = cursor.getString(index1);
        int index2 = cursor.getColumnIndex(DbListHelper.ARTIST_NAME);
        String cid2 = cursor.getString(index2);
        int index3 = cursor.getColumnIndex(DbListHelper.COLLECTION_NAME);
        String cid3 = cursor.getString(index3);
        int index4 = cursor.getColumnIndex(DbListHelper.TRACK_NAME);
        String cid4 = cursor.getString(index4);
        int index5 = cursor.getColumnIndex(DbListHelper.COLLECTION_PRICE);
        String cid5 = cursor.getString(index5);
        buffer.append(cid + " " + cid0 + " " + cid1 + " " + cid2 + " " + 
        cid3 + " " + cid4 + " " + cid5 + "\n");

    }
    return cursor;
}

MainActivity.java:这是我获取json数据并将所有数据存储在sqlite数据库中的类。

public class MainActivity extends ListActivity {

private SqliteListHelper listHelper;
// URL to get contacts JSON
private static String url = "https://itunes.apple.com/search?
term=jack+johnson&limit=50";

// JSON Node names
static final String TAG_RESULT = "results";
static final String TAG_ARTWORK_IMAGE = "artworkUrl100";
static final String TAG_WRAPPER_TYPE = "wrapperType";
static final String TAG_ARTIST_NAME = "artistName";
static final String TAG_COLLECTION_NAME = "collectionName";
static final String TAG_TRACK_NAME = "trackName";
static final String TAG_COLLECTION_PRICE = "collectionPrice";
static final String TAG_TRACK_ID = "trackId";

String artworkImage, wrapperType, artistName, collectionName, trackName, 
collectionPrice, trackId;

// contacts JSONArray
JSONArray tunes = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> resultsList;

ProgressDialog pDialog;

ListView lv;
ListViewAdapter adapter;
String extStorageDirectory;
File folder;
File file;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    resultsList = new ArrayList<HashMap<String, String>>();
    lv = getListView();

    // Calling async task to get json
    new GetTunesDetails().execute();

    listHelper = new SqliteListHelper(getBaseContext());

    listHelper.open(getBaseContext());
}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetTunesDetails extends AsyncTask<Void, Void, Void> {

    private SimpleCursorAdapter dataAdapter;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... params) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);
        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                tunes = jsonObj.getJSONArray(TAG_RESULT);

                // looping through All Products
                for (int i = 0; i < tunes.length(); i++) {
                    JSONObject c = tunes.getJSONObject(i);
                    // the artworkImage variable which has image urls ,   
                    which i want to display in my listview
                    artworkImage = c.getString("artworkUrl100");
                    wrapperType = c.getString("wrapperType");
                    artistName = c.getString("artistName");
                    collectionName = c.getString("collectionName");
                    trackName = c.getString("trackName");
                    collectionPrice = c.getString("collectionPrice");
                    trackId = c.getString("trackId");

                    // tmp hashmap for single contact
                    HashMap<String, String> tunesMap = new HashMap<String, 
                    String>();

                    // adding each child node to HashMap key => value
                    // contact.put(TAG_ID, firstname);
                    tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
                    tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
                    tunesMap.put(TAG_ARTIST_NAME, artistName);
                    tunesMap.put(TAG_COLLECTION_NAME, collectionName);
                    tunesMap.put(TAG_TRACK_NAME, trackName);
                    tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
                    tunesMap.put(TAG_TRACK_ID, trackId);

                    // adding contact to contact list
                    resultsList.add(tunesMap);

                    //extStorageDirectory = 
                    Environment.getExternalStorageDirectory().toString();
                    //folder = new File(extStorageDirectory, "Fasoos");
                    //folder.mkdir();
                    //DownloadFile.DownloadFile(artworkImage, folder);
                    long id = listHelper.insertData(artworkImage, 
                    wrapperType, artistName, collectionName, trackName,
                            collectionPrice, trackId);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        if (pDialog.isShowing())
            pDialog.dismiss();
        Cursor cursor = listHelper.getAllData();
        String[] columns = new String[] { DbListHelper.ARTWORK_IMAGE, 
                DbListHelper.WRAPPER_TYPE,
                DbListHelper.ARTIST_NAME, DbListHelper.COLLECTION_NAME, 
                DbListHelper.TRACK_NAME,
                DbListHelper.COLLECTION_PRICE };

        int[] to = new int[] { R.id.artworkImage, R.id.wrapperType, 
                R.id.artistName, R.id.collectionName,
                R.id.trackName, R.id.collectionPrice };

        dataAdapter = new SimpleCursorAdapter(getBaseContext(), 
        R.layout.custom_row, cursor, columns, to);
        lv.setAdapter(dataAdapter);
    }
}

现在使用上面的代码,我的文本视图显示但图像不显示,所以我创建了一个类来下载我的SD卡中的文件

DownloadFile.java:

public class DownloadFile {
public static void DownloadFile(String fileURL, File directory) {
    try {
        FileOutputStream f = new FileOutputStream(directory);
        URL u = new URL(fileURL);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();

        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1048 * 1048];
        int len1 = 0;
        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.flush();
        f.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

}

现在我被困在哪里以及如何调用DownloadFile类以及如何在listview中显示图像

如果有人可以帮助我,那将是一个很大的帮助 谢谢

0 个答案:

没有答案