Download image using Circular Progressbar with percentage

Introduction:

   Today I will be taking you through android’s trending Circular ProgressBar with percentage. We have seen in many apps this thing, giving richness to UI,Using two Library classes to initialize the circular progressbar named  CircularProgressBar.java and RateTextCircularProgressBar.java  in this project i will download one image from URL and display into imageview,during that downloading process i will diaplay circular progressbar with percentage.     

demo





Using this code

Step1:
1.Initialize circular progressbar widgets in xml (using your package name with class name)

activity_main.xml
<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="match_parent"
 android:gravity="center_horizontal"
 android:orientation="vertical"
 android:background="#A4A4A4"
 tools:context=".MainActivity" >

<com.kalidoss.widgets.progressbar_circular.RateTextCircularProgressBar
 android:id="@+id/rate_progress_bar"
 android:layout_width="75dp"
 android:layout_height="75dp"
 android:layout_marginBottom="30dp"
 android:visibility="invisible"
 android:layout_marginTop="20dp" />
<ImageView
 android:id="@+id/imageView1"
 android:layout_width="150dp"
 android:layout_height="150dp"
 android:visibility="invisible"
 android:src="@drawable/ic_launcher" />

</LinearLayout>

Step2:
1.This default circular progressbar widgets library

CircularProgressBar.java

package com.kalidoss.widgets.progressbar_circular;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

/**
*
@author kalidoss rajendran
*/
public class CircularProgressBar extends View {
private int mDuration = 100;
private int mProgress = 30;
private Paint mPaint = new Paint();
private RectF mRectF = new RectF();
private int mBackgroundColor = Color.LTGRAY;
private int mPrimaryColor = Color.parseColor("#6DCAEC");
private float mStrokeWidth = 10F;
/**
* 进度æ?¡Ã¦”¹Ã¥?˜Ã§›‘Ã¥?¬
*
{@link #onChange( int duration, int progress, float rate)}
*/
public interface OnProgressChangeListener {
/**
* 进度改å?˜Ã¤Âº‹Ã¤»¶Ã¯¼Å’Ã¥½“进度æ?¡Ã¨¿›Ã¥Âº¦Ã¦”¹Ã¥?˜Ã¯¼Å’Ã¥°±Ã¤¼Å¡Ã¨°Æ’用该方法
@param duration 总进度
@param progress Ã¥½“Ã¥‰?进度
@param rate Ã¥½“Ã¥‰?进度ä¸Å½Ã¦€»Ã¨¿›Ã¥Âº¦Ã§Å¡„Ã¥•† Ã¥?³Ã¯¼Å¡rate = (float)progress / duration
*/
public void onChange( int duration, int progress, float rate);
}
private OnProgressChangeListener mOnChangeListener;
/**
* 设置进度æ?¡Ã¦”¹Ã¥?˜Ã§›‘Ã¥?¬
@param l
*/
public void setOnProgressChangeListener(OnProgressChangeListener l) 
{
mOnChangeListener = l;
}
public CircularProgressBar(Context context) {
super(context);
}
public CircularProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 设置进度æ?¡Ã§Å¡Ã¦Å“€Ã¥¤§Ã¥€¼, 该值è¦? Ã¥¤§Ã¤ÂºÅ½ 0
@param max
*/
public void setMax( int max ) {
if( max < 0 ) {
max = 0;
}
mDuration = max;
}
/**
* Ã¥¾—到进度æ?¡Ã§Å¡Ã¦Å“€Ã¥¤§Ã¥€¼
@return
*/
public int getMax() {
return mDuration;
}
/**
* 设置进度æ?¡Ã§Å¡„Ã¥½“Ã¥‰?çš„Ã¥€¼
@param progress
*/
public void setProgress( int progress ) {
if( progress > mDuration ) {
progress = mDuration;
}
mProgress = progress;
ifmOnChangeListener != null ) {
mOnChangeListener.onChange(mDuration, progress, getRateOfProgress());
}
invalidate();
}
/**
* Ã¥¾—到进度æ?¡Ã¥½“Ã¥‰?çš„Ã¥€¼
@return
*/
public int getProgress() {
return mProgress;
}
/**
* 设置进度æ?¡Ã¨Æ’ξ™¯Ã§Å¡„é¢Å“色
*/
public void setBackgroundColor( int color ) {
mBackgroundColor = color;
}
/**
* 设置进度æ?¡Ã¨¿›Ã¥Âº¦Ã§Å¡„é¢Å“色
*/
public void setPrimaryColor( int color ) {
mPrimaryColor = color;
}
/**
* 设置环形çš„Ã¥®½Ã¥Âº¦
@param width
*/
public void setCircleWidth(float width) {
mStrokeWidth = width;
}

@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
int halfWidth = getWidth() / 2;
int halfHeight = getHeight() /2;
int radius = halfWidth < halfHeight ? halfWidth : halfHeight;
float halfStrokeWidth = mStrokeWidth / 2;
// 设置画笔
mPaint.setColor(mBackgroundColor);
mPaint.setDither(true);
mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(mStrokeWidth);
mPaint.setStyle(Paint.Style.STROKE); //设置图形ä¸ÂºÃ§©ÂºÃ¥¿Æ’
// ç”»Ã¨Æ’ξ™¯
canvas.drawCircle(halfWidth, halfHeight, radius - halfStrokeWidth, mPaint);
// 画当å‰?进度çšåœ†Ã§Å½¯
mPaint.setColor(mPrimaryColor); // 改å?˜Ã§”»Ã§¬”é¢Å“色
mRectF.top = halfHeight - radius + halfStrokeWidth;
mRectF.bottom = halfHeight + radius - halfStrokeWidth;
mRectF.left = halfWidth - radius + halfStrokeWidth;
mRectF.right = halfWidth + radius - halfStrokeWidth;
canvas.drawArc(mRectF, -90, getRateOfProgress() * 360, falsemPaint);
canvas.save();
}
/**
* Ã¥¾—到当å‰?的进度çš„比率
<p> Ã§”¨Ã¨¿›Ã¥Âº¦Ã¦?¡Ã¥½“Ã¥‰?çš„Ã¥€¼ ä¸Å½ 进度æ?¡Ã§Å¡Ã¦Å“€Ã¥¤§Ã¥€¼Ã¦±‚Ã¥•† </p>
@return
*/
private float getRateOfProgress() {
return (float)mProgress / mDuration;
}
}

Step3:
1.This Text based(Download percentage)circular progressbar widgets library

RateTextCircularProgressBar.java
package com.kalidoss.widgets.progressbar_circular;

import com.kalidoss.widgets.progressbar_circular.CircularProgressBar.OnProgressChangeListener;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.TextView;

/**
*
@author kalidoss rajendran
*/

public class RateTextCircularProgressBar extends FrameLayout implements OnProgressChangeListener {

private CircularProgressBar mCircularProgressBar;
private TextView mRateText;
public RateTextCircularProgressBar(Context context) {
super(context);
init();
}
public RateTextCircularProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

private void init() {
mCircularProgressBar = new CircularProgressBar(getContext());
this.addView(mCircularProgressBar);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lp.gravity = Gravity.CENTER;
mCircularProgressBar.setLayoutParams(lp);
mRateText = new TextView(getContext());
this.addView(mRateText);
mRateText.setLayoutParams(lp);
mRateText.setGravity(Gravity.CENTER);
mRateText.setTextColor(Color.BLACK);
mRateText.setTextSize(20);
mCircularProgressBar.setOnProgressChangeListener(this);
}
/**
* 设置最大值
*/
public void setMax( int max ) {
mCircularProgressBar.setMax(max);
}
/**
* 设置进度
@param progress
*/
public void setProgress(int progress) {
mCircularProgressBar.setProgress(progress);
}
/**
* Ã¥¾—到 CircularProgressBar Ã¥¯¹Ã¨±¡Ã¯¼Å’用æ?¥Ã¨®¾Ã§½®Ã¥…¶Ã¤»–的一些å±Å¾Ã¦€§
@return
*/
public CircularProgressBar getCircularProgressBar() {
return mCircularProgressBar;
}
/**
* 设置中间进度百分比文å­—çš„Ã¥°ÂºÃ¥¯¸
@param size
*/
public void setTextSize(float size) {
mRateText.setTextSize(size);
}
/**
* 设置中间进度百分比文å­—çš„é¢Å“色
@param color
*/
public void setTextColor( int color) {
mRateText.setTextColor(color);
}

@Override
public void onChange(int duration, int progress, float rate) {
mRateText.setText(String.valueOf( (int)(rate * 100 ) + "%"));
}
}

MainActivity.java
package com.kalidoss.widgets.progressbar_circular;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import com.example.progressbar_circular.R;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

/**
*
@author kalidoss rajendran
*
*/

public class MainActivity extends Activity {

private RateTextCircularProgressBar mRateTextCircularProgressBar;

private int progress = 0;
ImageView img;

// download url
private static String file_url = 
"http://m.c.lnkd.licdn.com/mpr/pub/image-lEdqvsZMiUes03zAG0zIeGk_yu7W_3RQc28QoAZJy4b3fONFlEdQjVwMyB_QfPxxkoT5/kalidoss-rajendran.jpg";



protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

img=(ImageView)findViewById(R.id.imageView1);
mRateTextCircularProgressBar = (RateTextCircularProgressBar)findViewById(R.id.rate_progress_bar);
mRateTextCircularProgressBar.setMax(100);
mRateTextCircularProgressBar.clearAnimation();
mRateTextCircularProgressBar.getCircularProgressBar().setCircleWidth(20);
new DownloadFileFromURL().execute(file_url);
}

private Handler mHandler = new Handler() {

@Override
public void handleMessage(Message msg) {
mRateTextCircularProgressBar.setProgress(msg.what);
ifprogress >= 100 )
{
img.setVisibility(View.VISIBLE);
}
mHandler.sendEmptyMessageDelayed(progress++, 100);
super.handleMessage(msg);
}

};
class DownloadFileFromURL extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
}

/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();

// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);

// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

byte data[] = new byte[1024];

long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));

// writing data to file
output.write(data, 0, count);
}

// flushing output
output.flush();

// closing streams
output.close();
input.close();

catch (Exception e) {
Log.e("Error: ", e.getMessage());
}

return null;
}

/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
mHandler.sendEmptyMessageDelayed(Integer.parseInt(progress[0]), 100);
mRateTextCircularProgressBar.setVisibility(View.VISIBLE);

}

/**
* After completing background task
* Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {

// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
// setting downloaded into image view

img.setImageDrawable(Drawable.createFromPath(imagePath));

}

}
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.progressbar_circular"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.kalidoss.widgets.progressbar_circular.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


Happy Coding...
Previous
Next Post »

4 comments

Write comments
Anonymous
AUTHOR
October 23, 2015 at 9:32 AM delete

Thanks for sharing...

Reply
avatar
Anonymous
AUTHOR
March 26, 2016 at 1:42 PM delete

thanks..but how can we download jsonData which is not image just text like other json fields..with this loader?

Reply
avatar