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

Leave a comment