Monday, 7 October 2013

Import and export Excel .CSV File into SQLite Android

Import and export Excel .CSV File into SQLite Android 


Hi Guys today we will see very Important tutorial for Import and export Excel / CSV file into android SQLite database and SQLite to Excel / CSV.

This is very simple task,  here  we make simple self explanatory project example.
 DOWNLOAD
 DOWNLOAD

Friday, 4 October 2013

Class Exercise : SQLite, Shared Preferences, Services, Broadcast Reciever

Class Exercise : SQLite, Shared Preferences, Services, Broadcast Receiver 


Hi guys, Sorry for late Uploading Examples 
Here you can download all Five example of Class on 28th Sep 2013

1) Broadcast Receiver 

2) Services Example

3) Shared Preferences Example 

4) SQLite Example 

5) Layout Example



Friday, 20 September 2013

Android Activity and ImageView Animation

Android Activity and ImageView Animation 

Hi Guys, Here is sample example for animation in android. It covers almost all types of possible animations.
The Animation Demo code was borrowed from code I found different sources  on internet. I can’t find reference to it anymore so if anyone happens to find anything similar please provide reference in the comments and I’ll link it up.






Download 
Happy Coddddding :)



Tuesday, 17 September 2013

Handle "unfortunately, App has Stopped" Or "force close " situations in android


Handle "unfortunately, App has Stopped" Or  "force close " situations in android.


Many time we forget to catch exception or some time unexpected exception occur. So we should handle in some way that our app should not show "Force Close Dialog" in such condition. 
So here is simple example. For this situations
Create Simple Class As MyExceptionHandler.

package com.example.crashhandledex;

import java.io.PrintWriter;
import java.io.StringWriter;

import android.content.Context;
import android.content.Intent;

public class MyExceptionHandler implements
              java.lang.Thread.UncaughtExceptionHandler {
       private final Context myContext;
       private final Class<?> myActivityClass;

       public MyExceptionHandler(Context context, Class<?> c) {

              myContext = context;
              myActivityClass = c;
       }

       public void uncaughtException(Thread thread, Throwable exception) {

              StringWriter stackTrace = new StringWriter();
              exception.printStackTrace(new PrintWriter(stackTrace));
              System.err.println(stackTrace);// You can use LogCat too
              Intent intent = new Intent(myContext, myActivityClass);
              String s = stackTrace.toString();
              // you can use this String to know what caused the exception and in
              // which Activity
              intent.putExtra("uncaughtException",
                           "Exception is: " + stackTrace.toString());
              intent.putExtra("stacktrace", s);
              myContext.startActivity(intent);
              // for restarting the Activity
              // Process.killProcess();
              System.exit(0);
       }
}


AND IN YOUR ACTIVITY  USED AS 


public class MainActivity extends Activity {

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,
                           MainActivity.class));

              final Button button1 = (Button) findViewById(R.id.button1);
              button1.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {
                           //Example Crash, Here App will restart instead of showing force close dialog
                           int i = Integer.valueOf("SJDkal");
                           button1.setText(i);

                     }
              });

       }
}



Happy Codddddin :)

Best Practices for Exception Handling and Logging

Best Practices for Exception Handling and Logging

The Nature of Exceptions


Broadly speaking, there are three different situations that cause exceptions to be thrown:
Exceptions due to programming errors: In this category, exceptions are generated due to programming errors (e.g., NullPointerException and IllegalArgumentException). The client code usually cannot do anything about programming errors.
Exceptions due to client code errors: Client code attempts something not allowed by the API, and thereby violates its contract. The client can take some alternative course of action, if there is useful information provided in the exception. For example: an exception is thrown while parsing an XML document that is not well-formed. The exception contains useful information about the location in the XML document that causes the problem. The client can use this information to take recovery steps.
Exceptions due to resource failures: Exceptions that get generated when resources fail. For example: the system runs out of memory or a network connection fails. The client's response to resource failures is context-driven. The client can retry the operation after some time or just log the resource failure and bring the application to a halt.

Best Practices for Exception Handling
1. When deciding on checked exceptions vs. unchecked exceptions, ask yourself, "What action can the client code take when the exception occurs?"
If the client can take some alternate action to recover from the exception, make it a checked exception. If the client cannot do anything useful, then make the exception unchecked. By useful, I mean taking steps to recover from the exception and not just logging the exception.
Moreover, prefer unchecked exceptions for all programming errors: unchecked exceptions have the benefit of not forcing the client API to explicitly deal with them. They propagate to where you want to catch them, or they go all the way out and get reported. The Java API has many unchecked exceptions, such as NullPointerException, IllegalArgumentException, and IllegalStateException. I prefer working with standard exceptions provided in Java rather than creating my own. They make my code easy to understand and avoid increasing the memory footprint of code.
2. Preserve encapsulation.
Never let implementation-specific checked exceptions escalate to the higher layers. For example, do not propagate SQLException from data access code to the business objects layer. Business objects layer do not need to know about SQLException. You have two options:
1) Convert SQLException into another checked exception, if the client code is expected to recuperate from the exception.
2) Convert SQLException into an unchecked exception, if the client code cannot do anything about it.
3. Try not to create new custom exceptions if they do not have useful information for client code.
4. Do not use your base exception class for "unkown" exception cases.
actually a follow-up from the first advice above. If you model your own exception hierarchy, you will typically have an exception base class (eg. MyAPIException) and several specific ones that inherit from that one (eg. MyAPIPathNotFoundException). Now it is tempting to throw the base exception class whenever you don't really know what else to throw, because the error case is not clear or very seldom. It's probably a Fault and thus you would start mixing it with your Contingency exception class hierarchy, which is obviously a bad thing.
One of the advantages of an exception base class is that the client has the choice to catch the base class if he does not want to handle the specific cases (although that's probably not the most robust code). But if that exception is also thrown in faulty situations, the client can no longer make a distinction between one-of-those-contingency-cases and all-those-unexcpected-fault-cases. And it obviously brakes your explicit exception design: there are those specific error cases you state and let the client know about, but then there is this generic exception thrown where the client cannot know what it means and is not able to handle it as a consequence.
5. When wrapping or logging exceptions, add your specific data to the message. 
6. Don't throw exceptions in methods that are likely to be used for the exception handling itself.
This follows straight from the two previous advices: if you throw or log exceptions, you are typically in exception handling code, because you wrap a lower-level exception. If you add dynamic data to your exceptions, you might access methods from the underlying API. But if those methods throw exceptions, your code becomes ugly.
7. Document exceptions.

Best Practices for Using Exceptions
1. Always clean up after yourself
If you are using resources like database connections or network connections, make sure you clean them up. If the API you are invoking uses only unchecked exceptions, you should still clean up resources after use, with try - finally blocks.
2. Never use exceptions for flow control
Generating stack traces is expensive and the value of a stack trace is in debugging. In a flow-control situation, the stack trace would be ignored, since the client just wants to know how to proceed.
3. Do not suppress or ignore exceptions
When a method from an API throws a checked exception, it is trying to tell you that you should take some counter action. If the checked exception does not make sense to you, do not hesitate to convert it into an unchecked exception and throw it again, but do not ignore it by catching it with {} and then continue as if nothing had happened.
4. Do not catch top-level exceptions
5. Log exceptions just once
Logging the same exception stack trace more than once can confuse the programmer examining the stack trace about the original source of exception. So just log it once.

Logging
When your code encounters an exception, it must either handle it, let it bubble up, wrap it, or log it. If your code can programmatically handle an exception (e.g., retry in the case of a network failure), then it should. If it can't, it should generally either let it bubble up (for unchecked exceptions) or wrap it (for checked exceptions). However, it is ultimately going to be someone's responsibility to log the fact that this exception occurred if nobody in the calling stack was able to handle it programmatically. This code should typically live as high in the execution stack as it can. Some examples are the onMessage() method of an MDB, and the main() method of a class. Once you catch the exception, you should log it appropriately.
The JDK has a java.util.logging package built in, although the Log4j project from Apache continues to be a commonly-used alternative. Apache also offers the Commons Logging project, which acts as a thin layer that allows you to swap out different logging implementations underneath in a pluggable fashion. All of these logging frameworks that I've mentioned have basically equivalent levels:
1) FATAL: Should be used in extreme cases, where immediate attention is needed. This level can be useful to trigger a support engineer's pager.
2) ERROR: Indicates a bug, or a general error condition, but not necessarily one that brings the system to a halt. This level can be useful to trigger email to an alerts list, where it can be filed as a bug by a support engineer.
3) WARN: Not necessarily a bug, but something someone will probably want to know about. If someone is reading a log file, they will typically want to see any warnings that arise.
4) INFO: Used for basic, high-level diagnostic information. Most often good to stick immediately before and after relatively long-running sections of code to answer the question "What is the app doing?" Messages at this level should avoid being very chatty.
5) DEBUG: Used for low-level debugging assistance.
If you are using commons-logging or Log4j, watch out for a common gotcha. The error, warn, info, and debug methods are overloaded with one version that takes only a message parameter, and one that also takes a Throwable as the second parameter. Make sure that if you are trying to log the fact that an exception was thrown, you pass both a message and the exception. If you call the version that accepts a single parameter, and pass it the exception, it hides the stack trace of the exception.
When calling log.debug(), it's good practice to always surround the call with a check for log.isDebugEnabled(). This is purely for optimization. It's simply a good habit to get into, and once you do it for a few days, it will just become automatic.
Do not use System.out or System.err. You should always use a logger. Loggers are extremely configurable and flexible, and each appender can decide which level of severity it wants to report/act on, on a package-by-package basis. Printing a message to System.out is just sloppy and generally unforgivable.

Wednesday, 11 September 2013

Design Patterns for Highly Successful Mobile Apps

Six Design Patterns for Highly Successful Mobile Apps


For years, building web apps has required server-side code and a database. That was great for browsers, but then mobile apps came along and changed everything. Today apps appear on any number of devices, including browsers, and the same app needs to run seamlessly on multiple devices. 
Apps are fundamentally different from their web application counterparts. Traditional web applications run on a monolithic, server-side stack, which delivers content in the form of web pages. For the most part, browsers simply display this content. When a user interacts with a web page, requests are sent to the server for additional content.
In contrast, mobile apps run on a client. Instead of deploying program logic to a back-end server, the logic is housed on the client. This fundamentally changes the dynamic between client and server, making the client no longer merely a display mechanism.
Additional considerations for the development of mobile apps come in the form of the resource constraints imposed by mobile platforms. Mobile apps need to be as lightweight and agile as possible. In other words, you simply wouldn’t run a LAMP stack on an iPhone.
Another challenge for Mobile app developers is dealing with the cumulative traffic that can be generated by even a modest number of clients.  For example, many mobile apps connect to the cloud regularly throughout the day to perform authentication, upload and download data, or to perform geo-queries against a user's current location.  This can result in what amounts to a distributed denial of service attack (DDoS) against an underpowered service architecture.
An added consideration is the data-warehousing infrastructure necessary to deal with all the information being collected. For mobile apps to deliver cutting edge, rich interaction on mobile devices they must be supported by equally rich services and data storage mechanisms.
Enter the cloud.
By hosting rich services in the cloud, client apps can deliver the interactivity that users desire while maintaining a lightweight footprint. With the emergence of mobile PaaS (Platform-as-a-Service) solutions, the days of app developers having to find another developer with a different skill set to help or spending half or more of their development time building services, may soon be gone.
Everything from storing users, groups, roles, single sign-on authentication, social interactions, feeds, queries, connections between users and objects can be provided by a PaaS solution. This leaves the developers to focus on writing cool apps and not on the server code.
So what services do mobile developers need?  We think these 6 patterns are a great start.
1. User Management
Who are you? Who do you know who has the same app? Who do you know outside the app?
One of the most fundamental needs of app developers is user management - straightforward ways to handle users’ (customers’) access control, groups, roles, subscriptions, upgrades, reminders, and so on across multiple devices and apps.
Internet ID and social connectivity also relate to user management. Developers are being rewarded for building identity into apps - from showing pictures of users to bridging to other identities like Twitter and Facebook.
2. Connected & Social Interactions
Who do you follow? Who are your friends? Who will you invite?
In-app and extra-app interactions are all core to mobile apps and devices. For example, an app might bridge out to do a notification or invite a user to join.
In the past, this would have required a generous helping of custom server-side code. Development platforms that provide activity streams, linked profiles, and so on facilitate the development of connected and social interactions.
3. Activity Streams
Activity streams are a kind of static query on moving data. They take connections and turn them into activities, adding a social layer to data and opening up real-time collaboration.
Popular activities vary depending on context but activity streams enable activities such as status updates, check-ins, comments, or other broadcasts to fellow users off of any object or off of multiple objects.
4. Sync Content & Data
Apps need to be able to share data with users, and import, export, and sync application data with third-party applications. The ability to sync data across devices allows developers to create apps, which provide consistency of experience. Think about your favorite “shopping list” or “to do” app that syncs across your laptop, your iPad, and your mobile phone!
5. Location, location, location
Geo-location or Location-Based Service (LBS) apps attach real-world locations to mobile devices and are one of the fastest growing types of apps. You can establish when and where you receive information, track your peers and friends in real-time by location and proximity, find and provide information about things and friends near you.
6. Analytics
App developers need to be able to monitor usage and analyze data to drive both app functionality and business intelligence. Important services include real-time activity processing, behavior tracking and targeting.
Analytics on individual apps are powerful and useful for decision-making about functionality, usage, troubleshooting problems, and so on.  But it’s a game changer when the insights from aggregated data - possibly from multiple apps a developer has created - allow developers to turn what they’re doing into a business and evolve it over time.

by Rod Simpson



Wednesday, 4 September 2013

ImageView Animation in Android


ImageView Animation in Android 


Animation for imageview is very simple here is simplest example.


// Step1 : create the  RotateAnimation object
RotateAnimation anim = new RotateAnimation(0f, 350f, 15f, 15f);
// Step 2:  Set the Animation properties
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);

// Step 3: Start animating the image
 image.startAnimation(anim);

// Later. if you want to  stop the animation
// image.setAnimation(null);


you can download 
another example from here for better understanding :)
http://nineoldandroids.com/

Download

Happy Coddddding :)