Friday 4 May 2012

Android Custom ListView with Seekbar ,TextView and Button


In this Example you can see how to use Custom Listview with Seekbar ,TextView and Button in android ListView.

Below is code for Activity which have ListView .



public class SeekBarExampleActivity extends ListActivity implements
  OnClickListener, OnTouchListener, OnSeekBarChangeListener {
 /** Called when the activity is first created. */
 ListView mListView;
 public static final int TOTAL_ITEM = 25;

 ImageView mImageView;
 ArrayList mSeekbarValue;

 ImageButton mImageButton;
 ListAdapter mListAdapter;
 TextView mTempTextview;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  mListView = getListView();
  mSeekbarValue = new ArrayList(TOTAL_ITEM);
  for(int i=0;i adapter, View view,
    int position, long lon) {

  }
 };

 @Override
 public boolean onTouch(View v, MotionEvent event) {
  Log.v("Log_tag", "LinearView is Click");
  /*LinearLayout mLinearlayout = (LinearLayout) v;
  if (mLinearlayout.getChildCount() > 0) {
   LinearLayout mtopLinearlayout = (LinearLayout) mLinearlayout
     .getChildAt(0);
   mTempTextview = (TextView) mtopLinearlayout.getChildAt(0);
   Log.v("Log_tag", "Tecview chnage");
  }*/

  return false;
 }

 @Override
 public void onProgressChanged(SeekBar seekBar, int progress,
   boolean fromUser) {
  int position = seekBar.getId();
  LinearLayout mLinearlayout=(LinearLayout) seekBar.getParent();
  if (mLinearlayout.getChildCount() > 0) {
   LinearLayout mtopLinearlayout = (LinearLayout) mLinearlayout
     .getChildAt(0);
   mTempTextview = (TextView) mtopLinearlayout.getChildAt(0);
   Log.v("Log_tag", "Tecview chnage");
  }
  //mSeekbarValue.add(position, progress);
  mSeekbarValue.set(position, progress);
  updateTextview(progress);
 }

 @Override
 public void onStartTrackingTouch(SeekBar seekBar) {

 }

 @Override
 public void onStopTrackingTouch(SeekBar seekBar) {

 }

 public void updateTextview(int paramValue) {
  if (mTempTextview != null) {
   mTempTextview.setText(String.valueOf(paramValue));
  }
 }
}



Here is My Row xml used for Custom ListView:

list_row_view.xml:





    

        

        

    



main.xml





    
    







Friday 20 April 2012

Android Dialog with Custom View

You can create Android Dialog with Below code .


public class DatePickerDialogActivity extends Activity {
 
     @Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
return super.onMenuItemSelected(featureId, item);
}

@Override
public boolean onMenuOpened(int featureId, Menu menu) {
// TODO Auto-generated method stub
return super.onMenuOpened(featureId, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return super.onOptionsItemSelected(item);
}

@Override
public void onOptionsMenuClosed(Menu menu) {
// TODO Auto-generated method stub
super.onOptionsMenuClosed(menu);
}

public static final int DATE_PICKER_DIALOG=1;
public static final int MY_NEW_DIALOG=2;
public Calendar mCalendar;
int mYear;
int mMonth;
int mDay;
String mStringdate="04/04/2012";
String mStrdate1="2012-04-04";
public DatePickerDialog mDatePickerDialog;
public Dialog mDialog;
public Button mButton;
@Override
protected Dialog onCreateDialog(int id) {
switch(id){

case DATE_PICKER_DIALOG:
mDatePickerDialog=new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
view.setOnClickListener(mDateSetListener);
mYear=year + 1;
mMonth=monthOfYear;
mDay=dayOfMonth;
Log.v("Log_tag", "Year is " + mYear +"month is "+ monthOfYear +"Day is "+ dayOfMonth);
}
}, mYear, mMonth, mDay);
mDatePickerDialog.setTitle(R.string.date_set_message);

return mDatePickerDialog;
case MY_NEW_DIALOG:
mSimpleDialog=new Dialog(this,R.style.CustomDialogTheme);
mSimpleDialog.setContentView(R.layout.dialog_layout);
TextView mTextView=(TextView)findViewById(R.id.msgtxt);
Button mBtnYes=(Button)mSimpleDialog.findViewById(R.id.btn_yes);
Button mBtnNo=(Button)mSimpleDialog.findViewById(R.id.btn_no);
mBtnYes.setOnClickListener(DialogButtonClickListener);
mBtnNo.setOnClickListener(DialogButtonClickListener);
mSimpleDialog.setCancelable(true);
mSimpleDialog.show();
return mSimpleDialog;

}
return null;
}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {

super.onPrepareDialog(id, dialog);
}

OnClickListener mDateSetListener =new OnClickListener() {

@Override
public void onClick(View v) {

Log.v("Log_tag", "Set Date is done");
}
};


OnClickListener mButtonClickListener =new OnClickListener() {

@Override
public void onClick(View v) {

if(mDatePickerOn){
showDialog(DATE_PICKER_DIALOG);
}else{
showDialog(MY_NEW_DIALOG);
}

Log.v("Log_tag", "Set Date is done");

}
};



Dialog  mSimpleDialog;
ToggleButton mToggleButton;
boolean mDatePickerOn=false;

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       // requestWindowFeature(Window.)
    super.onCreate(savedInstanceState);
        setContentView(R.layout.my_dialog);
        mCalendar=Calendar.getInstance();
        mYear=mCalendar.get(Calendar.YEAR);
        mMonth=mCalendar.get(Calendar.MONTH);
        mDay=mCalendar.get(Calendar.DAY_OF_MONTH);
        mButton=(Button)findViewById(R.id.btn_show_calander);
        mButton.setOnClickListener(mButtonClickListener);
        mToggleButton=(ToggleButton)findViewById(R.id.toogleButton);
        mToggleButton.setOnCheckedChangeListener(mOnCheckedChangeListener);
      SimpleDateFormat mSimpleDateFormat=new SimpleDateFormat("EEE, MMM d, ''yy");
        SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy");
        try {
        //dateobj1= mSimpleDateFormat.parse(mStrdate1);
        Date dateObj = curFormater.parse(mStringdate);
             SimpleDateFormat postFormater = new SimpleDateFormat("EEE,MMMM dd, yyyy");
        String newDateStr = postFormater.format(dateObj);
        // date2=mSimpleDateFormat.format(dateobj1);
        //dateobj=mSimpleDateFormat.parse(mStringdate);
        //String dateis=mSimpleDateFormat.format(dateobj);
        Log.v("Log_tag", "Here we are with Date Function"+ newDateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
     
    }
 
    OnCheckedChangeListener mOnCheckedChangeListener=new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

if(isChecked){
mDatePickerOn=true;
}else{
mDatePickerOn=false;
}
}
};
 
    View.OnClickListener DialogButtonClickListener=new View.OnClickListener() {

@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_yes:
finish();
break;
case R.id.btn_no:
mSimpleDialog.dismiss();
break;
}

}
};
}



Here is xml Layout for Custom Dialog .
dialog_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/dialog_bg"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="35dp"
        android:text="@string/hello"
        android:id="@+id/msgtxt"/>

    <LinearLayout
        android:id="@+id/btn_linerLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:gravity="center_horizontal"
        android:layout_marginTop="50dp">

        <Button
            android:id="@+id/btn_yes"
            android:layout_width="125dp"
            android:layout_height="40dp"
            android:layout_gravity="center_vertical"
         
            android:text="@string/btn_yes"
            android:layout_marginRight="5dp" />

        <Button
            android:id="@+id/btn_no"
            android:layout_width="125dp"
            android:layout_height="40dp"
            android:layout_gravity="center_vertical"
         
            android:text="@string/btn_no"
            android:layout_marginLeft="5dp"/>
    </LinearLayout>

</LinearLayout>


Another xml layout that used in Example is below
  my_dialog.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn_show_calander"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="mButtonClickListener"
        android:text="@string/btn_text" />

    <ToggleButton
        android:id="@+id/toogleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ToggleButton"
        android:textOn="@string/text_toggle_on"
        android:textOff="@string/text_toggle_off"
        android:gravity="center"/>

</LinearLayout>


Saturday 4 February 2012

Android Vs iPhone : Do iOS Apps Crash More Than Android Apps? A Data Dive.




Ever wonder why certain mobile apps you use crash so much?
It turns out there are many possible reasons. And it can vary particularly depending on whether you are using an Apple iOS device such as an iPhone or iPad, or an Android device.
One of the reasons for app crashes is the proliferation of mobile operating systems on iOS and Android. As Apple and Google have released more new operating systems, each with multiple updates, app developers face more operating systems to test apps on. In data that mobile app monitoring startup Crittercism compiled for app crashes between December 1 and 15, there were at least 23 different iOS operating systems on which apps had crashed and 33 Android operating systems on which apps had crashed. (See the graphs above.) Note that the graphs that separate out Android and iOS show these number of operating systems and the graph that combines both iOS and Android shows less–22 iOS and 17 Android.
The largest proportion of app crashes from both iOS and Android platforms were on iOS 5.01 with 28.64% of overall crashes (in a normalized data set). That makes sense since iOS 5 was still relatively new at that time and many apps still need to work out the kinks with the new OS. But there are also older iOS versions that have a significant proportion of app crashes. For example, iOS 4.2.10 had 12.64% of app crashes, iOS 4.3.3 had 10.66% and iOS 4.1 had 8.24%. One other point that this made clear to me is that many people apparently take their time updating their iPhone software or never update it at all.
The data raises two main questions for me: why do apps on these operating systems crash so much, and do iOS apps crash more than Android apps? On the first question of why apps crash, the reasons are many, says Crittercism CEO Andrew Levy. This can be due to hardware issues, such as the use of location or GPS services or cameras; it could be due to the Internet connection, that is, how a phone connects to 3G or WiFi, or that the device is not connected to the Internet at a certain moment, or that something happens during the switch between 3G and WiFi. There could also be issues with language support on certain devices. There can also be memory problems if an app uses too much memory.
Problems can also occur with third-party services that developers use in their apps, from analytics to advertising systems. For example, there were reports that Apple’s iAds system gave some developers problems if they did not adhere to certain standards. ”It can be a mix of both hardware and software issues that developers may or may not be responding to,” Levy says.
In addition, developers also constantly create new updates to their apps to create new features or fix bugs. But again, people often don’t update their apps–just as they don’t update their operating system. (Android, unlike iOS, allows users to auto-update their apps, which can eliminate some of the problems.) So developers often test all previous versions of their apps with each version of the different operating systems. ”The permutations go on forever,” Levy says. “That’s a large reason for creating our platform.” Particularly with a new OS, developers have to test their app to make sure it still works on the new OS. Often they will seek to test their apps in a test environment, but often that isn’t possible.
The Apple iOS operating system app crashes accounted for more of the app crashes in Crittercism’s data than did Android-based phones, as mentioned above. In the pie graph “Crashes by OS Version Normalized” you can see that iOS accounted for close to three-fourths of the app crashes, with Android making up the rest. But is that just because Crittercism has more iOS phones in its network? Crittercism parsed some data to answer that question.
Crittercism analyzed a total of more than 214 million app launches from November and December 2011 from apps that use its service (see graph at top of this article). There were about 3 times more app launches for iOS that Crittercism analyzed, about 162 million to 52 million. But the analysis examined app crashes as a percentage of each app launch, so this data takes out the issue of there being more iOS than Android apps. In other words for each iOS app and each Android app how often percentage-wise do they crash?
In the top quartile of apps, Android apps crashed 0.15% of the time they launched, while top quartile iOS apps crashed 0.51% of the time. In the second quartile of apps, Android apps crashed 0.73% of the time and iOS apps crashed 1.47% of their launches. In the third quartile of apps, Android apps crashed 2.97% of the time, while iOS apps crashed 3.66% of the time.
So what does all this data mean? On a basic level, you can see that iOS apps crashed more than Android apps during this time period. But Crittercism’s Levy cautions that this doesn’t necessarily mean that overall iOS apps crash more than Android apps. That’s because Apple had recently released a new version iOS 5 in October. Android’s new Ice Cream Sandwich operating system (Android 4.0), meanwhile, had not been widely released on phones yet at the time of this study. “I expect as Ice Cream Sandwich just launched and the new Nexus S phone launched (during the study), we’ll expect the same situation to occur (with Android) as what happened (with iOS),” Levy says.
Still, the data shows that apps on iOS did crash substantially more than Android apps. Anecdotally, I know that certain apps I use on my iPhone crash and they crash often. Will that change as Ice Cream Sandwich rolls out and as more developers improve on iOS 5? We’ll see.
One other thing about the data: in the best apps, that is, the top quartile, the apps crashed much less than in the third quartile. Levy emphasized that that shows the difference that developers can make with their apps by analyzing the data and improving their apps. Splitting up the data by quartiles also removes apps with massive user bases that can skew the averages.
My own point: when you get to the top apps, Android’s lower app crash rate than iOS makes less of a difference because they are both well below 1%. However, there was a bigger difference between iOS and Android app crashes in the top quartile of apps than in the third quartile. In other words, the best apps in Android crashed about one third as many times as the best iOS apps, while the second best quartile Android apps crashed about half as much as comparable iOS apps, and in the quartile, the difference between the two operatings systems was even less. So the very top Android apps are achieving a crash rate that, at least in this time period, the best iOS apps can’t match. Why that is, I’m not entirely clear.
However, Android, it should be noted, allows developers to push updates faster than Apple. With Android developers can just send an update to its code, which can show up almost in real-time. But for iOS it can takes days or a week for an update to show up. That means there can be more app crashes while those updates are waiting to happen. Whereas with Android, presumably if developers know there’s a bug they can immediately fix it.
One final piece of interesting data from Crittercism: The performance of apps is not only different on various operating systems but also on different devices. About 74.41% of the iOS crashes Crittercism tracked were on the iPhone, 14.81% were on the iPod Touch, and 10.72% were on the iPad.
Crittercism, which is backed by Google Ventures, Kleiner Perkins Caufield & Byers, AngelPad, AOL Ventures, Opus Capital and Shasta Ventures, provides crash reporting to app developers. The company provides developers with a wide range of data besides the mobile device and operating system, including, for example, the length of time between when an app is loaded and when it crashes, or how a user is holding a phone–portrait or landscape–when it crashes. It can also help evaluate whether an app’s own code has caused it to crash or whether a third party service SDK being used is causing the problem. This kind of data is important for helping developers plug all the holes in the landscape of operating systems. Clients using Crittercism include: Aston Martin ExploreBullet Time and Hipster.
Protecting apps from crashes is not only important for app developers, who by definition live and die by the ability of their apps to work smoothly. Increasingly, many types of companies rely on apps to run their businesses, even if there isn’t a large consumer user base using the apps. Banks have mobile apps that enable check deposits, sales people use apps in the field, and so on. “It’s about protecting your brand,” says Crittercism cofounder Rob Kwok. “More and more business-critical functions are  moving to apps.”
Crittercism is signing up a number of large customers to its platform as a result. The company has already ramped way up from the 214 million app launches that it monitored in this data from November and December. If you’re hoping to end those annoying crashes on your phone or tablet, that should be welcome news.

Wednesday 1 February 2012

Android Graphics : Some Fact About Android Graphics

Here Some Interesting Things About Android Graphics By Post of Dianne Hackborn.


• Android has always used some hardware accelerated drawing. Since before 1.0 all window compositing to the display has been done with hardware.

• This means that many of the animations you see have always been hardware accelerated: menus being shown, sliding the notification shade, transitions between activities, pop-ups and dialogs showing and hiding, etc.

• Android did historically use software to render the contents of each window. For example in a UI like http://www.simplemobilereview.com/wp-content/uploads/2010/12/2-home-menu.png there are four windows: the status bar, the wallpaper, the launcher on top of the wallpaper, and the menu. If one of the windows updates its contents, such as highlighting a menu item, then (prior to 3.0) software is used to draw the new contents of that window; however none of the other windows are redrawn at all, and the re-composition of the windows is done in hardware. Likewise, any movement of the windows such as the menu going up and down is all hardware rendering.

• Looking at drawing inside of a window, you don’t necessarily need to do this in hardware to achieve full 60fps rendering. This depends very much on the number of pixels in your display and the speed of your CPU. For example, Nexus S has no trouble doing 60fps rendering of all the normal stuff you see in the Android UI like scrolling lists on its 800x480 screen. The original Droid however struggled with a similar screen resolution.

• "Full" hardware accelerated drawing within a window was added in Android 3.0. The implementation in Android 4.0 is not any more full than in 3.0. Starting with 3.0, if you set the flag in your app saying that hardware accelerated drawing is allowed, then all drawing to the application’s windows will be done with the GPU. The main change in this regard in Android 4.0 is that now apps that are explicitly targeting 4.0 or higher will have acceleration enabled by default rather than having to put android:handwareAccelerated="true" in their manifest. (And the reason this isn’t just turned on for all existing applications is that some types of drawing operations can’t be supported well in hardware and it also impacts the behavior when an application asks to have a part of its UI updated. Forcing hardware accelerated drawing upon existing apps will break a significant number of them, from subtly to significantly.)

• Hardware accelerated drawing is not all full of win. For example on the PVR drivers of devices like the Nexus S and Galaxy Nexus, simply starting to use OpenGL in a process eats about 8MB of RAM. Given that our process overhead is about 2MB, this is pretty huge. That RAM takes away from other things, such as the number of background processes that can be kept running, potentially slowing down things like app switching.

• Because of the overhead of OpenGL, one may very well not want to use it for drawing. For example some of the work we are doing to make Android 4.0 run well on the Nexus S has involved turning off hardware accelerated drawing in parts of the UI so we don’t lose 8MB of RAM in the system process, another 8MB in the phone process, another 8MB in the system UI process, etc. Trust me, you won’t notice -- there is just no benefit on that device in using OpenGL to draw something like the status bar, even with fancy animations going on in there.

• Hardware accelerated drawing is not a magical silver bullet to butter-smooth UI. There are many different efforts that have been going on towards this, such as improved scheduling of foreground vs. background threads in 1.6, rewriting the input system in 2.3, strict mode, concurrent garbage collection, loaders, etc. If you want to achieve 60fps, you have 20 milliseconds to handle each frame. This is not a lot of time. Just touching the flash storage system in the thread that is running the UI can in some cases introduce a delay that puts you out of that timing window, especially if you are writing to storage.

• A recent example of the kinds of interesting things that impact UI smoothness: we noticed that ICS on Nexus S was actually less smooth when scrolling through lists than it was on Gingerbread. It turned out that the reason for this was due to subtle changes in timing, so that sometimes in ICS as the app was retrieving touch events and drawing the screen, it would go to get the next event slightly before it was ready, causing it to visibly miss a frame while tracking the finger even though it was drawing the screen at a solid 60fps. (Edit: for those who need this made clear, yes of course this particular issue is fixed.)

• When people have historically compared web browser scrolling between Android and iOS, most of the differences they are seeing are not due to hardware accelerated drawing. Originally Android went a different route for its web page rendering and made different compromises: the web page is turned in to a display list, which is continually rendered to the screen, instead of using tiles. This has the benefit that scrolling and zooming never have artifacts of tiles that haven’t yet been drawn. Its downside is that as the graphics on the web page get more complicated to draw the frame rate goes down. As of Android 3.0, the browser now uses tiles, so it can maintain a consistent frame rate as you scroll or zoom, with the negative of having artifacts when newly needed tiles can’t be rendered quickly enough. The tiles themselves are rendered in software, which I believe is the case for iOS as well. (And this tile-based approach could be used prior to 3.0 without hardware accelerated drawing; as mentioned previously, the Nexus S CPU can easily draw the tiles to the window at 60fps.)

• Hardware accleration does not magically make drawing performance problems disappear. There is still a limit to how much the GPU can do. A recent interesting example of this is tablets built with Tegra 2 -- that GPU can touch every pixel of a 1280x800 screen about 2.5 times at 60fps. Now consider the Android 3.0 tablet home screen where you are switching to the all apps list: you need to draw the background (1x all pixels), then the layer of shortcuts and widgets (let’s be nice and say this is .5x all pixels), then the black background of all apps (1x all pixels), and the icons and labels of all apps (.5x all pixels). We’ve already blown our per-pixel budget, and we haven’t even composited the separate windows to the final display yet. To get 60fps animation, Android 3.0 and later use a number of tricks. A big one is that it tries to put all windows into overlays instead of having to copy them to the framebuffer with the GPU. In the case here even with that we are still over-budget, but we have another trick: because the wallpaper on Android is in a separate window, we can make this window larger than the screen to hold the entire bitmap. Now, as you scroll, the movement of the background doesn’t require any drawing, just moving its window... and because this window is in an overlay, it doesn’t even need to be composited to the screen with the GPU.

• As device screen resolution goes up, achieving a 60fps UI is closely related to GPU speed and especially the GPU’s memory bus bandwidth. In fact, if you want to get an idea of the performance of a piece of hardware, always pay close attention to the memory bus bandwidth. There are plenty of times where the CPU (especially with those wonderful NEON instructions) can go a lot faster than the memory bus.

EDIT:

Wow this has generated a lot more discussion, and I won't be able to address nearly everything that has been raised. But I'll try to expand on things a bit here to better address what I think are some of the more interesting points.

Some have raised points along the lines of Samsung Galaxy S2 phones already having a smoother UI and indicating that they are doing something different vs. the Galaxy Nexus. When comparing individual devices though you really need to look at all of the factors. For example, the S2's screen is 480x800 vs. the Galaxy Nexus at 720x1280. If the Nexus S could already do 60fps for simple UIs on its 480x800, the CPU in the S2's is even better off.

The real important difference between these two screens is just that the Galaxy Nexus has 2.4x as many pixels that need to be drawn as the S2. This means that to achieve the same efficiency at drawing the screen, you need a CPU that can run a single core at 2.4x the speed (and rendering a UI for a single app is essentially not parallelizable, so multiple cores isn't going to save you).

This is where hardware accelerated rendering really becomes important: as the number of pixels goes up, GPUs can generally scale much better to handle them, since they are more specialized at their task. In fact this was the primary incentive for implementing hardware accelerated drawing in Android -- at 720x1280 we are well beyond the point where current ARM CPUs can provide 60fps. (And this is a reason to be careful about making comparisons between the Galaxy Nexus and other devices like the S2 -- if you are running third party apps, there is a good chance today that the app is not enabling hardware acceleration, so your comparison is doing CPU rendering on the Galaxy Nexus which means you almost certainly aren't going to get 60fps out of it, because it needs to hit 2.4x as many pixels as the S2 does.)

To be complete, there is another big advantage that the GPU gives you -- many more drawing effects become feasible. For example, if you are drawing a bitmap in software, you basically can't do anything to it except apply an offset. Just trying to scale it is going to make rendering significantly slower. On a GPU, applying transformations well beyond simple scales is basically free. This is why in the new default Holo themes in Android we have background images -- with hardware accelerated drawing, we can afford to draw (and scale) them. In fact, if the hardware path is not enabled by the app, these background images will be turned off.

Saturday 28 January 2012

Download Image From Url or link in Android With ProgressDialog to Show Image is Loading..

Hello,Every One I have Now Write here simple Demo for Loading Image From Url with Help of
AsyncTask in Android,By this Way We Can see that how much data of image has been loading and so we can show progress of Loading Image To ProgressDialog in Android.

Below is Main Activity luncher Class Which is :
LoadBitmapActivity.java

Here is Java Code for It.
___________________________________Start____________________________________________


public class LoadBitmapActivity extends Activity {
/** Called when the activity is first created. */
public boolean isConnected = false;
public static final String IMAGE_URL = "http://media1.santabanta.com/full4/bollywood%20movies/agneepath/agneepath-8a.jpg";
ProgressDialog mProgressDialog;
TextView mTextView;
ImageView mImageView;
Button mButton;
private ByteArrayOutputStream byte_output_stream;
private double filesize;
private double downloaded;
public static final int DOWNLOADING = 0;
private int status = DOWNLOADING;
public static final int COMPLETE = 1;
private Bitmap mBitmap;
HttpURLConnection connection;
InputStream is;
public int MAX_BUFFER_SIZE = 1024;
public static int SIZE = 100;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.text_data);
mImageView = (ImageView) findViewById(R.id.loaded_image);
mButton = (Button) findViewById(R.id.btn_start);
mButton.setOnClickListener(mButtonClickListener);

}

View.OnClickListener mButtonClickListener = new View.OnClickListener() {

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start:
if (checkInternet()) {
new DownloadImagetask().execute(IMAGE_URL);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
LoadBitmapActivity.this);
builder.setTitle(R.string.alert_internet_msg_title);

builder.setPositiveButton(R.string.alert_btn_text,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
}
break;

default:
break;
}
}
};

public boolean checkInternet() {
ConnectivityManager mConnectivityManager = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkinfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkinfo != null && mNetworkinfo.isAvailable()
&& mNetworkinfo.isConnected()) {
return isConnected = true;
} else {
return isConnected = false;
}
}

private class DownloadImagetask extends AsyncTask<String, Integer, Bitmap> {

@Override
protected void onPostExecute(Bitmap result) {
mProgressDialog.dismiss();
mImageView.setImageBitmap(result);

super.onPostExecute(result);
}

public DownloadImagetask() {
mBitmap = null;
downloaded = 0;
filesize = 0;
status = DOWNLOADING;
}

@Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(LoadBitmapActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// mProgressDialog.setProgress(0);
mProgressDialog.setMessage(getString(R.string.progress_msg_title));
// mProgressDialog.setMax(10);
mProgressDialog.show();
super.onPreExecute();
}

@Override
protected void onProgressUpdate(Integer... values) {
mProgressDialog.setProgress(values[0]);
super.onProgressUpdate(values);
}

@Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
filesize = connection.getContentLength();
byte_output_stream = new ByteArrayOutputStream((int) filesize);
connection.setDoOutput(true);
connection.connect();
is = connection.getInputStream();

if (filesize < SIZE) {
MAX_BUFFER_SIZE = 1024;
} else {
MAX_BUFFER_SIZE = (int) Math.ceil(filesize / SIZE);
}
// loop with step 1Kb
while (status == DOWNLOADING) {
byte[] imagedata_buffer;
if (filesize - downloaded > MAX_BUFFER_SIZE) {
imagedata_buffer = new byte[MAX_BUFFER_SIZE];
} else {
imagedata_buffer = new byte[(int) (filesize - downloaded)];
}
int read = is.read(imagedata_buffer);
if (read == -1) {
publishProgress(100);
break;
}
byte_output_stream.write(imagedata_buffer, 0, read);
downloaded += read;

publishProgress((int) ((downloaded / filesize) * 100));
}

if (status == DOWNLOADING) {
status = COMPLETE;
}
return BitmapFactory
.decodeStream((InputStream) new ByteArrayInputStream(
byte_output_stream.toByteArray()));

} catch (MalformedURLException excep) {
excep.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}

}

return null;
}

}
}
-----------------------------------------------End of Class------------------------------------------------
Here is Xml that i have used for Activity.

main.xml



<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center_vertical" >

    <TextView
        android:id="@+id/text_data"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <ImageView
        android:id="@+id/loaded_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="15dip"
        android:src="@drawable/ic_launcher" />

    <Button
        android:id="@+id/btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:gravity="center"
        android:text="@string/btn_start" />

</FrameLayout>

For Work with image to load from Internet you need to give two permission in your's android project Manifest .And Here are two permission.

This Permission Give us to access internet from our android application.

<uses-permission android:name="android.permission.INTERNET"/>
And Now Second one i have used for To get State of our Android Mobile it is connected to internet or not,and this permission also need to get any changes in network state .
   <uses-permission  android:name="android.permission.ACCESS_NETWORK_STATE"/>