Coding of Upload Assignment

September 23,2016

Here the coding of upload assignment.

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

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

        @Override
        public Object getItem(int position) {
            return list_sub.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.assignment_layout, parent, false);
            }
                txt_sub = (TextView) convertView.findViewById(R.id.textView_sub);
                txt_descr = (TextView) convertView.findViewById(R.id.textView_desc);

                btn_dl = (Button) convertView.findViewById(R.id.button_dld);
                btn_dl.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //String t = txt_sub.getText().toString();
                        //String d = txt_descr.getText().toString();
                        String downld = list_download.get(position).replace("\\\\","");
                        downloadFile(downld);
                       // DownloadAssignment dn = new DownloadAssignment();
                        //dn.execute( downld);


                    }
                });
                txt_sub.setText(list_sub.get(position));
                txt_descr.setText(list_desc.get(position));
                //btn_dl.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(Assignment.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(Assignment.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(Assignment.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(Assignment.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 ShowAssignment extends AsyncTask<String,Integer,Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {
            ArrayList<NameValuePair> arrayList = new ArrayList<>();
            arrayList.add(new BasicNameValuePair("stream", params[0]));
            arrayList.add(new BasicNameValuePair("year",params[1]));
            //downloadFile(params[0]);
            try {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(getString(R.string.path)+"download_assignment.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 Subject = jsonObject.getJSONArray("Subject");
                    JSONArray Description = jsonObject.getJSONArray("desc");
                    JSONArray URL = jsonObject.getJSONArray("url");
                    for(int i=0;i<Subject.length();i++){
                        list_sub.add(Subject.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(Assignment.this,"Assignment Downloaded",Toast.LENGTH_SHORT).show();
                CustomAdapter adapter = new CustomAdapter();
                lv.setAdapter(adapter);
            }
            else{
                Toast.makeText(Assignment.this,"Download failed!!",Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(aBoolean);
        }
    }

}

Leave a comment