Save Activity state in Android

There are many situation where you will need to save the state of current activity and then retrieving it back. Mostly this will be required when user will change the screen orientation mode and the app need to support both the mode like Portrait and Landscape.

So use the below code and save all the values in it,


@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
}

And following is the code for retrieving back the values,


@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}

CAREFUL: you need to call super.onSaveInstanceState(savedInstanceState) before adding your values to the Bundle, or they will get wiped out on that call (Droid X Android 2.2).

Moreover, onSaveInstanceState is only for transient state. You should save permanent changes in the onPause method

Posted in android storage | Tagged , , , , , , , , , | Leave a comment

How do I do a lazy load of images in ListView?

Most of the apps uses a ListView and in most of the ListViews the requirement is to show thumbnail size of images. ListView size may be more than 40,60,100 or even 200.

So, to download all images in background requires the good management of multiple thread and also take care of smooth sliding as well. So, basically all the threads will perform operation with bitmaps.

But be aware of bitmaps…..!

Generally we should avoid handling bitmaps. Because to make process on it takes considerably a long memory chunks and results in memoryOutOfException and VM size exceeds

It depends on the device’s internal memory and mostly android phone gives for this 16MB of size. So, when bitmap processes cross this limit, then app will crash.

But there are many libraries are available for this like,

https://github.com/thest1/LazyList

https://github.com/nostra13/Android-Universal-Image-Loader

http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html

But above all links are old and have many issues in using them app. So they are not the most optimal codes.

Till now, I found the following is the best example for handling bitmaps and playing with it securely from developer.android.com

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

I love to get replays.

Thanks.

Posted in android bitmap | Tagged , , , , , , , , , , | Leave a comment

Fix: android.os.NetworkOnMainThreadException

Many new android development learns might have come acrossed following network related error, android.os.NetworkOnMainThreadException

For this, you need to understand the thread system. Generally, the android system performs whatever tasks like ui, activity stacking, user interaction, etc all this things are done using a thread and its called as the Main thread.

So, if you perform any task like reading bigger size of file or fetching data over in network, it will take some considerable time. And such tasks hang up the Main thread( or UI thread) and so the device. If that time increases more than few seconds, then it results in crash and gives above error.

So, the solution is to make a background process and put all that code in it which is supposed to take considerably long time.

You can use AsyncTask for this. Here is the link about it to get more detail and following is the example code,


class RetrieveFeedTask extends AsyncTask {

private Exception exception;

protected RSSFeed doInBackground(String... urls) {

// TODO: Add code here which will take longer time
try {
URL url= new URL(urls[0]);
SAXParserFactory factory =SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
XMLReader xmlreader=parser.getXMLReader();
RssHandler theRSSHandler=new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is=new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();
} catch (Exception e) {
this.exception = e;
return null;
}
}

protected void onPostExecute(RSSFeed feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
}

Above example is of calling a webservice and retrieving a data using SAXParser. Same Way, you can apply the template for other tasks as well.

new RetrieveFeedTask().execute(urlToRssFeed);

Above is the code to start the background process.

Another solution to create a background process is through Runnable class as,


Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
//Your code goes here
} catch (Exception e) {
e.printStackTrace();
}
}
});

thread.start();

I would like to get more comments.

Thanks

Posted in Android Crash Thread, Uncategorized | Tagged , , , , , , , , , | Leave a comment

Open another application from your own app using explicit Intent

An android application can have multiple activities, services, content providers and/or broadcast listeners. If at least one of them is running, the application is up and running.

But, it is required to know the package name and Activity name of other app that you want to start. Anyway, below is the code where it can open app without knowing class name,


PackageManager pm = context.getPackageManager();
Intent appStartIntent = pm.getLaunchIntentForPackage(appPackageName);
if (null != appStartIntent)
{
startActivity(appStartIntent);
}

In case, if you know the class name then,


Intent intent = new Intent("android.intent.action.MAIN"); intent.setComponent(ComponentName.unflattenFromString("com.google.android.maps.mytracks/com.google.android.apps.mytracks.MyTracks"));
intent.addCategory("android.intent.category.LAUNCHER");
startActivity(intent);

Posted in Android Intent | Tagged , , , , , , , , | Leave a comment

Android intent not starting new activity?

Following is the code of starting new Activity. Suppose, current activity is A, and you want to open Activity B then use following snippet,

Intent i = new Intent(A.this, B.class);  
startActivity(i);

If you have any query, kindly give comment, I’ll give answer of it. Thanks.

Posted in Uncategorized | Tagged , , , , , , | Leave a comment

Android phones is better than the iPhone

We all know the iPhone, know how it works (or doesn’t work, in many instances). We know there is an app for just about every possible task on the planet. But an Android phone? You don’t really know an Android phone until you’ve worked with one. That’s when you’ll find how far you can push your mobile experience.

1: Browsing

Let me first say I do like the Safari browser on the iPhone. It’s fast, it’s reliable, it’s stable. But flexible? Flash? Monopolistic? Yes Safari is the only browser for the iPhone, and that browser still does not do Flash. However, the Android browser is one of the best browsers on the mobile market. On my HTC Hero, I have Opera Mini, Dolphin, and the default Browser. I haven’t used Opera Mini since I used it a couple of times upon installation. Dolphin is outstanding, with its use of Tabs and Gestures. But the default Android browser just can’t be beat. It usually loads pages faster than Safari, has Flash support, and simply does everything a browser should do.
2: Desktop

Instead of just having icons littering your phone’s desktop (like the iPhone), the Android phone adds widgets to the desktop. These widgets tend to have an actual purpose. For example:
The Twitter Widget allows you to update your Twitter status from your mobile desktop.
The People Widget allows you to enable different actions for different contacts right from your desktop (say you want to call your wife with a single click and text your child from a single click).
The Messages Widget allows you to instantly see your email from the desktop.
The Android desktop is on a completely different level from the iPhone desktop. To compare them is actually unfair. Apples to Éclairs as it were.

3: Connectivity

On one of the “pages” of my Hero desktop, I have four buttons:
Turn on/off bluetooth
Turn on/off Wifi
Turn on/off Mobile Network
Turn on/off GPS
These buttons let you instantly switch on or off the various connectivity options, which will go a long way toward conserving battery life. There is also an app in the Market called Y5, which will turn off Wi-Fi automatically when no known wireless network is available. To do any of this on the iPhone, you have to go into the Settings screen and navigate your way around the various options.

4: PC connection

Unlike the iPhone, you don’t need to have iTunes to manage your phone. Now, I say this with a bit of a chewed-up tongue because Android can’t sync with the Linux desktop yet. That’s okay for now. But Android can mount the SD card so that it is usable (via drag and drop) by any operating system. On this you can add music and files, which will then be usable on the phone. Simple.
5: Multi-notification

One of the issues I’ve always had with the iPhone is its notification system. Basically, it depends upon a single system that not all applications have access too. For instance, if you are a Twitterer, you can find out if you have updates only by opening the Twitter app on the iPhone. With Android, the apps have access to the notification system and can all report. The notification bar on the Android phone can alert you to new voice messages, email messages, Facebook notifications, new Gmail, new text messages, and much more. If an app has a notification, it can let you know quickly, and in the background.
6: Endless personalization

I hesitate to place this on the list because so many readers seem to think user-configuration is worthless. It’s not. The Android phone allows users to configure their mobile to look and behave exactly how they want it. If you’re a social network power user, you can have a screen for Facebook, one for Twitter, one for texting, and one for Flickr. Or if you are a business user, you can have a screen for contacts, for your calendar, for gmail, for email, for RSS, and more. Not only can you configure the desktop the way you want, you can configure the behavior of your phone. Set up default actions for different contacts — even add an entirely different desktop, should you want. The possibilities are endless with the Android phone. With the iPhone, you’re pretty much limited to what Apple says.
7: Market

Yes, Apple has an app for that. But so does Android. And chances are, the Android app is free and works as well (or better) than the iPhone app. And, believe it or not, there are thousands of apps in the Android Market. Apple does not (at least yet) have a patent on an application for just about everything. Give it time though. And installing applications on your Android phone is actually easier than it is on the iPhone. For free applications, you don’t have to worry about entering a password every time you try to install anything. And you do not have to link to Apple’s iTunes store to purchase applications from the Android Market. For those apps that have a price, you enter your information on the Google Market one time and you’re done.
8: Google integration

This one is almost not fair, since Android was built with the intention of integrating with Google. But wow does it integrate well. Want to search Google? Simply click the search button, enter your search string, and you’re off and running. Did I mention Google Voice? Yes, the Android has an app for that.
9: Open Source

Why does being open make Android better than iPhone? For the same reason that being open helps Linux: a planet full of developers with the ability to aid Android’s developers. Anyone can get access to the source of Android to better the system. This is also a double-edged sword, in that it allows those will less-than-ideal intentions to discover any weakness of the phone. But that can be seen as an indirect plus because when weaknesses are found in the open source community, they are quickly fixed. I assume that this tradition will extend to the Android phone. iPhone open? You’re kidding right?
10: Open to carriers

This is yet another reason why Android is superior. If you want an iPhone (at least for the time being), you better be open to AT&T. If you don’t like AT&T and you still want an iPhone, you better be open to doing a little jail breaking or move to another country. If you want an Android phone, you can join any number of carriers and have your choice of any number of outstanding phones using Android. No lock down.

Posted in Android Market | Tagged , , , , , , , , , , , , , , , , , , | Leave a comment

Connect Android device to MySQL

To make the connection between android device & MySQL, developer should have silent knowledge of class JSONObject because this class plays major role for making connection fruitful. Here is a detail about this class.

Here is the whole code. You can download php file and java file.

JSONObject

A modifiable set of name/value mappings. Names are unique, non-null strings. Values may be any mix of JSONObjects, JSONArrays, Strings, Booleans, Integers, Longs, Doubles orNULL. Values may not be null, NaNs, infinities, or of any type not listed here.

This class can coerce values to another type when requested.

  • When the requested type is a boolean, strings will be coerced using valueOf(String).
  • When the requested type is a double, other Number types will be coerced using doubleValue. Strings that can be coerced using valueOf(String) will be.
  • When the requested type is an int, other Number types will be coerced using intValue. Strings that can be coerced using valueOf(String) will be, and then cast to int.
  • When the requested type is a long, other Number types will be coerced using longValue. Strings that can be coerced using valueOf(String) will be, and then cast to long. This two-step conversion is lossy for very large values. For example, the string “9223372036854775806” yields the long 9223372036854775807.
  • When the requested type is a String, other non-null values will be coerced using valueOf(Object). Although null cannot be coerced, the sentinel value NULL is coerced to the string “null”.

For many people, the main reson for learning a scripting language like PHP is because of the interaction with databases it can offer. In this tutorial I will show you how to use PHP and the MySQL database to store information on the web and include it into your website. Before you read this tutorial you should have at least a basic knowledge of how to use PHP.

Now, coming to our tutorial, there should a table like Student(s_id,s_name) where s_id is primary key of table Student. Target is that we want to insert data from android to mysql. For making this we will use PHP in middle as shown below.

Android —> PHP—-> MySQL database(table: Student)

In php we will fetch data from android through following method,

‘”.$_REQUEST[‘keyword’].”‘

Here is a whole .java file code for android to insert data to database.

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("s_name","Jack"));
try{     HttpClient httpclient = new DefaultHttpClient();
	//please note here that change url according to your application
	//if you are currently using android emulator, then you must use
 	//http://10.0.2.2/stu.php for connecting localhost of your pc.
     HttpPost httppost = new HttpPost("http://www.xyz.com/stu.php");
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     HttpResponse response = httpclient.execute(httppost);
     HttpEntity entity = response.getEntity();
     is = entity.getContent();
     }catch(Exception e){
         Log.e("log_tag", "Error in http connection"+e.toString());
    }
//convert response to stringtry
{
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
       sb = new StringBuilder();
       sb.append(reader.readLine() + "\n");
       String line="0";
       while ((line = reader.readLine()) != null) {
                      sb.append(line + "\n");        }
        is.close();
        String result=sb.toString();
        }catch(Exception e){
              Log.e("log_tag", "Error converting result "+e.toString());
        }//paring datatry
{
      jArray = new JSONArray(result);
      deal_id=new int[jArray.length()+1];
      JSONObject json_data=null;
      for(int i=0;i<jArray.length();i++){
             json_data = jArray.getJSONObject(i);
                      }
      }      catch(JSONException e1){
    	       } catch (ParseException e1) {
			e1.printStackTrace();	}
    }

 

PHP script to insert data into MySQL table Student

<?phpmysql_connect("host","username","password");
mysql_select_db("db_name");
$sql=mysql_query("insert into Student (s_name)values('".$_REQUEST['s_name']."')");
$r=mysql_query($sql);
if(!$r)echo "Error in query: ".mysql_error();mysql_close();?>

Freelance Jobs

Posted in Android PHP | Tagged , , , , , , , , , , , , , , , , | 6 Comments

Hello world!

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

Posted in Uncategorized | Leave a comment