Uploading files in android is a common feature that most developers find hard to work with. There are so many methods and ways that are provided to offer solutions while doing file upload in android.
In this article, we shall discuss the method that we have worked with it successfully and have found as secure, fast, and reliable.
The fast android networking library is available in GitHub and is developed by amitshekhariitbhu
In our previous articles, we have discussed the topics below
- create a register application using a fast android networking library
- create a login application using a fast android networking library
Let’s now focus on how to upload a file in android using the fast android networking library. The files that this library can upload include images, videos, and pdf and word documents.
- Start by creating a project in android studio (for this discussion we shall use java as the language of programming)
You can convert the files we shall create using java language to kotlin language by following this article we developed on past, how to convert java files to kotlin files
- In the xml file, create an image view which will preview the image and a button which will be used during upload to submit the file as shown below
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<LinearLayout
android:id="@+id/lay_purpose_gallery_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="upload image"
android:textColor="#000"
android:textSize="14sp" />
<RelativeLayout
android:id="@+id/lay_rel_gallery"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:background="@drawable/edittext_border"
android:orientation="vertical">
<ImageView
android:id="@+id/image_add_gallery"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="5dp"
android:contentDescription="@string/app_name"
android:scaleType="fitXY" />
<TextView
android:id="@+id/text_select3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:drawableStart="@drawable/add_image"
android:drawablePadding="5dp"
android:gravity="center"
android:text="select file"
android:textColor="@color/add_properties_text"
android:textSize="14sp" />
</RelativeLayout>
<Button
android:id="@+id/btn_sub"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="32dp"
android:background="@drawable/submit_button"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:text="@string/submit"
android:textColor="@color/white"
android:textSize="14sp"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintStart_toStartOf="parent" />
</LinearLayout>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
- Next, add the fast networking library from GitHub
dependencies {
implementation 'com.amitshekhar.android:android-networking:1.0.2'
}
- In the manifest file add the internet permission, read external storage permission, write external storage permission as follows
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
In the application tag still inside the manifest file set request legacy to true as shown
<application
android:requestLegacyExternalStorage="true">
</application>
- In the java activity,
-In the onCreate method add a network interceptor for debugging
// Adding an Network Interceptor for Debugging purpose :
new OkHttpClient.Builder()
.addNetworkInterceptor(new StethoInterceptor())
.build();
AndroidNetworking.initialize(getApplicationContext());
- Once you click the upload button, you will need to check the version of the android device since you have to request the read external storage permission
uploadfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
imageChooser();
} else {
imageChooser();
}
}
});
Note that image chooser method is the one used to trigger the image picking from your device. The code for choosing the image from the file is as below
public void imageChooser() {
//Pick Image From Gallery
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_PICTURE);
}
- The code for the activity result that you have called in the image chooser method above is as below
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
// compare the resultCode with the
// SELECT_PICTURE constant
if (requestCode == SELECT_PICTURE) {
// Get the url of the image from data
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// update the preview image in the layout
Picasso.get().load(selectedImageUri).into(img_gallery);
String imagepath = getRealPathFromURI(selectedImageUri,this);
myfile = new File(imagepath);
}
}
}
}
- The code for the method get path from URI defined above which gets the full image path from URI is as shown
public String getRealPathFromURI(Uri contentURI, Activity context) {
String[] projection = { MediaStore.Images.Media.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = context.managedQuery(contentURI, projection, null,
null, null);
if (cursor == null)
return null;
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
String s = cursor.getString(column_index);
// cursor.close();
return s;
}
// cursor.close();
return null;
}
- The code for uploading file to the server using the fast android networking library is as below
public void uploadData() {
//URL to upload data to
AndroidNetworking.upload("https://www.example.com/file")
// image to upload
.addMultipartFile("image",myfile)
// other parameter as string
.addMultipartParameter("user_id",userid)
.setTag("uploadTest")
.setPriority(Priority.HIGH)
.build()
.setUploadProgressListener(new UploadProgressListener() {
@Override
public void onProgress(long bytesUploaded, long totalBytes) {
// do anything with progress
showProgressDialog();
}
})
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
// do anything with response
dismissProgressDialog();
Toast.makeText(getApplicationContext(),"Image Uploaded Successfully",Toast.LENGTH_LONG).show();
finish();
}
@Override
public void onError(ANError error) {
// handle error
dismissProgressDialog();
Toast.makeText(getApplicationContext(),"An error occured",Toast.LENGTH_LONG).show();
}
});
}
- The predefined show and dismiss dialog displayed during progress and once finished is as below
public void showProgressDialog() {
pDialog.setMessage(getString(R.string.loading_title));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
public void dismissProgressDialog() {
pDialog.dismiss();
}
Remember to initialize the imports and define the elements at the top of the java file
Having followed the above discussion, you should be able to upload an image or file using the android fast networking library