Upload Notice

September 14,2016

Today i have done the coding of notice upload.

public void showFileChooser(View v) {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/pdf");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    try {
        startActivityForResult(Intent.createChooser(intent, "Select a file to upload"), 0);
    } catch (Exception ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Error",
                Toast.LENGTH_SHORT).show();
    }


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    switch (requestCode) {
        case 0:
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                String path;
                try {
                    path = getRealPathFromURI(uri);
                    Log.d("log_tag",path);
                    f = new File(path);
                    isFileSelected = true;


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);

}

private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) {
        result = contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}

class UploadTask extends AsyncTask<String,Integer,Boolean>{

    @Override
    protected Boolean doInBackground(String... params) {
        return uploadFile(params[0]);
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if(aBoolean){
            //String id=edt_id.getText().toString();
             title=edt_title.getText().toString();
             type=sp_notice_type.getSelectedItem().toString();
             description=edt_description.getText().toString();
             url=getString(R.string.path)+"Notices/"+f.getName();

            UploadNotice up=new UploadNotice();
            up.execute(title,type,description,url);
           // Toast.makeText(NoticeUp.this,"File Uploaded",Toast.LENGTH_SHORT).show();

        }
        else{
            Toast.makeText(NoticeUp.this,"Uploading file failed",Toast.LENGTH_SHORT).show();
        }


    }
}

boolean uploadFile(String filepath) {
    Log.d("log_tag",filepath);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1024 * 1024;
    String responseFromServer="";
    String urlString=getString(R.string.path)+"upload_file.php";
    try{
        FileInputStream fileInputStream = new FileInputStream(new File(filepath));

        URL url=new URL(urlString);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filepath + "\"" + lineEnd);
        dos.writeBytes(lineEnd);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while(bytesRead>0){
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        }
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        fileInputStream.close();
        dos.flush();
        dos.close();




        inStream = new DataInputStream(conn.getInputStream());
        String str;
        while ((str = inStream.readLine()) != null){
    }
        inStream.close();
        return true;

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


}


public void uploadButton(View v){
    dia=new ProgressDialog(NoticeUp.this);
    dia.setTitle("Loading");
    dia.show();
    if(isFileSelected) {

        final AlertDialog.Builder builder=new AlertDialog.Builder(NoticeUp.this);
        builder.setTitle("Upload Notice");
        builder.setMessage("Do you want to upload this notice??");
        builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int i) {
                dia.dismiss();
                new UploadTask().execute(f.getAbsolutePath());
                Toast.makeText(NoticeUp.this,"Notice Uploaded!!",Toast.LENGTH_SHORT).show();

            }
        });
        builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
                dia.dismiss();
                Toast.makeText(NoticeUp.this,"Uploading Failed!!",Toast.LENGTH_SHORT).show();
            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();





    }
    else{
        Toast.makeText(this,"Please Select a file!!",Toast.LENGTH_SHORT).show();
    }

}
class UploadNotice extends AsyncTask<String,Integer,Boolean>{

    @Override
    protected Boolean doInBackground(String... params) {

        ArrayList<NameValuePair> list=new ArrayList<>();
        list.add(new BasicNameValuePair("Title",params[0]));
        list.add(new BasicNameValuePair("Type",params[1]));
        list.add(new BasicNameValuePair("Description",params[2]));
        list.add(new BasicNameValuePair("URL",params[3]));
        try{
            HttpClient client=new DefaultHttpClient();
            HttpPost post=new HttpPost(getString(R.string.path)+"notice_upload.php");
            post.setEntity(new UrlEncodedFormEntity(list));
            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 res=b.toString();
            Log.d("result",res);
            JSONObject jsonObject=new JSONObject(res);
            String resp=jsonObject.getString("result");
            if(resp.equalsIgnoreCase("ok")) {
               // Toast.makeText(NoticeUp.this, "Notice uploaded", Toast.LENGTH_SHORT).show();

                return true;
            }
            else{
                Log.d("no data stored",resp);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }

        return false;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        if(aBoolean==true){


        super.onPostExecute(aBoolean);
          //  Toast.makeText(NoticeUp.this,"Data inserted",Toast.LENGTH_SHORT).show();
        }
        //else{
          //  Toast.makeText(NoticeUp.this,"Data not inserted",Toast.LENGTH_SHORT).show();
        //}
      //
    }
}}

Leave a comment