Android 图片库 JSON / SQLite 带可变数量的图像

Posted

技术标签:

【中文标题】Android 图片库 JSON / SQLite 带可变数量的图像【英文标题】:Android Picture Gallery JSON / SQLite w/ variable number of Images 【发布时间】:2018-07-14 13:08:14 【问题描述】:

我的目标

所以我想在我的 android 应用程序中解析图片以获取图片库。假设我有5 个(或更多)图片库,每个图片库中的图片数量不定

我的 GalleryOverview 给了我我的 ListView 让我们说

缩略图 说明 日期

单击 ListView 中的一个项目会给我 PictureDetail Activity 中的整个画廊。单击图片本身,它会打开 SinglePicture Activity 以提供全分辨率的图片

当前状态

所以,活动树不是问题,我能够解析和加载 1 个画廊,其中包含静态数量的图片。 我失败的地方:JSON-Parsing(我自己选择了哪个结构)并插入到本地 SQLTable 中

OVERVIEW.CLASS

public class Overview extends AppCompatActivity 

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery_recyclerview_allimages);

    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv_images);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);

    Overview.ImageGalleryAdapter adapter = new Overview.ImageGalleryAdapter(getApplicationContext(),SinglePicture.getSpacePhotos());
    recyclerView.setAdapter(adapter);



private class ImageGalleryAdapter extends RecyclerView.Adapter<ImageGalleryAdapter.MyViewHolder>  

    @Override
    public ImageGalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) 

        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        // Inflate the layout
        View photoView = inflater.inflate(R.layout.gallery_costume_item_layout, parent, false);

        ImageGalleryAdapter.MyViewHolder viewHolder = new ImageGalleryAdapter.MyViewHolder(photoView);
        return viewHolder;
    

    @Override
    public void onBindViewHolder(ImageGalleryAdapter.MyViewHolder holder, int position) 

        SinglePicture spacePhoto = mSpacePhotos[position];
        ImageView imageView = holder.mPhotoImageView;

        Glide.with(mContext)
                .load(spacePhoto.getUrl())
                .into(imageView);
    

    @Override
    public int getItemCount() 
        return (mSpacePhotos.length);
    

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener 

        public ImageView mPhotoImageView;

        public MyViewHolder(View itemView) 

            super(itemView);
            mPhotoImageView = (ImageView) itemView.findViewById(R.id.iv_photo);
            itemView.setOnClickListener(this);
        

        @Override
        public void onClick(View view) 

            int position = getAdapterPosition();
            if(position != RecyclerView.NO_POSITION) 
                SinglePicture spacePhoto = mSpacePhotos[position];

                Intent intent = new Intent(mContext, PictureDetail.class);
                intent.putExtra(PictureDetail.EXTRA_SPACE_PHOTO, spacePhoto);
                startActivity(intent);
            
        
    

    private SinglePicture[] mSpacePhotos;
    private Context mContext;

    public ImageGalleryAdapter(Context context, SinglePicture[] spacePhotos) 
        mContext = context;
        mSpacePhotos = spacePhotos;
    

图片详情

public class PictureDetail extends AppCompatActivity 

public static final String EXTRA_SPACE_PHOTO = "PictureDetail.SPACE_PHOTO";

private ImageView mImageView;

@SuppressLint("CheckResult")
@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery_detail);

    mImageView = (ImageView) findViewById(R.id.image);
    SinglePicture spacePhoto = getIntent().getParcelableExtra(EXTRA_SPACE_PHOTO);

    Glide.with(this)

            .asBitmap()

            .load(spacePhoto.getUrl())

            //.listener(new RequestListener<String, Bitmap>()
            .listener(new RequestListener<Bitmap>() 
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) 
                    return false;
                

                @Override
                public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) 
                    return false;
                



                public void onPalette(Palette palette) 
                    if (null != palette) 
                        ViewGroup parent = (ViewGroup) mImageView.getParent().getParent();
                        parent.setBackgroundColor(palette.getDarkVibrantColor(Color.GRAY));
                    
                
            )

            .into(mImageView);


解析 JSON

public class JSON_GallReader extends AppCompatActivity 


SQLiteDatabase sqLiteDatabase;
String HttpJSonURL = config.JSON_GL;
ProgressDialog progressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.json_reader);

    SQLiteDataBaseBuild();
    SQLiteTableBuild();
    DeletePreviousData();

    new StoreJSonDataInToSQLiteClass(JSON_GallReader.this).execute();



private class StoreJSonDataInToSQLiteClass extends AsyncTask<Void, Void, Void> 

    public Context context;

    String FinalJSonResult;


    public StoreJSonDataInToSQLiteClass(Context context) 

        this.context = context;
    

    @Override
    protected void onPreExecute() 

        super.onPreExecute();

        progressDialog = new ProgressDialog(JSON_GallReader.this);
        progressDialog.setTitle("LOADING");
        progressDialog.setMessage("Please Wait");
        progressDialog.show();

    

    @Override
    protected Void doInBackground(Void... arg0) 

        HttpServiceClass httpServiceClass = new HttpServiceClass(HttpJSonURL);

        try 
            httpServiceClass.ExecutePostRequest();


            if (httpServiceClass.getResponseCode() == 200) 

                FinalJSonResult = httpServiceClass.getResponse();

                if (FinalJSonResult != null) 

                    JSONArray jsonArray = null;
                    try 

                        JSONObject jsonObj = new JSONObject(FinalJSonResult);

                        // Getting JSON Array node
                        JSONArray gallery = jsonObj.getJSONArray("gallery");


                        // looping through the Gallery
                        for (int i = 0; i < gallery.length(); i++) 
                            JSONObject c = gallery.getJSONObject(i);
                            final int id = i;
                            String jr_id = c.getString("id");
                            String jr_descr = c.getString("cover");
                            String jr_name = c.getString("title");
                            String jr_date = c.getString("descr");

** 问题来了**

                            String SQLiteDataBaseQuery = "INSERT INTO overall_table (id,des,name,date,imgurl,fburl,fbid) VALUES('"+id+"', '"+jr_descr+"',** HERE IS THE PROBLEM** );";

                            sqLiteDatabase.execSQL(SQLiteDataBaseQuery);



                        


                     catch (JSONException e) 
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    
                
             else 

                Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
            
         catch (Exception e) 
            // TODO Auto-generated catch block
            e.printStackTrace();
        



        return null;
    

    @Override
    protected void onPostExecute(Void result)

    
        sqLiteDatabase.close();

        progressDialog.dismiss();

        Toast.makeText(JSON_Reader.this,"Load Done", Toast.LENGTH_LONG).show();

    



public void SQLiteDataBaseBuild()

    sqLiteDatabase = openOrCreateDatabase(SQLiteHelper.DATABASE_NAME, Context.MODE_PRIVATE, null);




public void SQLiteTableBuild()

        sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS "+SQLiteHelper.TAB_NAME+"("+SQLiteHelper.table_id+" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
            + SQLiteHelper.table_desc+" VARCHAR, " and so on..





public void DeletePreviousData()

    sqLiteDatabase.execSQL("DELETE FROM "+ TAB_NAME+"");


当前 JSON(也可以随意编辑这个)


  "gallery": [
    
      "cover": "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
      "title": "Test Gallery 1",
      "desc": "Here you go number one",
      "pics": [
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png"
      ]
    ,
    
      "cover": "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
      "title": "Here you go number 2",
      "desc": "Hier steht die Beschreibung zur Gallery",
      "pics": [
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png"
      ]
    ,
    
      "cover": "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
      "title": "Here you go number three",
      "desc": "Hier steht die Beschreibung zur Gallery",
      "pics": [
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png",
        "https://storage.googleapis.com/creator-academy-assets/thumbnails/thumbnails-z1-1.png"
      ]
    
  ]

问题

如您所见,在我的 JSON_GallReader 中,当我遍历我的 JSON 长度时,我真的不知道如何通过一个数组(图库)循环,该数组是“图片”数组的一部分 - 基本上我可以 JSONArray pics=jsonObj.getJSONArray("pics"); 和 对于 (int j = 0; j

但是

有什么方法可以将我的所有链接放在一个表中,还是我必须为所有链接创建一个单独的表?

我的第二个想法是:也许我应该得到两个 JSON,一个用于解析图像库,一个只包含 IMG 链接,当单击 ListView 项目时,它们将被即时解析。那会更好吗? 顺便说一句,我正在使用 GLIDE。

【问题讨论】:

【参考方案1】:

您可以通过以下代码将所有图片数组存储到一个列表中

List<String> pics_list =new ArrayList();
JsonObject response=new JsonObject(s);
JsonArray gallery =response.getJsonArray("gallery");
if(gallery!=null && gallery.length()>0)
for(int i=0;i<gallery.length();i++)
JsonObject json=gallery.getJsonObject(i);
JsonArray pics =json.getJsonArray("pics");
String [] arr=new String[pics.length];
for(int j=0; j<pics.length();j++)

arr[j]=pics.optstring(i);


for(int k=0 ;k<arr.length();k++)
pics_list.add(arr[k]);




之后,您可以使用 sqlite 中的 update 或 create 命令将此列表保存到数据库中

【讨论】:

非常感谢!你的意见是,我现在应该将图像链接插入与封面、标题、描述部分相同的 sql 数据库中还是创建一个单独的数据库?我正在考虑这样的查询:“INSERT INTO images_table (id,cover,title,desc,IMGURLSHERE) VALUES('"+i+"', '"+jr_cover+"', '"+jr_title+"', '" +jr_desc+"', '"+arr+"');";只用 arr[1] arr[2] 等等......你有什么建议? 您可以将所有图像存储在一个表中,并且可以使用插入语句更快地插入 谢谢,莫希特。对我有帮助 ContentValues 值=新 ContentValues(); for (int u=0; u 我的问题是,img-links 列的数量应该是动态的,所以可能 gallery[0] 在 pics 数组中有 10 个 url,gallery[1] 有 11 个 url.. 我想那里将是一个大问题,如果之后我循环通过 row[0] 并且在开头没有定义列 [11]

以上是关于Android 图片库 JSON / SQLite 带可变数量的图像的主要内容,如果未能解决你的问题,请参考以下文章

在 Android 中从 sqlite 创建 Json

Android SQLite, JSON, List 用于存储常量对象

以 JSON 或 SQLITE (Android) 存储数据

如何在json android中返回多行并将其传递给sqlite

JSON文件VS SQLite android

Android 数据存储,何时使用 Sqlite,何时使用 JSON,Linq 替代方案