Coding of Download Notice

September 28,2016

Here the coding is:

class CustomAdapter extends BaseAdapter{
        LayoutInflater lin=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);


        @Override
        public int getCount() {
            return list_title.size();
        }

        @Override
        public Object getItem(int position) {
            return list_title.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if(convertView==null){
                convertView=lin.inflate(R.layout.notice_layout,parent,false);


            }
            txt_title=(TextView)convertView.findViewById(R.id.textView_notice_title);
            txt_desc=(TextView)convertView.findViewById(R.id.textView_notice_desc);
            b1=(Button)convertView.findViewById(R.id.button_download);
            b1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

//                            String t = txt_title.getText().toString();
//                            String d = txt_desc.getText().toString();
                    String downld = list_download.get(position).replace("\\\\","");
                    downloadFile(downld);
//                    DownloadNotices sn = new DownloadNotices();
//                    sn.execute(downld);



                }
            });


            txt_title.setText(list_title.get(position));
            txt_desc.setText(list_desc.get(position));
            //b1.setText(list_download.get(position));

            return convertView;
        }
    }




    void downloadFile(String path){
         manager=(DownloadManager)getSystemService(DOWNLOAD_SERVICE);

        String fileName = path.split("/")[path.split("/").length-1];

        file = new File(Environment
                .getExternalStorageDirectory().toString()
                + "/Download/"+fileName);

        String temp_path = path.replaceAll(" " , "%20");
        Uri uri = Uri.parse(temp_path);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setDescription("File Download").setTitle(fileName);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
        request.setVisibleInDownloadsUi(true);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        downloadReference = manager.enqueue(request);
        Toast.makeText(Notice.this,"Download Queued",Toast.LENGTH_SHORT).show();
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long ref = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);
                if(ref==downloadReference){
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(ref);
                    Cursor cursor = manager.query(query);
                    cursor.moveToFirst();
                    int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    String savedFileName = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                    if(status==DownloadManager.STATUS_SUCCESSFUL){
                        AlertDialog.Builder builder = new AlertDialog.Builder(Notice.this);
                        builder.setTitle("File saved");
                        builder.setMessage("File has been downloaded to the following directory:\n" + savedFileName);
                        builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.setPositiveButton("Open File", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                try {
                                    Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
                                    String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
                                    String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                                    myIntent.setDataAndType(Uri.fromFile(file),mimetype);
                                    startActivity(myIntent);
                                } catch (Exception e) {
                                    Toast.makeText(Notice.this, "File is not valid or there is no application that can handle the file", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    }
                    else if(status==DownloadManager.STATUS_FAILED){

//                        Log.d("log_dm_status",cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION)));
                        AlertDialog.Builder builder = new AlertDialog.Builder(Notice.this);
                        builder.setTitle("Error downloading attachment");
                        builder.setMessage("There was an error downloading the file. Please try again.");
                        builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    }
                }
            }
        };
        registerReceiver(receiver,filter);
    }
    class ShowNotice extends AsyncTask<String,Integer,Boolean>{


        @Override
        protected Boolean doInBackground(String... params) {
            ArrayList<NameValuePair> arrayList= new ArrayList<>();
            arrayList.add(new BasicNameValuePair("stream",params[0]));


            try {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(getString(R.string.path)+"notice_download.php");
                post.setEntity(new UrlEncodedFormEntity(arrayList));
                HttpResponse r = client.execute(post);
                HttpEntity e = r.getEntity();
                InputStream is = e.getContent();
                BufferedReader bf = new BufferedReader(new InputStreamReader(is));
                StringBuilder b = new StringBuilder();
                String line;
                while ((line = bf.readLine()) != null) {
                    b.append(line);
                }
                String result = b.toString();
                Log.d("result", result);
                JSONObject jsonObject = new JSONObject(result);
                String response = jsonObject.getString("result");
                if (response.equalsIgnoreCase("ok")) {
                    JSONArray Title = jsonObject.getJSONArray("Title");
                    JSONArray Description = jsonObject.getJSONArray("desc");
                    JSONArray URL = jsonObject.getJSONArray("url");
                    for(int i=0;i<Title.length();i++){
                        list_title.add(Title.getString(i));
                        list_desc.add(Description.getString(i));
                        list_download.add(URL.getString(i));
                    }
                    return true;
                } else {
                    //Log.d("no data fetched", response);
                }
            }


            catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            if(aBoolean==true){
                Toast.makeText(Notice.this,"Notice Downloaded",Toast.LENGTH_SHORT).show();
                CustomAdapter adapter = new CustomAdapter();
                lv.setAdapter(adapter);
            }
            else{
                Toast.makeText(Notice.this,"Download failed!!",Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(aBoolean);
        }
    }}