Pages

Friday, 24 August 2012

Detecting Android Device on Ubuntu(Linux) 0r ????????? No permission for Device

Hi,  
   To test our Android Application we need to use Device(Mobile Handset, Tablet or Emulator).
It's Easy to run Android Application on Emulator. But some time we need to run or test the Application on actual device. Before testing application we need to check whether device drive properly install or not.

When u connect device on Ubuntu. Many time it show one message on terminal( Command prompt),  

?????????? No permission for Device.   

At this time you need to kill  all adb using   write following on terminal. do not give any path before this.

>>>>killall adb    

Then you need to start your server or adb again.... But before that you need to close your eclipse.  then type on terminal...

>>>>Sudo '/your adb path here/' start-server

your server will start and showing starting message on terminal.

Then check whether testing device is visible or not on terminal. Use following command for that...

>>>> '/your adb path here/' devices

it show following message  

List of attached devices
Smart Tab 1.  

you will also find your device in Eclipse...
  open device in Eclipse... it will show the devices which are attached including Emulator

Enjoy...
Save Tree save world

Sunday, 15 April 2012

Button-Android Fundamental-part-1

Button:-
               This is first part of Android fundamental for new Android user.In this part we study about the Button.

Create Button:-
                           To use Button, we need to create button in sample.xml file.we can create button by two way.
1.Using .xml file
2.By java code

1.Sample.xml file:-
                              You need to drag and drop button from form widget. or you manually write code for button in sample.xml file.
Here is code for Button.

<Button 
        android:id="@+id/button1"
        android:layout_width="106dp"
        android:layout_height="90dp"
        android:textSize="15px"
        android:text="Home"
        android:drawableTop="@drawable/faq"
        android:textColor="@color/myWhiteColor"
        android:background="@drawable/examguide_btnmain"
        android:gravity="center" android:layout_marginTop="25dp"></Button>

Property Description:- 
                            1.Android-id:-  You need to set id for button for further use in .java file.we need id of any widget to allocate some work for further coding.   
               Button Home=(Button)findViewById(R.id.button1); 
      Here we assign id to Home button.
                           2.Android:text:- Text which we require to show on Button. we assign "Home" text to Button.
                           3.Android:layout_height/Android:layout_width:-Here we decide height and width of Button.
                           4.android:drawableTop:- We can assign any image to button on respective side. Like top, Bottom, Right, Left.
                           5.android:textColor:- Using this property we can assign color to Button-text.
                           6.android:gravity:- Gravity are use to set gravity for text.you can choose any gravity as per your need.
                           7.android:layout_marginTop:- We can allocate margin in left, right, top and at bottom.
                           8.android:background:-  We use this property to hide button view. using this property we able to show only text and image of button but you need to use appropriate color which match with background.

2. By Programatically:-
                                       Here is sample code for add Button in java program.

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 

          //Create instance of button
          Button Home = new Button(this);
          Home .setText("Home");

         //we use linear layout to add button.
        LinearLayout layout = (LinearLayout ) View.inflate(this, R.layout.sample, null);
        //add the button to the view
       layout  .addView(Home );
       //set the layout using the inflated view
        setContentView(layout);
  
   }

3. Use of Button:-  
                            We use button for do some work after click on it.
 we use Onclick() method for that. Here is sample code which jump from one activity to second activity.

Home.setOnClickListener(new View.OnClickListener()
        {
          
            @Override
            public void onClick(View v)
            {

                 Intent intent = new Intent(getApplication(),Activity2.class);
                 startActivity(intent);

                 //Uri uri = Uri.parse("http://www.mpsc.gov.in/advertisements.jsp?head=1&status=1");
                // Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                // startActivity(intent);
 
            }
        });


Commented line are use to jump on specific web page.

4.Image:-
                    Here is image which use all above properties.
 


                  
         

Enjoy..........

SAVE TREE SAVE LIFE................
                           


 

Monday, 2 April 2012

Resources NotFoundException

Error:-
         I got following error while Debugging OF my Application.
 
          Uncaught handler: thread main exiting due to uncaught exception
android.content.res.Resources$NotFoundException: String resource ID #0x1


I got this error when i am trying to fetch data from database and try to assign this data to EditText.

I had one integer return type method which return NoOfQuestion  which i want to show in EditText like this..

txtNoQuestion.setText((owq.getNoOfQuestion()));        //Incorrect        txtNoMarks.setText((owq.getMarks()));                        //Incorrect

Then i use following method and it solve my Problem.

txtNoQuestion.setText(Integer.toString(owq.getNoOfQuestion()));   //Correct                        txtNoMarks.setText(Integer.toString(owq.getMarks()));                 //correct                                



Enjoy......

SAVE TREE SAVE LIFE 

Sunday, 1 April 2012

Single Time Login Page.

Introduction:-
                     Single time Login means Whenever we release Android Application in Android Market we 
need  allow login process to user only for single time. User enter his information and get login. When user open application second time then application directly jump on Main page instead of login page.
              For this process  we need to store some flag or value into database for further matching. For this, 

Process:-
                We create one static string variable in any activity which user must visit after login (Page which open after login page).
Write this code in onCreate () method of MainActivity.java
  public static final String PREFS_NAME = "MyPrefsFile";

Then we need to create object of SharedPreference in MainActivity.java which can retrieve and modify value.Only one instance of the  SharedPreference object is returned to any callers for the same name.

SharedPreferences settings = getSharedPreferences(MainActivity.PREFS_NAME, 0);

getSharedPreferences():- Retrieve and hold the contents of the preferences file ''MainActivity.PREFS_NAME".

Parameter:-
1. name(MainActivity.PREFS_NAME):- Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).

2. mode(0):- MODE_WORLD_WRITEABLE to control permissions.

Then we need to create instance of  Editor.

 SharedPreferences.Editor editor = settings.edit();

Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
We set Boolean value to check user enter in this activity or not.
Following code for set value.

        //Set "ifLoggedIn" to true
          editor.putBoolean("hasLoggedIn", true);

          // Commit the edits!
          editor.commit();



Then we need to check this value in onCreate() method of LoginActivity.java whether user logged in or not.

SharedPreferences settings = getSharedPreferences(ExamGuideActivity.PREFS_NAME, 0);
        //Get "hasLoggedIn" value. If the value doesn't exist yet false is returned
        boolean hasLoggedIn = settings.getBoolean("hasLoggedIn", false);

        if(hasLoggedIn)
        {
             startActivity(new Intent(this, FirstActivity.class ));
        }
        else
        {
             startActivity(new Intent(this, LoginActivity.class ));
        }

Enjoy......

SAVE TREE SAVE LIFE 

                                                               

Monday, 12 March 2012

SQLite

Introduction:-
                      SQLite is a popular choice for local/client storage on web browsers. It has many bindings to programming languages.SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. In addition it requires only little memory at runtime (approx. 250 KByte).

In Android:-
                    
SQLite is available on every Android device. Using an SQLite database in Android does not require any database setup or administration.
You only have to define the SQL statements for creating and updating the database. Afterwards the database is automatically managed for you by the Android platform.

Android Architecture :-
 1.SQLiteOpenHelper:-
                                      SqLiteOpenHelper are use to database creation and managing database version.
In SQLiteOpenHelper you implement onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and and optionally onOpen(SQLiteDatabase) method.

-onCreate(SQLiteDatabase db):-
                                            Called when the database is created for the first time.
                                 @Override
                                  public void onCreate(SQLiteDatabase db)
                                 {
                                             db.execSQL(DATABASE_CREATE);
                                  }

- onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion):-
                                             Called when the database needs to be upgraded.
                                    @Override
                                     public void onUpgrade(SQLiteDatabase db, int oldVersion,  int newVersion)
                                     {
                                             Log.w(TAG, "Upgrading database from version " + oldVersion
                                              + " to "
                                              + newVersion + ", which will destroy all old data");
                                               db.execSQL("DROP TABLE IF EXISTS titles");
                                              onCreate(db);
                                     }

- onOpen(SQLiteDatabase db):-
                                            Called when the database has been opened.
                                    
 2.SQLiteDatabase:-
                                      SQLiteDatabase is the base class for working with a SQLite database in Android. SQLiteDatabase has methods to create, delete, execute SQL commands, and perform other common database management tasks.

         3.Package:-
                           android.database.sqlite contain all related package of SQLite.

Creating Database:-
                                Following code show how to create database.Suppose it's a employee data including name and salary.                             
     private static final int DATABASE_VERSION = 1;
     private static final String DATABASE_CREATE =
                   "create table salary (_id integer primary key autoincrement, "
                   + "name text Not Null, salary text Not Null);";

Inserting Data in Database:-
                                           Using following function you can insert data into database.

                                public long insertsalary(String name, String salary)
                                {
                                               ContentValues initialValues = new ContentValues();
                                                initialValues.put(KEY_NAME, name);
                                                initialValues.put(KEY_SALARY, salary);
                                                return db.insert(DATABASE_TABLE, null, initialValues);
                                 }

Retrieving Data:- 
                     1. One Record:- Fetch one record at a time.
                                         public Cursor getdetails(String id) throws SQLException
                                        {
                                                        Cursor mCursor =
                                                                    db.query(true, DATABASE_TABLE, new String[]
                                                                     {
                                                                             KEY_ROWID,
                                                                              KEY_NAME,
                                                                             KEY_SALARY,
                                                                       },
                                                                     KEY_ROWID + "=" + id, null, null, null, null, null);
                                                       if (mCursor != null)
                                                      {
                                                                    mCursor.moveToFirst();
                                                       }
                                                      return mCursor;
                                       }

                 2. AllRecord:- Fetch all record..
                                   public Cursor getAllDetails()
                                  {
                                        return db.query(DATABASE_TABLE, new String[]
                                         {
                                                  KEY_ROWID,
                                                  KEY_NAME,
                                                  KEY_SALARY,
                                         },
                                             null,null,null,null,null);
                                   }
How to find Database:-
                                   SQLite database is located at DDMS. 
Select DDMS- Select FileBrowser\Data\Data\Your Package Name\Database\"database_Name.db".

SQLiteBrowser:-
                                 You find Database file but how to check the content of database whether insert correctly or not?. SQLite Browser is use to check the database content. You need to download it from following link.
Download SQlite Browser from here  

Delete One Record:-
                                 It's very easy to delete single record from database. You need only call the Delete() from your Activity and pass appropriate value(integer or string). You need to apply different query for integer and String.

                                1.Integer Parameter.
                                  public void delete(int value)
                                 {
                                        try{           
                                                   SQLiteDatabase db= this.getWritableDatabase();
                                                   db.delete(TABLE_NAME, COLUMN_ID+"="+value, null);

                                             }
                                             catch(Exception e){
                                             e.printStackTrace();
                                             }
                                  }    

        
                               2.String Parameter.
                                public void deleteBName(String keyword)
                               {
                                    try
                                    {
                                        SQLiteDatabase db=this.getWritableDatabase();
                          db.delete(TABLE_NAME,COLUMN1+"=?", new String [] {String.valueOf(keyword)});
                                    }
                                   catch(Exception e)
                                   {
                                           e.printStackTrace();
                                   }          
                             }

                   
Delete all Record:-
                               Following function delete all record.
                                public void deleteAll(){
                                try{           
                                       SQLiteDatabase db= this.getWritableDatabase();
                                       db.delete(TABLE_NAME, null, null);
                                     }catch(Exception e){
                                    e.printStackTrace();
                                     }
                               }


Thank you!

Save Tree Save Life.....

                                                              

Sunday, 11 March 2012

Telnet with Emulater.

Introduction:-
                     Telnet is a network protocol used on the Internet or LAN to provide a bidirectional interactive text-oriented communications facility using a virtual terminal connection. By default telnet is not enable in window, we need to enable it.

Enable Setting:-
                           Click on Start - Control Panel - Program - Then click on "turn windows feature ON/OFF"
-Enable Telnet.   Now it's available for use.

With Emulator:-
                       Open command prompt- "Path to your sdks"\ telnet localhost 5554 then press Enter.
                       5554:- Number of emulator which you want to connect with telnet.
                       Path:- C:\users\san\android-sdks\platform-tools (Generally, it may different in your case).

Example:- C:\users\san\android-sdks\platform-tools\telent loaclhost 5554
       After clicking enter following screen will open.(should emulator open before enter this syntax).

Help provide you other command.

Passing value from Telnet to Emulator:-
                                                       "geo" command are use to send Longitude and latitude to emulator.

Syntax:- geo fix longitude latitude
Example:- geo fix 76.57492 18.457

this value check with emulator value which user fix on map.

Start/Stop AVD:-
                         1.  using Telnet you can start/stop avd(android virtual device).

                         Example:- avd start 5556
                                         avd start 5558

                         2. Load/delete snapshot of avd.

                         Example:- avd snapshot save 5554
                                         avd snapshot del 5554

Manage Network:-
                                Example:- network status
                                                network capture start

You can also able to do lot of work which Telnet offer. Go and play on Telnet.




Thank you....
Save Tree Save Life


            
            

Architecture of Android

Introduction:-
Android is a software platform for mobile devices based n Linux operating system and developed by
 Google and Open Handset Alliance.

Android Features:-
                     - Android architecture enabling developers to reuse and replacement of existing
 component .  
                     -provide SQLite for data storage .                                                                                         
                     -Great media support(JPEG,GIF,PNG,AMR,MP3,MPEG4) .                                               
                     -Network support(Bluetooth,Wi-Fi,EDGE,3G) .                                                                    
                     -Hardware support(Camera,GPS,Compass,Accelerometer).
                     -Powerful SDK                                                  
   

Architecture:-  
                     The following diagram shows Architecture of Android.


Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.
Android allow developers to make a powerful and innovative application.


Application Framework:-
                    Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language.

Linux Kernel:-
                           Android relies on Linux version 2.6.

 
                       - Core System Services:-
                                  -Security Management.
                                  -Process Management.
                                  -Memory Management.
                                  -Driver Model.
                                  -Network Stack

 Libraries:-
                 -Android include a set of C/C++ Libraries.        
                                                                         

                 -Some other are.
                       -System C Library.
                       -Media Libraries.
                       -SGL.
                       -3D Libraries.
                       -FreeType.
                       -SQLite.


Thank you....

Save Tree Save Life

String Tokenizer


String Tokenizer:-

Using StringTokenizer you can easily Split String into Tokens.
We can use StringTokenizer using following method;-
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)  
 
Here is simple Example.

 StringTokenizer strTo = new StringTokenizer("x-y-z", "-");
 while (st.hasMoreTokens()) 
 {
     System.out.println(st.nextToken());
 }
Another way:-
 for (String token : "x-y-z".split("-")) 
 {
     System.out.println(token);
 }

Simple java Example:-

public class Test {
public static void main(String[] args) {
    String str="this is=android{welcome}";
    StringTokenizer st = new StringTokenizer(str,"={}");

    System.out.println("---- Split by sp");
    while (st.hasMoreElements()) {
        String profile=st.nextElement().toString();
        String name=st.nextElement().toString();
        System.out.println("profile="+ profile +"name="+ name);
    }

    System.out.println("---- Split by comma ',' ------");
    StringTokenizer st2 = new StringTokenizer(str, ",");

    while (st2.hasMoreElements())
    {
        System.out.println(st2.nextElement());
    }
   
}
}
o/p:-
---- Split by sp
profile=this,is
name=android
other=welcome

---- Split by comma ',' ------
this
is=android{welcome}
Explanation:-

1> public int countTokens ()

Returns the number of unprocessed tokens remaining in the string.
Returns:-
number of tokens that can be retreived before an Exception will result from a call to nextToken().

2>public boolean hasMoreElements ()

Returns
  • true if unprocessed tokens remain.

3>public boolean hasMoreTokens ()

Returns
  • true if unprocessed tokens remain.

4>public Object nextElement ()

Returns the next token in the string as an Object. This method is implemented in order to satisfy the Enumeration interface.
Returns:-
next token in the string as an Object
Throws:-
NoSuchElementExceptionif no tokens remain.

5>public String nextToken (string delims)


Returns the next token in the string as a String. The delimiters used are changed to the specified delimiters.
Parameters:-
delims the new delimiters to use.
Returns
  • next token in the string as a String.
Throws
NoSuchElementExceptionif no tokens remain. 






























Thank you.. Suggestion Appreciated..