Friday, June 29, 2012

Android Toast notification show Different Gravity.

Android Toast notification show Different Gravity.
Android  toast notification is a message that pops up on the surface of the window. It only fills the amount of space required for the message and the user's current activity remains visible and interactive. The notification automatically fades in and out, and does not accept interaction events.
Toast notify we can show in different gravity like "TOP", "RIGHT", "LEFT", "BOTTOM".etc.. Below i added code..

import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.Gravity;
import android.widget.Toast;
public class AndroidQAActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast t = Toast.makeText(AndroidQAActivity.this, "Hi Buddy", Toast.LENGTH_LONG);

t.setGravity(Gravity.TOP|Gravity.RIGHT, 0, 0); 
t.show();
Toast t1 = Toast.makeText(AndroidQAActivity.this, "Hi Buddy", Toast.LENGTH_LONG);
t1.setGravity(Gravity.CENTER, 0, 0);
t1.show();
Toast t2 = Toast.makeText(AndroidQAActivity.this, "Hi Buddy", Toast.LENGTH_LONG);
t2.setGravity(Gravity.BOTTOM, 0, 0);
t2.show();
}
}

Thursday, June 28, 2012

Android List Of Preference

Android List Of Preference
Android List Of Preference
1.ListPreference : This preference will store a string into the SharedPreferences. This string will be the value from the  setEntryValues(CharSequence[])
array.
2.EditTextPreference :This preference will store a string into the SharedPreferences.
3.CheckBoxPreference : This preference will store a boolean into the SharedPreferences.
4.RingtonePreference :
5.MultiSelectListPreference
6.DialogPreference
Screen Shot







Activity Code:

import android.os.Bundle;
import android.preference.PreferenceActivity;
public class AndroidQAActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.main);;
}
}
Resource Code   

<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:key="Android"
android:title="Android Preference"
android:summary="List of Version">
<PreferenceCategory android:title="List Preference">
<ListPreference
android:key="Android"
android:title="Android List of Version"
android:summary="Cool List of Version"
android:entries="@array/androidversion"
android:entryValues="@array/androidversion_values"
android:dialogTitle="List of Version"
android:defaultValue="List of Version" />
</PreferenceCategory>
<PreferenceCategory android:title="Edit Preference">
<EditTextPreference
android:key="Android"
android:title="Edit Preference"
android:summary="Edit Text"
/>
</PreferenceCategory>
<PreferenceCategory android:title="RingTone Preference">
<RingtonePreference
android:key="Android"
android:title="RingTone Preference"
android:summary="RingTone Preference"
/>
</PreferenceCategory>
<PreferenceCategory android:title="CheckBox Preference">
<CheckBoxPreference
android:key="1"
android:title="CheckBox Preference"
android:summary="CheckBox Preference"
/>
</PreferenceCategory>
</PreferenceScreen>

String Code 
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="androidversion">
<item>Android 1.6</item>
<item>Android 2.1</item>
<item>Android 2.2</item>
<item>Android 2.3</item>
<item>Android 3.0</item>
<item>Android 4.0.1</item>
</string-array>
<string-array name="androidversion_values">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
</string-array>
</resources>

DOWNLOAD SOURCE CODE

Android EditText TextWatcher Example

Android EditText TextWatcher Example
 TextWatcher
This methods  will be called when the text is changed.
Text Watcher Having Three Events.
1.beforeTextChanged
2.onTextChanged
3.afterTextChanged
  beforeTextChanged   This means that the characters are about to be replaced with some new text. The text        is  uneditable.   Use: when you need to take a look at the old text which is about to change.
 onTextChanged Changes have been made, some characters have just been replaced. The text is uneditable.Use: when you need to see which characters in the text are new.
 afterTextChanged The same as above, except now the text is editable.
    Use: when a you need to see and possibly edit new text.

Problem
EditText maxLength:100 

Ex: when you type the text  in EditText you can see remaining length using TextWatcher.
Solution :

Activity Code 
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class AndroidQAActivity extends Activity implements TextWatcher {
EditText text;
int textCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText)findViewById(R.id.url_field);
text.addTextChangedListener(this);
}
/* TextWatcher Implementation Methods */
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int end) {
textCount = text.getText().length();
setTitle("Message :: "+String.valueOf(textCount)+"/100");
}
public void afterTextChanged(Editable s) {
}
}

Screen Shot:


XMl Code 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/url_field"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:maxLength="100"
android:lines="1" />
</LinearLayout>


Tuesday, June 26, 2012

JAVA Interview Question And Answer

JAVA Interview Question And Answer
 DownLoad  JAVA IQA
-->
Q1. What is the difference between an Abstract class and Interface?
1. Abstract classes may have some executable methods and methods left
unimplemented. Interfaces contain no implementation code.
2. An class can implement any number of interfaces, but subclass at most one abstract class.
3. An abstract class can have nonabstract methods. All methods of an interface are
abstract.
4. An abstract class can have instance variables. An interface cannot.
5. An abstract class can define constructor. An interface cannot.
6. An abstract class can have any visibility: public, protected, private or none
(package). An interface's visibility must be public or none (package).
7. An abstract class inherits from Object and includes methods such as clone() and
equals().
Q2.What are checked and unchecked exceptions?
Java defines two kinds of exceptions :
Checked exceptions : Exceptions that inherit from the Exception class are
checked exceptions. Client code has to handle the checked exceptions thrown by
the API, either in a catch clause or by forwarding it outward with the throws clause.
Examples - SQLException, IOxception.
Unchecked exceptions : RuntimeException also extends from Exception. However,
all of the exceptions that inherit from RuntimeException get special treatment.
There is no requirement for the client code to deal with them, and hence they are
called unchecked exceptions. Example Unchecked exceptions are
NullPointerException, OutOfMemoryError, DivideByZeroException typically,
programming errors.
Q3.What is a user defined exception?
User-defined exceptions may be implemented by
• defining a class to respond to the exception and
• embedding a throw statement in the try block where the exception can occur or
declaring that the method throws the exception (to another method where it is
handled).
The developer can define a new exception by deriving it from the Exception class as follows:
public class MyException extends Exception {
/* class definition of constructors (but NOT the exception handling code) goes here public MyException() {
super();
}
public MyException( String errorMessage ) {
super( errorMessage );
}
}
The throw statement is used to signal the occurance of the exception within a try block. Often, exceptions are instantiated in the same statement in which they are thrown using the
syntax.
throw new MyException("I threw my own exception.")
To handle the exception within the method where it is thrown, a catch statement that handles MyException, must follow the try block. If the developer does not want to handle the exception in the method itself, the method must pass the exception using the syntax:
public myMethodName() throws MyException
Q4.What is the difference between C++ & Java?
Well as Bjarne Stroustrup says "..despite the syntactic similarities, C++ and Java are very different languages. In many ways, Java seems closer to Smalltalk than to C++..". Here are few I discovered:
• Java is multithreaded
• Java has no pointers
• Java has automatic memory management (garbage collection)
• Java is platform independent (Stroustrup may differ by saying "Java is a platform"
• Java has built-in support for comment documentation
• Java has no operator overloading
• Java doesn’t provide multiple inheritance
• There are no destructors in Java
Q5.What is serialization?
Quite simply, object serialization provides a program the ability to read or write a whole object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a byte stream suitable for streaming to some type of network or to a file-system, or more generally, to a transmission medium or storage facility. A seralizable object must implement the Serilizable interface. We use ObjectOutputStream to write this object to a stream and ObjectInputStream to read it from the stream.
Q9.Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA?
Null interfaces act as markers..they just tell the compiler that the objects of this class need to be treated differently..some marker interfaces are : Serializable, Remote, Cloneable
Q6. Is synchronised a modifier?indentifier??what is it??
It's a modifier. Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
Q7.What is singleton class?where is it used?
Singleton is a design pattern meant to provide one and only one instance of an object. Other objects can get a reference to this instance through a static method (class constructor is kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages in memory management, and for Java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or business reasons--for example, we may only want a single instance of a pool of database connections.
Q8.What is a compilation unit?
The smallest unit of source code that can be compiled, i.e. a .java file.
Q13.Is string a wrapper class?
String is a class, but not a wrapper class. Wrapper classes like (Integer) exist for each primitive type. They can be used to convert a primitive data value into an object, and viceversa.
Q9.Why java does not have multiple inheritance?
The Java design team strove to make Java:
• Simple, object oriented, and familiar
• Robust and secure
• Architecture neutral and portable
• High performance
• Interpreted, threaded, and dynamic
The reasons for omitting multiple inheritance from the Java language mostly stem from the "simple, object oriented, and familiar" goal. As a simple language, Java's creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++'s unnecessary complexity (simple).
In the designers' opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritance from the language (just as they cut operator overloading). The designers' extensive C++ experience taught them that multiple inheritance just wasn't worth the headache.
Q10.Why java is not a 100% oops?
Many people say this because Java uses primitive types such as int, char, double. But then all the rest are objects. Confusing question.
Q11.What is a resource bundle?
In its simplest form, a resource bundle is represented by a text file containing keys and a text value for each key.
Q17.What is transient variable?
Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.
Q12.What is Collection API?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
Q13.Is Iterator a Class or Interface? What is its use?
Iterator is an interface which is used to step through the elements of a Collection.
Q14.What is similarities/difference between an Abstract class and Interface?
Differences are as follows:
• Interfaces provide a form of multiple inheritance. A class can extend only one other
class.
• Interfaces are limited to public methods and constants with no implementation.
Abstract classes can have a partial implementation, protected parts, static methods,
etc.
• A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
• Interfaces are slow as it requires extra indirection to to find corresponding method
in in the actual class. Abstract classes are fast.
Similarities:
• Neither Abstract classes or Interface can be instantiated.
Q21.What is a transient variable?
A transient variable is a variable that may not be serialized.
Q22.Which containers use a border Layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout.
Q23.Why do threads block on I/O?
Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed.
Q24.How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
Q25.What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.
Q26. Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.
Q27. What's new with the stop(), suspend() and resume() methods in JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
Q28. Is null a keyword?
The null value is not a keyword.
Q29. What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow the
component to display normally.
Q30. What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout.
Q31. Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.
Q32. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
Q33. What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
Q34. Which characters may be used as the second character
of an identifier, but not as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.
Q35. What is the List interface?
The List interface provides support for ordered collections of objects.
Q36. How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
Q37. What is the Vector class?
The Vector class provides the capability to implement a growable array of objects
Q38. What modifiers may be used with an inner class that is a member of an outer class?
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
Q39. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.
Q40. What is the difference between the >> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.
Q41. Which method of the Component class is used to set the position and size of a component?
setBounds()
Q42. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
Q43. What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.
Q44. Which java.util classes and interfaces support event handling?
The EventObject class and the EventListener interface support event processing.
Q45. Is sizeof a keyword?
The sizeof operator is not a keyword.
Q46. What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
Q47. Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
Q48. What restrictions are placed on the location of a package statement within a source code file?
A package statement must appear as the first line in a source code file (excluding blank lines and comments).
Q49. Can an object's finalize() method be invoked while it is reachable?
An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.
Q50. What is the immediate superclass of the Applet class?
Panel
Q51. What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
Q52 Name three Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.



Q63. What is a task's priority and how is it used in scheduling?
A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.
Q65. When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started.
Q66. Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
Q67. What is the range of the short type?
The range of the short type is -(2^15) to 2^15 - 1.
Q68. What is the range of the char type?
The range of the char type is 0 to 2^16 - 1.
Q71. What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
Q74. What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are
evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
Q78. What is the purpose of the Runtime class?
The
purpose of the Runtime class is to provide access to the Java runtime system.
Q79. How many times may an object's finalize() method be invoked by the garbage collector?
An object's finalize() method may only be invoked once by the garbage collector.
Q80. What is the purpose of the finally clause of a try-catchfinally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
Q84. Can a double value be cast to a byte?
Yes,
a double value can be cast to a byte.
Q85. What is the difference between a break statement and a continue statement?
A
break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.
Q86. What must a class do to implement an interface?
It must provide all of the methods in the interface and identify the interface in its
implements clause.
Q87. What method is invoked to cause an object to begin executing as a separate thread?
The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.
Q88. Name two subclasses of the TextComponent class.
TextField and TextArea






Q92. What is the purpose of the wait(), notify(), and notifyAll() methods?
The
wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods..



Q93. What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.

Tuesday, June 12, 2012

android.os.NetworkOnMainThreadException


android.os.NetworkOnMainThreadException 
i am facing problem, when i am try access weburl using HTTPClient  Android SDK Versiong above 9  i got 
android.os.NetworkOnMainThreadException error.
Below i added solution for this one, you can check it.
Problem:   
06-12 18:21:57.192: W/System.err(19398): android.os.NetworkOnMainThreadException
06-12 18:21:57.202: W/System.err(19398): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
06-12 18:21:57.202: W/System.err(19398): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:74)
06-12 18:21:57.202: W/System.err(19398): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
06-12 18:21:57.212: W/System.err(19398): at libcore.io.IoBridge.connect(IoBridge.java:112)
06-12 18:21:57.212: W/System.err(19398): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
06-12 18:21:57.222: W/System.err(19398): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
06-12 18:21:57.222: W/System.err(19398): at java.net.Socket.connect(Socket.java:842)
Solution :
Activity  onCreate method  add this code.
if (android.os.Build.VERSION.SDK_INT > 9) {

StrictMode.ThreadPolicy policy =

new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy);

}
What is StrictMode?  
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. Keeping disk and network operations off the main thread makes for much smoother, more responsive applications. By keeping your application's main thread responsive
More Check this link




Monday, June 11, 2012

Android:To set an item as selected when the ListView opens

Android:To set an previous selected item as selected when the ListView opens
Problem:
 To set previous selected item as selected when the List View Opens.
Solution:
Make your listview as single choice mode or multible choice mode.
XML Code:
<ListView
              android:id="@+id/_list"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:clickable="true"
              android:choiceMode="singleChoice"
              >
  </ListView>
Activty Code :

listView.setAdapter(new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_single_choice, list_array));

jobList.setItemChecked( here your previous position, true);

Check out this may be help you

Related Posts Plugin for WordPress, Blogger...