Monday, October 28, 2013

View, SurfaceView

1. What is View in Android?
Ans: A widgets like buttons and text fields. A activity uses views and fragmaents to create the user interface. View Hierarchy: Hierarchy Viewer allows you to debug and optimize your user interface. It provides a visual representation of the layout's View hierarchy (the Layout View) and a magnified inspector of the display (the Pixel Perfect View).

2. What is Surface View?
Ans: Provides a dedicated drawing surface embedded inside of a view hierarchy. You can control the format of this surface and, if you like, its size; the SurfaceView takes care of placing the surface at the correct location on the screen

3. How you Use Surface view in Android and Show me working code?
Ans: with surfaceCreated(surfaceholder) and surfaceDestroyed(surfaceholder) methods.

4. Is it possible to add any view in Android Surface View ?
Ans. yes

5. If adding view on surface view then Show one example?

Ans. Enclose your surfaceView with a FrameLayout in your xml Layout. Then add your buttons to the same FrameLayout. Make sure they are placed below the surface view so they get drawn on top of it.

android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

android:layout_height="wrap_content"
android:layout_width="wrap_content">



android:layout_height="wrap_content"
android:layout_width="wrap_content">









6. What is media Player in android, why it’s needed?
Ans: MediaPlayer class can be used to control playback of audio/video files and streams.
Displays a video file. The VideoView class can load images from various sources (such as resources or content providers), takes care of computing its measurement from the video so that it can be used in any layout manager, and provides various display options such as scaling and tinting.

7. Can Media player UI resize? if so, show me a working code?
Ans: yes

8. What are the layouts available to create a UI-layout in .xml file?
Ans: Relative Layout, Linear Layout.Table Layout and Frame Layout.

9. Is there difference between Media player from Layout .xml file and Media player from android java code?
yes

Tuesday, October 22, 2013

How to store Logs in a txt file using the android

Here with I attached simple Logger class definition, you can use at it is. To store the log information in to Log.txt file in SDCARD, use at it is.


package com.clientname.projectname;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.FileHandler;
import android.os.Environment;

import android.util.Log;/**
•@author Rakesh.Jha
•Date - 07/10/2013
•Definition - Logger file use to keep Log info to external SD with the simple method
*/

public class Logger{

public static FileHandler logger = null;
private static String filename = "ProjectName_Log";
static boolean isExternalStorageAvailable = false;
static boolean isExternalStorageWriteable = false;
static String state = Environment.getExternalStorageState();

public static void addRecordToLog(String message){
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
isExternalStorageAvailable = isExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
isExternalStorageAvailable = true;
isExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need

// to know is we can neither read nor write
isExternalStorageAvailable = isExternalStorageWriteable = false;
}

File dir = new File("/sdcard/Files/Project_Name");
if (Environment.MEDIA_MOUNTED.equals(state)) {
if(!dir.exists())
{

Log.d("Dir created ", "Dir created ");
dir.mkdirs();
}

File logFile = new File("/sdcard/Files/Project_Name/"+filename+".txt");
if (!logFile.exists())
{
try
{
Log.d("File created ", "File created ");
logFile.createNewFile();

}
catch (IOException e)
{

// TODO Auto-generated catch block

e.printStackTrace();

}

}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(message + "\r\n");
//buf.append(message);
buf.newLine();
buf.flush();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();

}
}
}
}


Now once you created this file, where ever you want to store a log info into log.txt file use below code. -

package com.clientname.projectname;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;/**

•@author Rakesh.Jha

•Date - 03/10/2013
•Definition - //ToDO
*/


public class MainActivity extends Activity {
private static final String TAG = null;
Logger logger;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Testing :","log");
// no need to do this line, use below line
logger.addRecordToLog("Testing : log " );
logger.addRecordToLog("TAG MediaPlayer audio session ID: " );
MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.test);

//test is audio file, u have to keep in raw folder
logger.addRecordToLog( "MediaPlayer audio session ID: " + mediaPlayer.getAudioSessionId());
logger.addRecordToLog( "Media Player started " + "Started !");
mediaPlayer.start();
// no need to call prepare(); create() does that for you
}
}
private void prepareMediaServer() {


}
}

Singleton in Android

Singleton is a part of Gang of Four design pattern and it is categorized under creational design patterns.

-> Static member : This contains the instance of the singleton class.
-> Private constructor : This will prevent anybody else to instantiate the Singleton class.
-> Static public method : This provides the global point of access to the Singleton object and returns the instance to the client calling class.

1.create private instance
2.create private constructor
3.use getInstance() of Singleton class


public class Logger{
private static Logger objLogger;
private Logger(){
//ToDo here
}

public static Logger getInstance() {
if (objLogger == null) {
objLogger = new Logger();
}
return objLogger;
}
}

Tuesday, September 24, 2013

Error - com.android.ddmlib.InstallException: EOF

If getting below error - 
 
[2012-01-03 11:27:03 - HelloAndroid] Failed to install HelloAndroid.apk on device 
 emulator-5554!
[2012-01-03 11:27:03 - HelloAndroid] (null)
[2012-01-03 11:27:03 - HelloAndroid] Failed to install HelloAndroid.apk on device
 'emulator-5554': EOF
[2012-01-03 11:27:03 - HelloAndroid] com.android.ddmlib.InstallException: EOF
[2012-01-03 11:27:03 - HelloAndroid] Launch canceled!
 
 

DLNA with Android - UPnP

DLNA, or the Digital Living Network Alliance is an organization set up by Sony in 2003 that determines a universal set of rules and guidelines so devices can share digital media. The devices covered include computers, cameras, televisions, network storage devices, and of course cell phones. The guidelines are built from existing standards, but manufacturers have to pay to use them and have their device join the DLNA.

Saturday, April 13, 2013

Memory Management in Android

What is Memory?
What is Management ?
What is Memory Management in Android ?
Why we take care of memory management related problems in Android ?
When we take care of memory management in Android ?
What is heap size and how to manage heap size ?
What is memory leak ?
What is MAT (Eclipse Memory Analyzer tool)
What is GC (Garbage collection) and use of gc ?



Android Memory

Android is a Linux based OS with 2.6.x kernel, stripped down to handle most tasks pretty well. It uses native open source C libraries that have powered Linux machines for years. All the basic OS operations like I/O, memory management, and so on, are handled by the native stripped-down Linux kernel


Friday, April 5, 2013

How to use JSON in Android ?


JSON - JavaScript Object Notification.


JSON (JavaScript Object Notation) is an independent data exchange format. JSON is limited to text and numeric values. Binary values are not supported.

JSON is a subset of the JavaScript Specification (ECME-Script) and it is therefore directly supported in JavaScript.

Data structures in JSON are based on key / value pairs. The key is a string, the value can be a numerical value, a Boolean value (true or false) or an object.



Thursday, April 4, 2013

What is REST ?


Web services is a generic name for web-based RPC. This includes SOAP-based web services, which normally go by the proper name "Web Services"; but now, REST is also considered a web-service architecture.


REST is a non-XML-based, web-based RPC; but it is also a design philosophy and architecture.


REST stands for Representational State Transfer. (It is sometimes spelled "ReST".) It relies on a stateless, client-server, cacheable communications protocol -- and in virtually all cases, the HTTP protocol is used.

REST is a lightweight alternative to Web Services and RPC.

Wednesday, April 3, 2013

What is ANR issue in Android ?

If you getting ANR issue in Apps, try to understand what does it means ?

01-12 18:00:57.048 E/ActivityManager( 1709): ANR in com.kt.twwidget
01-12 18:01:18.700 E/ActivityManager( 1709): ANR in  com.kt.twwidget
01-12 18:01:40.800 E/ActivityManager( 1709): ANR in system
01-12 18:02:59.280 E/ActivityManager( 1709): ANR in  com.kt.twwidget
01-12 18:03:21.010 E/ActivityManager( 1709): ANR in  com.kt.twwidget


This issue is well-known in the Android community. Using part of its terminology, this issue is called an ANR or Application Not Responding. Thus, the application “system” appears to stop working or there is something that makes it to wait for a huge period of time,that huge, that an ANR is fired by the system. Because this happens at boot time, the entire system seems to freeze and it is not until the user kills this application that the terminal finishes its booting procedure and makes itself available to the user once again. From time to time, though not always, this odd behaviour can end up in an unexpected reboot.

An ANR happens when some long operation takes place in the "main" thread. This is the event loop thread, and if it is busy, Android cannot process any further GUI events in the application, and thus throws up an ANR dialog.

Many way of ANR issue throwing - 

1. Longer operation of method
2. Blocking the thread permanently
3. 

Detecting

Detecting from where ANRs issues happening is easy.
1. if it is a permanent block (deadlock situation is coming from CODE) , but harder if it's just a temporary delay. 
2. First, go over your code and look for vunerable spots and long running operations.
For examples may include using sockets, locks, thread sleeps, and other blocking operations from within the event thread. 
You should make sure these all happen in separate threads. If nothing seems the problem, use DDMS and enable the thread view. This shows all the threads in your application similar to the trace you have. Reproduce the ANR, and refresh the main thread at the same time. That should show you precisely whats going on at the time of the ANR

The stack trace shows that the main thread is in the Looper (the message loop implementation) and doing a timed wait through Object.wait. This means the message loops does not currently have any messages to dispatch, and is waiting for new messages to come in. An ANR happens when the system realizes a message loop is spending to much time processing a message, and not processing other messages in the queue. If the loops is waiting for messages, obviously this is not happening.

Approch - 


You can enable StrictMode in API level 9 and above - 


StrictMode is most commonly used to catch accidental disk or network access on the application's main thread, where UI operations are received and animations take place. By keeping your application's main thread responsive, you also prevent ANR dialogs from being shown to users.
public void onCreate() {
    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                           .detectAll()
                           .penaltyLog()
                           .penaltyDeath()
                           .build());
    super.onCreate();
}
using penaltyLog() you can watch the output of adb logcat while you use your application to see the violations as they happen.






What is a Hybrid App?





Hybrid is anything derived from heterogeneous sources, combination of different sources, in different manner, or composed of elements of different or incongruous kinds.

A hybrid app is one that is written with the same technology used for websites and mobile web implementations, and that is hosted or runs inside a native container on a mobile device.

Hybrid apps uses a web view control for corresponding OS (UIWebView on iOS, WebView on Android and others) to present the HTML and JavaScript files in a full-screen format, using the native browser rendering engine (not the browser itself).

WebKit is the browser rendering engine that is used on iOS, Android, Blackberry, i.e. HTML and JavaScript used to design & develop hybrid app, will rendered/processed by the WebKit rendering engine and displayed to the user in a full-screen web view control, not in a browser. 

 Apache Cordova (formerly PhoneGap) is an example of a JavaScript abstraction layer over native APIs. Through this abstraction layer (between native & hybrid) a common set of APIs is exposed in JavaScript, and these JavaScript APIs work on any device supported by the framework (Cordova that is seven mobile platforms including iOS, Android, Blackberry and Windows Phone 7). 

When the native wrapper is compiled around the HTML, CSS and JavaScript resources, there is an interop layer added that connects the JavaScript APIs with the platform specific APIs.


For Example - 


Working with Camera, when we want to take a image through camera, how  it is working in different platform (iOS or Android) -


Under the covers the JavaScript is making an interop call that access the native API for the camera. 

That means that on an iOS device this JavaScript is calling into the native layer to instantiate a  UIImagePickerController and on Android it creates an Intent to use MediaStore.ACTION_IMAGE_CAPTURE to take a picture.

As a developer, no worry about all above stuff (internal calling or internal working process), you just need to call the JavaScript function (navigator.camera.getPicture() in this case), and respond to the outcome (the imageData passed to the onCameraSuccess call back function in this case).



So, what we conclude - 



Hybrid apps are a great option for you if you:
  1. Want to target multiple mobile platforms
  2. Want to take advantage of device capabilities like geolocation, accelerometer or the camera
  3. Want the app to be useable when the device is offline
  4. Don’t need the advanced graphics performance that you can only get from a native app
Hybrid apps are built with web technologies which means there are millions of web developers who already have the base skill set to build mobile apps.


What is Hybrid mobile apps, Native apps and Mobile apps ?


For a developer, before moving to any particular language, or area, s/he should think about all pros & cons.
When we are talking to Mobility, things is coming into mind is –

1.      Android
2.      iOS
3.      BlackBerry
4.      Windows

But, if we are talking about Android, then the area comes into picture is –

1.      Native apps development
2.      Hybrid apps development
3.      Mobile web apps development

Native apps are built for a specific platform with the platform SDK, tools and languages, typically provided by the platform vendor (e.g. xCode/Objective-C for iOS, Eclipse/Java for Android, Visual Studio/C# for Windows Phone).

- Always provide the fasted performance
- Cost will little bit high, if it is single platform development
- Always good for games

Mobile Web apps are server-side apps, built with any server-side technology (PHP, Node.js, ASP.NET) that render HTML that has been styled so that it renders well on a device form factor.

Hybrid apps, like native apps, run on the device, and are written with web technologies (HTML5, CSS and JavaScript). Hybrid apps run inside a native container, and leverage the device’s browser engine (but not the browser) to render the HTML and process the JavaScript locally. A web-to-native abstraction layer enables access to device capabilities that are not accessible in Mobile Web applications, such as the accelerometer, camera and local storage.

Hybrid app will be easier to build,
- Used HTML5 , CSS, JavaScript, JQuery mobile
- Cost will less if developed for multiple platforms
- For game it is not good

What should I Choose Native, Hybrid or Mobile web application development?
Answer will be depends L, so before committing down a single path consider the user experience and what each option provides you.

Depends upon –

1.      Depends on budget
2.      Depends on apps type(game or application)
3.      Depends on scarify (performance, look & feel)
4.      Time
5.      And lots of thing, on which developer can choose the development tools or way

Like any other technology choice, deciding between native and hybrid requires you to look at the user experience and decide on the level of investment you need to make to achieve the goal.

They also need to be written/rewritten for each mobile platform you are targeting. Hybrid apps will always enable you to build for more platforms faster, if you are willing to sacrifice small amounts of performance (e.g. game-level responsiveness).




Friday, March 15, 2013

Before Launch Android Application - CheckList




Shipping your Android application: A Complete checklist





I recently completed my 20th Android application. I learned a lot from the project, which was a really a good to understand what to do what don't.

Herewith I'm listing out some point to be follow before the launch of application -

1. You need to sure apps must be in industry standart

Manifest

  • Decide/test what SDK versions you are compatible with, and explicitly set the <uses-sdk> element. Example:
    <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="8"/>
    • You can set the android:targetSdkVersion attribute to indicate which SDK you built against, and for which the app is intended to run on
    • You can set android:minSdkVersion to indicate the lowest revision of the SDK that the app will run against. Apps built against newer versions of the SDK will generally run on older devices, as long as you are careful not to invoke API calls that do not exist in the older SDK.
    • Here is a reference to the various SDK levels and what releases of Android correspond to them.
    • Here are some references for best practices in targeting your app to run on various versions of Android while still taking advantage of the latest OS features:
  • Decide what screen resolutions you are compatible against. Our app is intended to run on medium and large displays, but does not run well on devices such as the Motorola Charm and Flipout, which have Blackberry-style form factors with small screens. So we included the <supports-screens> element in our manifest, with android:SmallScreens="false".
    <supports-screens android:smallScreens="false"/>
  • Is your application intended to run only on a touchscreen, and not on a traditional style (keypad + d-pad) interface?  If so, set the <uses-configuration> elements appropriately. You can specify more than one for an “or”-style grouping of supported configurations. This example says the application is compatible with both stylus-driven (resistive) and finger-driven (capacitance) touchscreens, but one or the other is required:
    <uses-configuration android:reqTouchScreen="stylus"/>
    <uses-configuration android:reqTouchScreen="finger"/>
  • Explicitly set a top-level theme for your application, using the android:theme attribute of the <application> element. Here’s an example manifest entry:
    <application android:icon="@drawable/icon"
                  android:label="@string/app_name"
                  android:theme="@android:style/Theme.Light"
                  android:debuggable="false"
                  android:name="com.myorg.myapp.MyAppSubclass">
         <!-- blah blah blah -->
    </application>

Packaging

  • Clean up unnecessary permissions qualifiers in your manifest. You don’t want to ask for more system permissions than your app really needs. People are sensitive to this stuff.
  • Clean up unused assets (image, audio, layouts, etc) in your res folder hierarchy. It’s amazing how assets can get orphaned as your application’s interface moves through iterations of design. Leaving them in the app only increases the size of the APK and takes up more space on your user’s devices.
  • Turn off debug logging:
    • The Android Log API will antagonize the garbage collector if you do string concatenation in your log messages (and we all do that).
  • Shut off debug menus (unless you want your customers to access them).
  • Change the debuggable=true item in your application element to false (as in the above example).

Resources

  • Externalize view layouts from Java code into XML layout files.
  • When defining styles, it helps to explicitly specify all the attributes that you want to be sure are presented a particular way.
    • Different device manufacturers tinker with the built-in themes, and your application can inherit font, size and color attributes different from what you expected when your application is run on a device different from those you used during development.
  • Externalize resources, such as drawables and color definitions, into XML.
  • Externalize strings into XML.
  • Remove hardcoded pixel constants in your code, layouts, and resources. Use device-independent pixels (dp units in your layout files) wherever possible, and more likely than not things will “just work” when your app runs on different screen resolutions.
  • Include assets as needed for high-density, medium-density and low-density displays.

Application

  • Save application state, terminate threads, and clean up state on onPause/onStop/onDestroy handler methods within your activities.
  • Subclass the Android Application object:
    • Register your subclass by setting the android:name attribute of the <application> element in your manifest.
    • Implement application onLowMemory handler, and be a nice citizen.
    • Implement application lifecycle methods onCreate, onTerminate. Create global items to share between activities in onCreate, and clean up resources as best you can in onTerminate.
  • Implement configChanges in your Manifest and onConfigurationChanged in your Activity classes, to intercept default behavior for system configuration changes. If you don’t do this, Android will kill and restart your activities to handle them:
    • When the user rotates the device between portrait and landscape. The following Manifest example will cause Android to invoke onConfigurationChanged in your activity class when the user rotates the device, rather than Android stopping and restarting your activity:
      <activity android:name=".activity.MyAwesomeActivity"
                android:label="@string/app_name"
                android:configChanges="orientation"
                >
                <!-- remainder of activity declaration goes here -->
      </activity>
      And here is how you would respond to it within your Activity:
      @Override
      public void onConfigurationChanged(Configuration newConfig) {
          // TODO do something here
          super.onConfigurationChanged(newConfig);
      }
    • When the user slides in/out the hardware keyboard on some devices, such as the original Droid/Milestone from Motorola. The following Manifest example will cause Android to invoke onConfigurationChanged when the user changes the keyboard configuration, again without killing your activity:
      <activity android:name=".activity.MyAwesomeActivity"
                android:label="@string/app_name"
                android:configChanges="keyboard|keyboardHidden"
                >
                <!-- remainder of activity declaration goes here -->
      </activity>
    • In both cases, it’s worth noting that you’re intended to respond to the change within the body of onConfigurationChanged. But you can also not bother to override onConfigurationChanged, which effectively disables Android’s activity kill/restart mechanism. You should do this only if you are certain your activity will not be affected by the change in question.
    • More information about configuration changes is available at the official Android developer site.
  • Implement Activity onLowMemory handlers.
  • Make sure background threads are terminated properly on switch between Activities.

External Storage

  • Support application installation to SD card if at all possible. Owners of devices such as the Nexus One, with limited internal storage, will thank you.
  • Properly determine location if you plan to use the SD card for temporary storage.
    • In Froyo (Android 2.2) and later, use the Context#getExternalFilesDir method to get a directory for your temp files, which will automatically be cleaned up by the Android OS if the user uninstalls your application.
    • On earlier releases of Android, you can create a folder in the same place that getExternalFilesDir would provide. When the user updates to Froyo, Android will still auto-remove the contents on app uninstall.
private static final String EXT_STORAGE_ROOT = "/Android/data/com.mycompany.myapp/files/";
cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), EXT_STORAGE_ROOT + dirName);

Networking

  • Ensure your application behaves properly (posts error message, etc) when Airplane mode is enabled.

Battery Life

Most of these suggestions came from the Google I/O presentation Coding for Life — Battery Life, That Is:
  • Try to avoid EDGE/2G for large data transfers – use 3G or WiFi if you can.
  • Use GZIP compression for HTTP access whenever possible:
    • The less time you keep the radio active, the bigger you win with battery life.
    • The CPU used for decompression is fast, native, and negligible compared to keeping the radio running.
  • Reduce garbage collection:
    • Retain a single instance to an object, perhaps as a class member, rather than reallocating it.
    • Set references to null when you are done with them, to release them to the garbage collector earlier rather than later.
  • Recycle Regex Matcher objects:
    • Matcher#reset(newString) to reuse the matcher object.
  • Recycle StringBuilder object instances:
    • use StringBuilder#setLength(0) – good as new!
  • Share static objects (such as StringBuilders) in classes such as ListAdapter, where they get called often.
  • Use stream-based parsers for JSON and XML, not tree-based ones.
  • Keep background services alive only as long as necessary, and run them only as frequently as necessary.
  • Periodic background services should wake up on an alarm, try to run only when the system is already running, and schedule themselves to be invoked “inexactly”, as a group along with other alarms.
  • Fixed-point arithmetic is better than floating-point. ARM processors don’t have native floating-point instructions and must do all floating point as multi-instruction algorithms, which is really expensive.
  • Be careful with wake-locks. They can kill the battery like a vampire.
    • Use a window-managed wake-lock if you can, which Android will automatically handle for you:
    • getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    • Or set the android:keepScreenOn="true" attribute in your XML layouts for controls that must keep the screen alive.
    • Finally, if you must create and manage your own wake-lock, specify a timeout so it will expire if you forget to release it.



Resouces - google, Android and tagged in Android

Android and strange error with maps from google


If you getting below error -

 03-15 14:22:40.464: W/System.err(2358):     at android_maps_conflict_avoidance.com.google.googlenav.map.BaseTileRequest.readResponseData(BaseTileRequest.java:115)
03-15 14:22:40.465:
W/System.err(2358):     at android_maps_conflict_avoidance.com.google.googlenav.map.MapService$MapTileRequest.readResponseData(MapService.java:1473)
03-15 14:22:40.465: W/System.err(2358):    
at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher.processDataRequest(DataRequestDispatcher.java:1117)
03-15 14:22:40.465: W/System.err(2358):    
at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher.serviceRequests(DataRequestDispatcher.java:994)
03-15 14:22:40.465: W/System.err(2358):    
at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher$DispatcherServer.run(DataRequestDispatcher.java:1702)
03-15 14:22:40.465: W/System.err(2358):    
at java.lang.Thread.run(Thread.java:856)


10-03 15:54:51.784: WARN/System.err(12994): java.io.IOException: Server returned: 3
10-03 15:54:51.784: WARN/System.err(12994):     at android_maps_conflict_avoidance.com.google.googlenav.map.BaseTileRequest.readResponseData(BaseTileRequest.java:115)
10-03 15:54:51.784: WARN/System.err(12994):     at android_maps_conflict_avoidance.com.google.googlenav.map.MapService$MapTileRequest.readResponseData(MapService.java:1473)
10-03 15:54:51.784: WARN/System.err(12994):     at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher.processDataRequest(DataRequestDispatcher.java:1117)
10-03 15:54:51.784: WARN/System.err(12994):     at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher.serviceRequests(DataRequestDispatcher.java:994)
10-03 15:54:51.784: WARN/System.err(12994):     at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher$DispatcherServer.run(DataRequestDispatcher.java:1702)
10-03 15:54:51.784: WARN/System.err(12994):     at java.lang.Thread.run(Thread.java:1019)
 
 
 
SSolution - 
 
Use two key - debug key and release key
 
 <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.Sherlock" 
        android:debuggable="false"> 
 
And 
 
Follow below steps - 
 
You can't use debug.keystore to create a Google Maps API key for applications going into the market. If you already have the application (or indeed any application) in the market then you already have the keystore you should use. This is how you use this keystore to get a Google Maps API key:
Step 1: At the command line navigate to the directory with your keystore file in it:
cd <keystore-dir>
Step 2: Now list the contents of your keystore:
keytool -list -keystore <your-keystore-file>
Step 3: Enter the password for your keystore when prompted. Keytool will now display a list of certificates and their MD5s.
Step 4: Copy the MD5 for the certificate you are going to use to sign your application into your copy/paste buffer.
Step 5: Open a browser and navigate to http://code.google.com/android/maps-api-signup.html - if you're not logged in with your Android Market account, you'll need to do that next, before you generate your API key.
Step 6: Paste the MD5 from your copy/paste buffer into the text box labelled "My certificate's MD5 fingerprint:" and tick the "I have read and agreed..." box.
Step 7: Click 'Generate API Key'. You'll now see the API key you need to use.
Step 8: Copy and paste the API key into your MapView component's android:apiKey property.
If you have multiple MapView components then you can declare a string resource:
<string name="production_api_key">thisIsMyKeyValue</string>
Now you can use this in your android:apiKey property in the same way that you reference any other string value:
android:apiKey="@string/production_api_key"
Now export the application to an APK file using the certificate you used in step 4.
Provided you follow this step-by-step guide you should be OK - I've just myself started using a maps API key generated in this way.
Things to watch out for:
  • Using the MD5 of the keystore file (md5 <my-keystore-file>), not of the certificate. Its the MD5 of the certificate you need.
  • Being logged in to Google when you generate the API key, but with the wrong account. Your maps API key and your Android Market signing key must belong to the same Google account.
 
If you are using FrameLayout then -
 
<FrameLayout
            android:id="@+id/mapview_bg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/silver" 
            >

            <com.google.android.maps.MapView
                android:id="@+id/deal_mapview"
                android:layout_width="146dp"
                android:layout_height="106dp"
                android:apiKey="@string/google_map_api_key"
                android:clickable="true" />
       </FrameLayout>
 
 
Sources - google, stack and personal exp 
  

Monday, January 14, 2013

Java - Data Structure Question & Answer

1. What is data structure?
A data structure is a way of organizing data that considers not only the items stored, but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data.


There are two types of data structure
  • Linear 
  • Nonlinear

2. List out the areas in which data structures are applied extensively?
  1. Compiler Design,
  2. Operating System,
  3. Database Management System,
  4. Statistical analysis package,
  5. Numerical Analysis,
  6. Graphics,
  7. Artificial Intelligence,
  8. Simulation
3. What are the major data structures used in the following areas : RDBMS, Network data model and Hierarchical data model.
  1. RDBMS = Array (i.e. Array of structures)
  2. Network data model = Graph
  3. Hierarchical data model = Trees
4. If you are using C language to implement the heterogeneous linked list, what pointer type will you use?
The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type.
5. Minimum number of queues needed to implement the priority queue?
Two. One queue is used for actual storing of data and another for storing priorities.
6. What is the data structures used to perform recursion?
Stack. Because of its LIFO (Last In First Out) property it remembers its 'caller' so knows whom to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls.
Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, explicit stack is to be used.

7. What are the notations used in Evaluation of Arithmetic Expressions using prefix and postfix forms?
Polish and Reverse Polish notations.
8. Convert the expression ((A + B) * C - (D - E) ^ (F + G)) to equivalent Prefix and Postfix notations.
  1. Prefix Notation: - * +ABC ^ - DE + FG
  2. Postfix Notation: AB + C * DE - FG + ^ -
9. Sorting is not possible by using which of the following methods? (Insertion, Selection, Exchange, Deletion)

Sorting is not possible in Deletion. Using insertion we can perform insertion sort, using selection we can perform selection sort, using exchange we can perform the bubble sort (and other similar sorting methods). But no sorting method can be done just using deletion.
10. What are the methods available in storing sequential files ?
  1. Straight merging,
  2. Natural merging,
  3. Polyphase sort,
  4. Distribution of Initial runs.
11. List out few of the Application of tree data-structure?
  1. The manipulation of Arithmetic expression,
  2. Symbol Table construction,
  3. Syntax analysis.
12. List out few of the applications that make use of Multilinked Structures?
  1. Sparse matrix,
  2. Index generation. 
13. In tree construction which is the suitable efficient data structure? (Array, Linked list, Stack, Queue)
Linked list is the suitable efficient data structure.
14. What is the type of the algorithm used in solving the 8 Queens problem?
 Backtracking.
15. In an AVL tree, at what condition the balancing is to be done?
If the 'pivotal value' (or the 'Height factor') is greater than 1 or less than -1.
16. What is the bucket size, when the overlapping and collision occur at same time?
One. If there is only one entry possible in the bucket, when the collision occurs, there is no way to accommodate the colliding value. This results in the overlapping of values.
17. Classify the Hashing Functions based on the various methods by which the key value is found.
  1. Direct method,
  2. Subtraction method,
  3. Modulo-Division method,
  4. Digit-Extraction method,
  5. Mid-Square method,
  6. Folding method,
  7. Pseudo-random method.
18. What are the types of Collision Resolution Techniques and the methods used in each of the type?
  1. Open addressing (closed hashing), The methods used include: Overflow block.
  2. Closed addressing (open hashing), The methods used include: Linked list, Binary tree.
19. In RDBMS, what is the efficient data structure used in the internal storage representation?
B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes searching easier. This corresponds to the records that shall be stored in leaf nodes.
20. What is a spanning Tree?
A spanning tree is a tree associated with a network. All the nodes of the graph appear on the tree once. A minimum spanning tree is a spanning tree organized so that the total edge weight between nodes is minimized.
21. Does the minimum spanning tree of a graph give the shortest distance between any 2 specified nodes?
No. The Minimal spanning tree assures that the total weight of the tree is kept at its minimum. But it doesn't mean that the distance between any two nodes involved in the minimum-spanning tree is minimum.
22. Which is the simplest file structure? (Sequential, Indexed, Random)
Sequential is the simplest file structure.
23. Whether Linked List is linear or Non-linear data structure?
According to Access strategies Linked list is a linear one.
According to Storage Linked List is a Non-linear one.

24. What is a Linked list ?
A linked list is a linear collection of data elements, called nodes, where the linear order is given by pointers. Each node has two parts first part contain the information of the element second part contains the address of the next node in the list.

25. What is Queue ?
 A queue is an ordered collection of items from which items may be deleted at one end (front end) and items inserted at the other end (rear end). It obeys FIFO rule there is no limit to the number of elements a queue contains.

 26. What is Precision ?
Precision refers the accuracy of the decimal portion of a value. Precision is the number of digits allowed after the decimal point.

27.  What are the goals of Data Structure ?
It must rich enough in structure to reflect the actual relationship of data in real world. The structure should be simple enough for efficient processing of data.

28. What is the difference between a Stack and an Array?
    Stack
  • Stack is a dynamic object whose size is constantly changing as items are pushed and popped .
  • Stack may contain different data types.
  • Stack is declared as a structure containing an array to hold the element of the stack, and an integer to indicate the current stack top within the array.
  • Stack is a ordered collection of items.
  • Array
  • Array is an ordered collection of items.
  • Array is a static object.
  • It contains same data types.
  • Array can be home of a stack i.e. array can be declared large enough for maximum size of the stack.

 29. What is Sequential Search ?

In sequential search each item in the array is compared with the item being searched until a match occurs. It is applicable to a table organized either as an array or as a linked list.

 30. What are the disadvantages array implementations of linked list?
The no of nodes needed can’t be predicted when the program is written.
The no of nodes declared must remain allocated throughout its execution.

31. What is a priority queue?
The priority queue is a data structure in which the intrinsic ordering of the elements.

32. What are the disadvantages of sequential storage?
Fixed amount of storage remains allocated to the data structure even if it contains less element.
No more than fixed amount of storage is allocated causing overflow.

33. Define circular list?
In linear list the next field of the last node contain a null pointer, when a next field in the last node contain a pointer back to the first node it is called circular list.

34. What does abstract Data Type Mean?
Data type is a collection of values and a set of operations on these values. Abstract data type refer to the mathematical concept that define the data type.

35.  What do you mean by recursive definition?
The definition which defines an object in terms of simpler cases of itself is called recursive definition.

36. What actions are performed when a function is called?
    When a function is called
  • arguments are passed
  • local variables are allocated and initialized
  • transferring control to the function

37. Define double linked list?
    It is a collection of data elements called nodes, where each node is divided into three parts
  • An info field that contains the information stored in the node.
  • Left field that contain pointer to node on left side.
  • Right field that contain pointer to node on right side.
38. What do you mean by overflow and underflow?
When new data is to be inserted into the data structure but there is no available space i.e.free storage list is empty this situation is called overflow.
When we want to delete data from a data structure that is empty this situation is called underflow.

39. Whether Linked List is linear or Non-linear data structure?
According to Access strategies Linked list is a linear one. According to Storage Linked List is a Non-linear one.

40. What do you mean by free pool?
Pool is a list consisting of unused memory cells which has its own pointer.


 41. What are the methods available in storing sequential files ?
  • Straight merging
  • Natural merging
  • Polyphase sort
  • Distribution of Initial runs

 42. What is a node class?
A node class is a class that has added new services or functionality beyond the services inherited from its base class.

 43. what is binary tree?
A binary tree is a tree data structure in which each node has at most two child nodes, usually distinguished as left and right.

44. Why is the isEmpty() member method called?

The isEmpty() member method is called within the dequeue process to determine if there is an item in the queue to be removed i.e. isEmpty() is called to decide whether the queue has at least one element. This method is called by the dequeue() method before returning the front element.

 45. How is the front of the queue calculated ?
The front of the queue is calculated by front = (front+1) % size.

 46. What does each entry in the Link List called?
Each entry in a linked list is called a node. Think of a node as an entry that has three sub entries. One sub entry contains the data, which may be one attribute or many attributes. Another points to the previous node, and the last points to the next node. When you enter a new item on a linked list, you allocate the new node and then set the pointers to previous and next nodes.

 47. What member function places a new node at the end of the linked list?
The appendNode() member function places a new node at the end of the linked list. The appendNode() requires an integer representing the current data of the node.

48. How is any Data Structure application is classified among files?
A linked list application can be organized into a header file, source file and main application file. The first file is the header file that contains the definition of the NODE structure and the LinkedList class definition. The second file is a source code file containing the implementation of member functions of the LinkedList class. The last file is the application file that contains code that creates and uses the LinkedList class.

49. Run Time Memory Allocation is known as ?
Allocating memory at runtime is called a dynamically allocating memory. In this, you dynamically allocate memory by using the new operator when declaring the array, for example : int grades[] = new int[10];

50. What method is used to place a value onto the top of a stack?
push() method, Push is the direction that data is being added to the stack. push() member method places a value onto the top of a stack.

51. What method removes the value from the top of a stack?
The pop() member method removes the value from the top of a stack, which is then returned by the pop() member method to the statement that calls the pop() member method.

52. Tell how to check whether a linked list is circular ?
Create two pointers, each set to the start of the list. Update each as follows:

while (pointer1)

{
pointer1 = pointer1->next;
pointer2 = pointer2->next; if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2)

? ? ? ? ? ? {
print (\”circular\n\”);
}
}