For media selection from file and uploading over server
Use Fast Networking library
compile 'com.amitshekhar.android:android-networking:1.0.2'
manifest.xml
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-feature android:name="android.hardware.camera.autofocus" />
MainActivity.java
package ratnatech.odishakrushifileupload;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.StringRequestListener;
import com.androidnetworking.interfaces.UploadProgressListener;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
public class MainActivity extends AppCompatActivity {
String str_filePath="";
private final int requestCode = 20;
private static final int PICK_PHOTO = 1958;
private static final int PICK_VIDEO= 1993;
private static final int PICK_AUDIO= 1994;
static final int REQUEST_VIDEO_CAPTURE = 1;
int SPLASH_TIME_OUT=2;
File file;
Spinner subgroup;
EditText edittext; String str_edittext="";
TextView attach_file,file_path,txt_complete;
Button btnSubmit;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setContentView(R.layout.activity_main);
subgroup=findViewById(R.id.subgroup);
edittext=findViewById(R.id.edittext);
attach_file=findViewById(R.id.attach_file);
file_path=findViewById(R.id.file_path);
txt_complete=findViewById(R.id.txt_complete);
btnSubmit=findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
str_edittext=edittext.getText().toString();
if(str_filePath.equals(""))
{
uploadWithoutFile();
}
else {
upload();
}
}
});
}
private void uploadWithoutFile() {
AndroidNetworking.post(Config.setFarmerQna)
.addBodyParameter("user_id","260")
.addBodyParameter("category_id","1")
.addBodyParameter("sub_category_id","1")
.addBodyParameter("dropdown","Mushroom")
.addBodyParameter("questext",str_edittext)
.setTag("test")
.setPriority(Priority.HIGH)
.build()
.getAsString(new StringRequestListener() {
@Override public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}
@Override public void onError(ANError error) {
// handle error Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
}
});
}
private void upload() {
AndroidNetworking.upload(Config.setFarmerQna)
.addMultipartFile("file",file)
.addMultipartParameter("user_id","260")
.addMultipartParameter("category_id","1")
.addMultipartParameter("sub_category_id","1")
.addMultipartParameter("dropdown","Vegetable")
.addMultipartParameter("questext",str_edittext)
.setTag("uploadTest")
.setPriority(Priority.HIGH)
.build()
.setUploadProgressListener(new UploadProgressListener() {
@Override public void onProgress(long bytesUploaded, long totalBytes) {
// do anything with progress
int percentage=(int)((bytesUploaded*100)/totalBytes);
txt_complete.setText(percentage+"% uploaded");
}
})
.getAsString(new StringRequestListener() {
@Override public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
txt_complete.setText("");
new Handler().postDelayed(new Runnable() {
/* * Showing splash screen with a timer. This will be useful when you * want to show case your app logo / company*/
@Override public void run() {
// This method will be executed once the timer is over onBackPressed();
}
}, SPLASH_TIME_OUT);
}
@Override public void onError(ANError error) {
// handle error Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
}
});
}
public void attachFile(View view)
{
// setup the alert builder AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose from ");
// add a list String[] pic = { "Capture Photo","Pick Image from Gallery","Video Record","Pick Video from Gallery","Pick Audio from Gallery"};// "Camera", builder.setItems(pic, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
txt_complete.setText("");
Toast.makeText(MainActivity.this, "Capture Photo", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, requestCode);
break;
case 1:
txt_complete.setText("");
Toast.makeText(MainActivity.this, "Pick Image from Gallery", Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent2, PICK_PHOTO);
break;
case 2:
txt_complete.setText("");
Toast.makeText(MainActivity.this, "Video Record", Toast.LENGTH_SHORT).show();
Intent intent3 = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent3.putExtra("android.intent.extra.durationLimit", 10);
if (intent3.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent3, REQUEST_VIDEO_CAPTURE);
}
break;
case 3:
txt_complete.setText("");
Toast.makeText(MainActivity.this, "Pick Video from Gallery", Toast.LENGTH_SHORT).show();
Intent intent4 = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent4, PICK_VIDEO);
break;
case 4:
txt_complete.setText("");
Toast.makeText(MainActivity.this, "Pick Audio from Gallery", Toast.LENGTH_SHORT).show();
Intent intent5 = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent5, PICK_AUDIO);
break;
}
}
});
// create and show the alert dialog AlertDialog dialog = builder.create();
dialog.show();
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO) {
Uri imageUri = data.getData();
str_filePath = getPath(imageUri);
file_path.setText(str_filePath);
file=new File(str_filePath);//getting image filepath < ------------------------------------------ }
else if(resultCode==RESULT_OK && requestCode==PICK_VIDEO)
{
Uri videoUri = data.getData();
str_filePath = getVideoPath(videoUri);
file_path.setText(str_filePath);
file=new File(str_filePath); // getting video filepath < ------------------------------------------ }
else if(resultCode==RESULT_OK && requestCode==PICK_AUDIO)
{
Uri audioUri = data.getData();
str_filePath = getAudioPath(audioUri);
file_path.setText(str_filePath);
file=new File(str_filePath); // getting audio filepath < ---------------------------------------------- }
else if(this.requestCode == requestCode && resultCode == RESULT_OK)
{
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
Uri cameraUri= getImageUri(this,bitmap);
str_filePath = getPath(cameraUri);
file_path.setText(str_filePath);
file=new File(str_filePath); // getting image captured filepath < ---------------------------------------- }
else if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
Uri videoUri = data.getData();
str_filePath = getVideoPath(videoUri);
file_path.setText(str_filePath);
file=new File(str_filePath); // getting video captured filepath < ----------------------------------- }
}
private String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };//,Video,Audio Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Video cursor.moveToFirst();
return cursor.getString(column_index);
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
private String getVideoPath(Uri uri) {
String[] projection = { MediaStore.Video.Media.DATA };//,Video,Audio Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);//Video,Images cursor.moveToFirst();
return cursor.getString(column_index);
}
private String getAudioPath(Uri uri) {
String[] projection = { MediaStore.Audio.Media.DATA };//,Video,Audio Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);//Video,Images cursor.moveToFirst();
return cursor.getString(column_index);
}
public static void verifyStoragePermissions(Activity activity) { // Check if we have write permission int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE );
}
}
}
activity_main.xml
<ScrollView android:id="@+id/layout_scroll" android:layout_width="match_parent" android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"
tools:context="ratnatech.farmerapp.Fragment.Ask">
<android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" app:popupTheme="@style/MyDarkToolbarStyle" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<!-- TODO: Update blank fragment layout -->
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content">
<Spinner android:id="@+id/subgroup" style="@style/spinner_style" android:drawSelectorOnTop="true" android:entries="@array/spinnerarray"/>
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_margin="10dp" android:layout_height="wrap_content">
<EditText android:id="@+id/edittext" android:layout_width="match_parent" android:layout_height="60dp" android:hint="Type here...." android:gravity="start" android:paddingLeft="5dp" android:background="@drawable/rectangle_border" />
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:orientation="vertical" android:onClick="attachFile" android:layout_marginRight="10dp">
<TextView android:id="@+id/attach_file" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/rectangle_border" android:layout_marginBottom="10dp" android:paddingRight="20dp" android:paddingLeft="20dp" android:drawableRight="@drawable/attachment" android:textColor="#000" android:text="Attach file"/>
<TextView android:id="@+id/file_path" android:layout_width="match_parent" android:layout_height="wrap_content" android:text=""/>
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_marginTop="30dp" android:layout_marginRight="10dp" android:layout_marginLeft="10dp">
<Button android:id="@+id/btnSubmit" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:textColor="#fff" android:text="Submit"/>
<TextView android:id="@+id/txt_complete" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:gravity="center" android:textStyle="bold" android:textSize="35sp" />
</LinearLayout>
</LinearLayout>
</ScrollView>
Comments
Post a Comment