Android Recycler视图下载按钮问题 [英] Android recycler view download button problem

查看:86
本文介绍了Android Recycler视图下载按钮问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的回收商视图屏幕:

Here is my recycler view screen :

我要检查文件名是否存在,然后显示打开按钮,如果不存在,则显示下载按钮.我的文件名是保存在主活动中的字符串,因此需要从主活动中检查它.并且文件名的格式为categoryname + sub-categ + samperpapername.我想检查加载回收器视图时是否所有项目都存在该文件,如果存在则仅更改该特定项目的按钮,如果没有,则显示下载按钮.我的适配器类在下面

I Want to check if the file name exsists then show open button, while if it dosent then show download button. my file name is a string saved in main activity so need to check it from main activity. And the file name has pattern of categoryname+sub-categ+samperpapername . I want to check if the file exsist for all items when recycler view is loaded, if it exsit then only change the button of that particular item, and if it dosent then show the download button. my adapter class is below

    public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {


private Context context;
List<ContentDetails> contentDetails;

private onItemClickListener mListener;
private boolean activate;

public interface onItemClickListener {
    void onItemClick(int position);
    void onDownloadClick(int position);
    void onOnlineClick(int position);
    void onDownloadOpenClick(int position);
}
public void setOnItemClickListener(onItemClickListener listener) {
    mListener = listener;
}






public ContentAdapter(List<ContentDetails> contentDetails, Context context){
    super();
    this.contentDetails = contentDetails;
    this.context = context;
}

public void activateButtons(boolean activate , int postion) {
    this.activate = activate;
     //need to call it for the child views to be re-created with buttons.
    notifyItemChanged(postion);
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.content_list, parent, false);
    ViewHolder viewHolder = new ViewHolder(v, mListener);
    return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    //Getting the particular item from the list
    ContentDetails contentDetail =  contentDetails.get(position);


    holder.textViewName.setText(contentDetail.getCunit());
    holder.textViewPublisher.setText(contentDetail.getCtitle());
    holder.textViewLink.setText(contentDetail.getClink());


    if (activate) {
        holder.buttonDownloadOpen.setVisibility(View.VISIBLE);
    } else {
        holder.buttonDownloadOpen.setVisibility(View.GONE);
    }


}

@Override
public int getItemCount() {
    return contentDetails.size();
}

class ViewHolder extends RecyclerView.ViewHolder{
    //Views
    public TextView textViewName;
    public TextView textViewPublisher;
    public TextView textViewLink;
    public Button buttonDownload;
    public Button buttonOnline , buttonDownloadOpen;
    int themeColor;
    int appColor;


    //Initializing Views
    public ViewHolder(View itemView  , final onItemClickListener listener) {
        super(itemView);

        textViewName = (TextView) itemView.findViewById(R.id.textViewName);
        textViewPublisher = (TextView) itemView.findViewById(R.id.textViewPublisher);
        textViewLink = (TextView) itemView.findViewById(R.id.textViewLink);
        buttonDownload = (Button) itemView.findViewById(R.id.btn_download);
        buttonOnline = (Button) itemView.findViewById(R.id.btn_viewonline);
        buttonDownloadOpen = (Button) itemView.findViewById(R.id.btn_downloadopen);




        SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(context);
        appColor = app_preferences.getInt("color", 0);
        themeColor = appColor;

        if (themeColor == 0){
            buttonDownload.setBackgroundColor(0xff000428);
            buttonOnline.setBackgroundColor(0xff000428);
        }else {
            buttonDownload.setBackgroundColor(Config.color);
            buttonOnline.setBackgroundColor(Config.color);
        }


        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null){
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION){
                        listener.onItemClick(position);
                    }
                }
            }
        });

        buttonDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        listener.onDownloadClick(position);
                    }
                }
            }
        });

        buttonOnline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        listener.onOnlineClick(position);
                    }
                }
            }
        });
        buttonDownloadOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        listener.onDownloadOpenClick(position);
                    }
                }
            }
        });

    }
}

}

谁能告诉我如何取得可能的结果.我很困惑如何达到这个结果,我需要帮助.任何人都可以帮助,现在如此困惑.而且,如果您还需要查看主要活动代码,请告诉我,我也会发布该代码,但是它太大了.

Can anyone tell me how can i achieve possible result. I am so confused how to achieve this result.I need help with it. Can anyone please help, so confused right now. And if you also require to see the main activity code, then let me know i will post that too but its too large.

我在Mainactivity中下载pdf方法

My downloading pdf method in Mainactivity

        public static void downloadPdf(Context context, String url, String name, String gname , String cname, final Callback callback){
    Uri uri;
    try{
        uri = Uri.parse(url);
    }
    catch(Exception e){

        callback.onError();
        return;
    }

    DownloadManager.Request r = new DownloadManager.Request(uri);

    r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOCUMENTS, gname+cname+name );
    r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);

    final DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    final long downloadId = dm.enqueue(r);

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                if(intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0) != downloadId){
                    // Quick exit - its not our download!
                    return;
                }

                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                Cursor c = dm.query(query);
                if (c.moveToFirst()) {
                    int columnIndex = c
                            .getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c
                            .getInt(columnIndex)) {

                        String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));




                        intent = new Intent(context , PdfOffline.class);
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        intent.putExtra("newuri", uriString);

                        callback.onSuccess();

                        context.startActivity(intent);

                    }
                    else{
                        callback.onError();
                    }
                }
                else{
                    callback.onError();
                }
                context.unregisterReceiver(this);
            }
        }
    };

    context.registerReceiver(receiver, new IntentFilter(
            DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

然后我用这个来称呼它:

then i call it using this :

     @Override
        public void onDownloadClick(int position) {
            String file_url = listContentDetails.get(position).getClink();
            String file_title = listContentDetails.get(position).getCtitle();
            String cname = getIntent().getExtras().getString("catename");
            String gname = getIntent().getExtras().getString("gradename");

            if (ContextCompat.checkSelfPermission(MainActivity3.this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE )
                    != PackageManager.PERMISSION_GRANTED) {




                ActivityCompat.requestPermissions(MainActivity3.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

            } else if (ContextCompat.checkSelfPermission(MainActivity3.this, Manifest.permission.READ_EXTERNAL_STORAGE )
                    != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(MainActivity3.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
            }

            else {
                pdfdw(file_url,file_title , gname , cname , position);

            }

        }



      private void pdfdw(String url , String title , String gname , String cname , final int postion){

    final ProgressDialog dialog = ProgressDialog.show(this,
            title,
            "Downloading... " , true, true);
    dialog.setCancelable(false);
    downloadPdf(this, url, title,gname, cname,
            new Callback() {
                @Override
                public void onSuccess() {
                    dialog.dismiss();
                    adapter.activateButtons(true , postion);

                }

                @Override
                public void onError() {
                    dialog.dismiss();
                    Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
                }
            });

}

推荐答案

简短的回答,您可以在成功下载(最好是数据库)后将下载参考存储在数据库或共享偏好中,然后检查记录以查看是否存在.

Short answer you can store your download references in a database or shared prefrence after a successful download,(preferably a database )then check against your records to see if it exists .

 public static String all_records(Context act)
    {

        SharedPreferences prefs = act.getSharedPreferences(svars.sharedprefsname, act.MODE_PRIVATE);

        String json = prefs.getString("all_records", "");
      //  Log.e("Downloads ",""+json);

        return json;
    }



public static void add_download(Context act,String url)
    {
        JSONArray ja=new JSONArray();
        try {
        ja=new JSONArray(all_records(act));
            JSONObject jo=new JSONObject();
            jo.put("url",url);
            ja.put(jo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        SharedPreferences.Editor saver =act.getSharedPreferences(svars.sharedprefsname, act.MODE_PRIVATE).edit();



        saver.putString("all_records",ja.toString());
        saver.commit();


    }
 public static boolean is_downloaded(Context act,String url)
    {
        JSONArray ja=new JSONArray();
        try {
        ja=new JSONArray(all_records(act));
            for (int i=0;i<ja.length();i++)
            {
                try {
                    Log.e("Check ", "" + ja.getJSONObject(i).getString("url") + " Against " + url);
                    if (ja.getJSONObject(i).getString("url").equalsIgnoreCase(url)) {
                        return true;
                    }
                }catch (Exception ex){}
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }



        return false;
    }

因此将网址添加到您的共享首选项

so add the url to your shared preference

if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action))
 {
add_download(/*your context*/,url); ...

最后在ContentAdapter中替换

finally in your ContentAdapter replace

如果(激活){ holder.buttonDownloadOpen.setVisibility(View.VISIBLE); } 别的 { holder.buttonDownloadOpen.setVisibility(View.GONE); }

if (activate) { holder.buttonDownloadOpen.setVisibility(View.VISIBLE); } else { holder.buttonDownloadOpen.setVisibility(View.GONE); }

使用

if (is_downloaded(context,contentDetail.getClink())) {
        holder.buttonDownloadOpen.setVisibility(View.VISIBLE);
     } else {
        holder.buttonDownloadOpen.setVisibility(View.GONE);
     }

如果您确实需要使用下载管理器,请尝试使用此功能

if you indeed need to use download manager try using this function

boolean is_downloaded(String url)
    {

        DownloadManager downloadManager = (DownloadManager) act.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Query myDownloadQuery = new DownloadManager.Query();
        myDownloadQuery.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
      //  myDownloadQuery.setFilterByStatus(DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING);
        Cursor cursor = downloadManager.query(myDownloadQuery);
        if(cursor.moveToFirst())
        {
            do{
if(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI)).equalsIgnoreCase(url)){return true;}
           // Log.e("Downlaods :",""+cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI)));

        }while(cursor.moveToNext());
        }else{
            Log.e("Downlaods :","No downloads");

        }

        cursor.close();
        return false;
    }
   

在ContentAdapter中替换

in your ContentAdapter replace

如果(激活){ holder.buttonDownloadOpen.setVisibility(View.VISIBLE); } 别的 { holder.buttonDownloadOpen.setVisibility(View.GONE); }

if (activate) { holder.buttonDownloadOpen.setVisibility(View.VISIBLE); } else { holder.buttonDownloadOpen.setVisibility(View.GONE); }

使用

if (is_downloaded(contentDetail.getClink())) {
        holder.buttonDownloadOpen.setVisibility(View.VISIBLE);
     } else {
        holder.buttonDownloadOpen.setVisibility(View.GONE);
     }

这篇关于Android Recycler视图下载按钮问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆