Php Script of Download Notice

September 27,2016

PHP Script of download notice:

<?php
$stream = $_POST[‘stream’];
$title = array();
$desc = array();
$url = array();
$con=new mysqli(“localhost”,”root”,””,”login”);
if($con->connect_errno){
echo “connection error”;
}
$query1=”select Title,Description,URL from upload_notice where Type=’$stream'”;
$result =$con->query($query1);
if($result->num_rows>0){
while($sql_arr=mysqli_fetch_array($result)){
array_push($title,$sql_arr[‘Title’]);
array_push($desc,$sql_arr[‘Description’]);
array_push($url,$sql_arr[‘URL’]);
}
$response=’ok’;
}
else
{
$response=’error’;
}
echo json_encode(array(‘result’=>$response,’Title’=>$title,’desc’=>$desc,’url’=>$url));
?>

Download Notice

September 26,2016

Today i have worked on the activity download notice. In this activity student may download the notices of their particular semester,particular branch.The data is retrieved from the database.The downloaded file is in pdf format.

Phpscript of Download any File

September 26,2016

<?php
$target_path = “Assignments/”;

/* Add the original filename to our target path.
Result is “audio/filename.extension” */
$target_path = $target_path . basename( $_FILES[‘uploadedfile’][‘name’]);

if(move_uploaded_file($_FILES[‘uploadedfile’][‘tmp_name’], $target_path)) {
echo “The file “. basename( $_FILES[‘uploadedfile’][‘name’]).
” has been uploaded”;
chmod (“uploads/”.basename( $_FILES[‘uploadedfile’][‘name’]), 0644);
} else{
echo “There was an error uploading the file, please try again!”;
echo “filename: ” . basename( $_FILES[‘uploadedfile’][‘name’]);
echo “target_path: ” .$target_path;
}
?>

 

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);
        }
    }

}

Php Script for Download Assignment

September 22,2016

Php Script:

<?php
$stream = $_POST[‘stream’];
$year=$_POST[‘year’];
//$stream=’CSE’;
//$year=’1′;
$sub=array();
$desc=array();
$url=array();
$con=new mysqli(“localhost”,”root”,””,”login”);
if($con->connect_errno){
echo “connection error”;
}
$query1=”select Subject,Description,URL from upload_asgnmt where Stream=’$stream’ and Year=’$year'”;
$result =$con->query($query1);
if($result->num_rows>0){
while($sql_arr=mysqli_fetch_array($result)){
array_push($sub,$sql_arr[‘Subject’]);
array_push($desc,$sql_arr[‘Description’]);
array_push($url,$sql_arr[‘URL’]);
}
$response=’ok’;
}
else
{
$response=’error’;
}
echo json_encode(array(‘result’=>$response,’Subject’=>$sub,’desc’=>$desc,’url’=>$url));
?>

Download Assignment

September 21,2016

Today i have worked on the activity download assignment. In this activity student may download the assignments of their particular semester,particular branch.The data is retrieved from the database.The downloaded file is in pdf format.

Coding Part

September 20,2016

Today i have worked on the coding of upload assignment.

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 FetchSubject extends AsyncTask<String,Integer,Boolean> {

    @Override
    protected Boolean doInBackground(String... params) {
        ArrayList<NameValuePair> arrayList = new ArrayList<>();
        arrayList.add(new BasicNameValuePair("sem", params[0]));
        arrayList.add(new BasicNameValuePair("stream", params[1]));
        Log.d("param0", params[0]);
        Log.d("param1", params[1]);
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(getString(R.string.path) + "subject_fetch.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");
                for (int i = 0; i < Subject.length(); i++) {
                    list_subject.add(Subject.getString(i));
                    att = list_subject.get(i).split(",");
                    //String[] items={ att.toString()};

                }
                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(UploadFile.this,"Notice Downloaded",Toast.LENGTH_SHORT).show();
            ad = new ArrayAdapter<>(UploadFile.this, android.R.layout.simple_list_item_1, att);
            sp_sub.setAdapter(ad);
        }

        super.onPostExecute(aBoolean);
    }
}

class UploadAssign 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 year=sp_sem.getSelectedItem().toString();
            String stream=sp_stream.getSelectedItem().toString();
            String sub=edt_sub.getText().toString();
            String desc=edt_desc.getText().toString();
            String url=getString(R.string.path)+"Assignment/"+f.getName();
            UploadAssignment up=new UploadAssignment();
            up.execute(year,stream,sub,desc,url);

        }
        else{
            Toast.makeText(UploadFile.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_asgnmt.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 uploadAssignmentButton(View v) {
    dia=new ProgressDialog(UploadFile.this);
    dia.setTitle("Loading");
    dia.show();
    if(isFileSelected) {final AlertDialog.Builder builder=new AlertDialog.Builder(UploadFile.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 UploadAssign().execute(f.getAbsolutePath());
                Toast.makeText(UploadFile.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(UploadFile.this,"Uploading Failed!!",Toast.LENGTH_SHORT).show();
            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();

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

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

    @Override
   protected Boolean doInBackground(String... params) {
        ArrayList<NameValuePair> list=new ArrayList<>();
        list.add(new BasicNameValuePair("Semester",params[0]));
        list.add(new BasicNameValuePair("Stream",params[1]));
        list.add(new BasicNameValuePair("Subject",params[2]));
        list.add(new BasicNameValuePair("Description",params[3]));
        list.add(new BasicNameValuePair("URL",params[4]));

        try{
            HttpClient client=new DefaultHttpClient();
            HttpPost post=new HttpPost(getString(R.string.path)+"upload_assignment.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){
            Toast.makeText(UploadFile.this,"Data inserted",Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(UploadFile.this,"Data not inserted",Toast.LENGTH_SHORT).show();
        }
        super.onPostExecute(aBoolean);
    }
}
    }

Php Script of Upload Assignment

September 19,2016

Today i have worked on the php script of upload assignment.

<?php
$sem=$_POST[‘Semester’];
$stream=$_POST[‘Stream’];
$sub=$_POST[‘Subject’];
$description=$_POST[‘Description’];
$url=$_POST[‘URL’];

$con=new mysqli(“localhost”,”root”,””,”login”);
if($con->connect_errno)
{
$response=”db_err”;
}
else
{
$query1=”INSERT into upload_asgnmt values(null,’$sem’,’$stream’,’$sub’,’$description’,’$url’,null)”;
$result=$con->query($query1);
if($result){
$response=’ok’;
}
else{
$response=’error’;
}
}
echo json_encode(array(‘result’=>$response));
$con->close();
?>

Upload Assignment

September 16,2016

Today i have started my next activity i.e. upload assignment.This activity is quite similar to upload notice activity. Teacher have to upload assignment of a particular subject for a particular branch.The file must be in pdf format.The data of assignment is stored in  database.

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();
        //}
      //
    }
}}