Android Application Class


Application class is the base class where you can maintain global variables.
 One can override the Application class by extending his own class  and 
specifying that class in AndroidManifest.xml’s tag.
Application class exists through out the app life cycle.
 Creating a static singletons can serve the purpose instead of extending and overriding Application class.
 But if one needs to manage other memory leaks he can override Applications class methods.import android.R.string;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;

public class myAppClass extends Application {
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
} @Override
public void onCreate() {
super.onCreate();
}

@Override
public void onLowMemory() {
super.onLowMemory();
}

@Override
public void onTerminate() {
super.onTerminate();

}

}

this is lifecycle code in Android Programming
main advantage of application class is , you can access global variable from anywhere in your project without loss, you may ask that we can accomplish this using activity , but difference is when you move from one activity to another one , there is difficult in that, in that case if u extend Application class, you can do that process as follows
public class myAppClass extends Application {
   
        public static String globalWord = “HI DEVS”;
        private static myAppClass Singleton;
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
} @Override
public void onCreate() {
      super.onCreate();
              Singleton = this;   // create singleton
}
public static myAppClass getSingleton()  // access singleton
{
        return Singleton;
}
}


Note:  add this class in  AndroidManifeist file as below
<application
        android:name=”.myAppClass”
        android:icon=”@drawable/ic_launcher”
        android:label=”@string/app_name”
        android:theme=”@style/AppTheme”
        >

       

Feedback and comments expexted as usual


JAVA.IO.FILENOTFOUNDEXCEPTION /data/plog.log (permission denied)

If the log shows the exception ‘FileNotFoundException’ with the ‘Permission Denied’,
the root cause of this error is the file is not being granted for write permission.
It means when the user tries to execute an action to write the data into the file and the file does not have a full permission,
this exception will be thrown to tell you that you are trying to perform an action that violating the permission.

You have to add permission in androidManifiest.xml file like as below

<application android:icon=”@drawable/icon” android:label=”@string/app_name”>
<activity android:name=”.WriteCBTextToFileActivity”
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>
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />

for example if you are trying to access network state ,, you have to add permission for that .
<uses-permission android:name=”android.permission.INTERNET” />
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />

How to create uilabel programatically in iphone development

here is sample code for creating UILabel programatically

UILabel  * label = [[UILabel alloc] initWithFrame:CGRectMake(40, 30, 300, 50)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = UITextAlignmentCenter; // UITextAlignmentCenter, UITextAlignmentLeft
label.textColor=[UIColor whiteColor];
label.numberOfLines=0;
label.lineBreakMode=UILineBreakModeWordWrap;
label.text = @”Created uilabel programatically”;
[self.view addSubview:label];

How to create UIWebView Programatically in iPhone development

Here we are going to create UIWebView programatically,here is code for your reference , as we know webview use to load html strings and url load, Apple provides UIWebView to achieve this task,

-(void)InitWebView
{
// initialize  and create the UIWebView
UIWebView  *aWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
aWebView.autoresizesSubviews = YES;
aWebView.autoresizingMask=(UIViewAutoresizingFlexibleHeight |                 UIViewAutoresizingFlexibleWidth);

//set the web view delegates for the web view to be itself
aWebView.delegate = self;

//Set the URL to go to for your UIWebView
NSString *urlAddress = @”http://www.google.com”;

//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];

//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

//load the URL into the web view.
[aWebView loadRequest:requestObj];

//add the web view to the content view
[self.view addSubview:aWebView];
}
// delegate methods to handle webview results

– (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(@” Request Failed”);
}
– (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(@”Web View Finished Loading”);
}
– (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(@” Handle URL Request”);
return YES;
}

NOTE: Make sure you have added UIWebViewDelegate in your interface header file like this
@interface yourclassname <UIWebViewDelegate>
{
}
@end
and dont forget to set reference to webview delegate , where you want to implement those method.
yourWebView.delegate = self;

Feedback expected , and if you have any queries feel free to contact me

Animating UIImage in UIImageView in iPhone and iPad Development

// create the uiimageview that will execute our animation
UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,480)];

// load all the frames of our animation
imageView .animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@”image1.jpg”],
[UIImage imageNamed:@”image2.jpg”],
[UIImage imageNamed:@”image3.gif”],
nil];

// all frames will execute in 1.75 seconds
imageView .animationDuration = 1.75;
// repeat the annimation forever
imageView .animationRepeatCount = 0;
// start animating
[imageView  startAnimating];
// add the animation view to the main window
[self.view addSubview:imageView ];

/// To Stop animation
[imageView stopAnimating];

how to add UIButton programatically

We all know that we can create any UI control from stroryboard or xib file, by drag and drop in storyboard, but there is certain limitations in it, so lets have a look on adding uicontrol programatically .

here is the code for adding uibutton programatically .

UIButton *Button = [[UIButton alloc] initWithFrame:CGRectMake(0,0,100,100)];/ button created button setBackgroundImage :[UIImage imageNamed:@”image.jpg”]];
[self.view addSubview:button] // adding button as subview to your main view.
button.hidden =  NO;

// thats it now button has been created , lets play some other thing with this button

[button setTitle:@”myButton”];

if you don’t want background image and title, instead of that you like displaying graphical title with nice artwork. Simple create your artwork image and you can set that image to uibutton

[button setImage :[UIImage imageNamed:@”artwork.png”] forControlState:UIControlStateNormal];

if you want to change image while click on that button,  you can add highlighted  artwork image and add it like below

[button setImage :[UIImage imageNamed:@”artwork.png”] forControlState:UIControlStateHighLighted];

NOTE: dont forget adding those images in your xcode project (simply drag your image and drop it in your project resources)

next thing we need to add action for button click

[button addTarget:self selector:@selector(buttonEvent) forEventState:UIControlTouchUpInside]

and if you want to change button position to somewhere
button.frame = CGRectMake(0,240,100,100);

 

Increasing performance of iPhone iPad application in asynchronous image downloading

in most of iOS application we need to download large number of images from server , for that we may use synchronous , but drawback in synchronous method  is , it blocks UI when data is huge,So to solve this problem we need to use asynchronous method ,here we use NSOperationqueue , and we have to create NSInvocationOperations to achieve this task , it enhances performance of application and never block UI.

-(void)InitiateAsynch
{
NSOperationQueue *operationQueue = [[NSOperationQueue alloc]init];
int nTotImage = 5;
for(int i = 0; i  nTotImage ; i++)
{
NSInvocationOperation *invocationOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(DownloadAsynch:) object:[NSString stringWithFormat:@”%d”,i]];
[queue addOperation:invocationOperation];
[invocationOperation  release];
}
}

-(void)DownloadAsynch: (NSString*)imageNo
{
NSString *imgStr = [NSString stringWithFormat:@”yourURL/%@.jpg”,imageNo]; /// change to  your URL
NSData *imageData=[[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:imgStr]];
UIImage *image=[[UIImage alloc]initWithData:imageData];
[imgDict setValue:image forKey:@”image”];
[imgDict setValue:imageNo forKey:@”imageNo”];
[self performSelectorOnMainThread:@selector(DisplayImg:) withObject:imgDict waitUntilDone:NO];
}

-(void)DisplayImg:(NSMutableDictionary *)Dict
{
int i = [[Dict objectForKey:@”imageNo”] intValue];
// waana display all images in single image view
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)];
[imgView setImage:[Dict objectForKey:@”image”]];
[self.view addSubview:imgView];

// wanna display all downloaded images in scrollview

UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(320*i, 0, 320, 320)];
[imgView setImage:[Dict objectForKey:@”image”]];
[YourScrolllView addSubview:imgView];
}