Some basics doubts in Android Programming

  • Replies:8
Vinoth and Vino
  • Forum posts: 7

Mar 24, 2016, 5:29:00 AM via Website

Helo guys, I've simple doubts in android.Please make me understand. I can't go without knowing this clearly.

1.Why super keyword ?

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

    addListenerOnButton();  

} ` 

Why we're using super.onCreate method in onCreate.. What it'll do ? I don't know the flow of execution too...(As per my knowledge.. First onCreate method will executed with Bundle(Bundle stores the user states) thn it moves to setContentView without executing super.onCreate.... If we've come to home and then when we open the app..then "super.onCreate" will execute with old state... isn't it ?

2.Why we're inheriting some classes ?
As per my knowledge... By way of inheriting we've the properties of parent class(for ex: Activity) so that only we're inheriting the parent class.. isn't it ?

3.Why should I wanna extend Activity ?
As per my knowledge.. If we wanna use activity then we've to extend Activity and override activity lifecycles as per our wish... isn't it ?

4.Why should I wanna extend SQLiteOpenHelper class ?
If we wanna create database then we wanna extend SQLiteOpenHelper class but I studied that SQLiteDatabase method called openOrCreate or similar methods are only used to create databases ? Then why should i wanna extend SQLiteOpenHelper class ????? (As per my knowledge... It's the main thing in sql database..In this "SQLiteOpenHelper" class only contains the sqlite database onCreate lifecycle methods etc.... so we wanna extend this class and then use openOrCreate or similar methods to achieve database creation in onCreate lifecycle... isn't it ?)

5.What is context ? Why we're passing context as parameter in super keyword ?(ex: onCreate lifecycle method)
Context is used to access system related informations ?

6.What's the use of using getters and setters in android ?

 `package com.example.sqlite;  

public class Contact {
int _id;
String _name;
String _phone_number;
public Contact(){ }
public Contact(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}

public Contact(String name, String _phone_number){  
    this._name = name;  
    this._phone_number = _phone_number;  
}  
public int getID(){  
    return this._id;  
}  

public void setID(int id){  
    this._id = id;  
}  

public String getName(){  
    return this._name;  
}  

public void setName(String name){  
    this._name = name;  
}  

public String getPhoneNumber(){  
    return this._phone_number;  
}  

public void setPhoneNumber(String phone_number){  
    this._phone_number = phone_number;  
}  

} `

7.What's the use of passing context in parameter ? and why we're passing DatabaseName,Database version ? In which time this super method executed ? then who will receive this as arguments ?

public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
} `

Source : javatpoint

8.Here,How I achieved "db.execSQL" ? I'm just passing SQLite as argument only know ? Then how can i use db.execSQL in this onCreeate method ? and my doubt is I'm passing onCreate(SQLiteDatabase db) as argument...then who'll receive this argument ????????

public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
} `

These are my basic doubts.. I can't go to anyother topic without knowing these things... I think i didn't learn all basics clearly..Please help me out..... ;'( ;'( Thank you so much in advanced :)

Reply
itterN
  • Forum posts: 12

Mar 24, 2016, 6:19:51 AM via Website

  1. The super keyword here is used to invoke the parent class's onCreate method. What the ancestor classes will do in that method is not explicitly defined - a FragmentActivity parent, for example, might use certain life-cycle events like onCreate, onStart, and so on to initialize saved fragments (such as a DialogFragment) as the app resumes.

    Your example is unclear - if it helps, given a MyActivity class that extends Activity, this is what will typically take place:

    MyActivity::onCreate start
     Activity::onCreate start
      (Any other ancestors)...
     Activity::onCreate end
    MyActivity::onCreate end
    
    MyActivity::onStart start
     Activity::onStart start
      (Any other ancestors)...
     Activity::onStart end 
    MyActivity::onStart end 
    
    (Other life-cycle events)...  
    
  2. I don't know what you're asking here - please clarify.

  3. Again, unclear - please clarify.

  4. The SQLiteOpenHelper class is provided for convenience - to make your life easier. Take a look at the source code for that class if you'd like to know what it does. If this doesn't answer your question then please clarify.

  5. The context object is passed to various methods in the framework because they perform options that require it. If you're looking for a broad discription of what a context object was designed to represent, take a look at the source code - from the documentaion for that class:

    Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

  6. That's a very broad question and it certainly isn't android-specific - try googling "java getter setter" or similar. Common examples: you might want to modify the getters/setters in the future (such as to preseve an invariant), you might want to create another class that extends Contact in the future and may need to override the default getter/setter implementations, and so.

  7. I'm not sure what you're asking here. SQLiteOpenHelper creates the database (the SQLiteOpenHelper object db) in response to some event (when you request access to the database I would imagine) then invoke's the onCreate method you wrote to initialize the database. If that doesn't answer your question please clarify.

— modified on Mar 24, 2016, 6:21:50 AM

Vinoth and Vino

Reply
Vinoth and Vino
  • Forum posts: 7

Mar 24, 2016, 7:00:57 AM via Website

Thank you soooooooooooooooooooooooooooooooo much bro :) But still I didn't get it well

  1. Please make me understand clearly about this " super.onCreate(savedInstanceState)... I know super keyword is used to call parent methods or any other

    protected void onCreate(Bundle savedInstanceState) { //This is our(MyActivity not Android's Activity class) onCreate Lifecycle method

    super.onCreate(savedInstanceState); // Now in this method.. It calls which onCreate method ? "protected void onCreate(Bundle savedInstanceState) " or "android's Activity onCreate Method ?

    setContentView(R.layout.activity_main);
    addListenerOnButton();
    } `

2.Why we're inheriting some classes ?
As per my knowledge... By way of inheriting we've the properties of parent class(for ex: Activity) so that only we're inheriting the parent class.. isn't it ?
for ex :

        public class MyActivity extends SQLiteOpenHelper{
                           ..........
  }

   or 

  public class MyActivity extends PreferenceActivity{
                           ..........
  }

3.Why should I wanna inherit Activity ?
As per my knowledge.. If we wanna use activity then we've to extend Activity and override activity lifecycles as per our wish... isn't it ?

for ex :

        public class MyActivity extends Activity{
                           ..........
  }

4.What's the difference between SQLiteOpenHelper and SQLiteDatabase ?

    As per my knowledge....We wanna use  SQLiteOpenHelper before creating database.....Databases are created by SQLiteDatabase methods... isn't it ?

7.What's the use of passing context in parameter ? and why we're passing DatabaseName,Database version ? In which time this super method executed ? then who will receive this as arguments ?

public DatabaseHandler(Context context) { //Why we're passing context object here ? For which method we're passing this context ? Which method will accept the context ?

super(context, DATABASE_NAME, null, DATABASE_VERSION); //Why we're passing context,DATABASE_NAME,null,DATABASE_VERSION here ? For which method we're passing these things ? Which method will accept these all?

//3rd argument to be passed is CursorFactory instance
} `

8.Please explain the flow of execution ?

public void onCreate(SQLiteDatabase db) { // What we're doing in parameter ? Are we creating objects ? or passing parameters to interested methods ?

String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
} `

Again,Thanks a lot bro :) I know You're spending much time to answer this......Thanks it'll clear my doubts...Please help me....and Do you have any blogs ? Are you in Twitter ? or some other social n/w sites ? I want your help ;'(

Reply
itterN
  • Forum posts: 12

Mar 24, 2016, 7:57:59 AM via Website

  1. Perhaps a simple example would be more effective here:

     class MyActivity1 extends Activity {
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             Log.v("MyActivity1", "onCreate start");
             super.onCreate(savedInstanceState); // call #1
             Log.v("MyActivity1", "onCreate end");
         }
     }
    
     class MyActivity2 extends MyActivity1 {
         @Override
         protected void onCreate(Bundle savedInstanceState) {
             Log.v("MyActivity2", "onCreate start");
             super.onCreate(savedInstanceState); // call #2
             Log.v("MyActivity2", "onCreate end");
         }
     }
    

    If you were to create an activity using MyActivity2 then you would see the following:

     MyActivity2 - onCreate start
     MyActivity1 - onCreate start
     MyActivity1 - onCreate end
     MyActivity2 - onCreate end
    

    that is, call #2 would invoke MyActivity1's onCreate method and call #1 would invoke Activity's onCreate method.

  2. I'm still not sure what you're asking, sorry. Are you asking why MyActivity (I'm assuming you're using this class as an activity) can't extend SQLiteOpenHelper? If so, MyActivity extends Activity (or some class derived from Activity, like PrefrenceActivity) because the framework requires it. Consider your MyActivity class, for example - somewhere in your manifest you'll having something along the lines of:

    <activity android:name=".MyActivity">
        ...
    </activity>
    

    The android framework will try to find a class by the name of "MyActivity" in your project and use it to create an instance of your class which it will then treat as an Activity object (I'm assuming reflection is used here). If MyActivity instead extended SQLiteOpenHelper then some code in the framework (something you didn't write) would likely throw an exception when attempting to cast the MyActivity object to Activity, something like:

    ...
    Object object = ... // creates an instance of MyActivity
    Activity activity = (Activity)object; // would throw an exception if MyActivity did not extend Activity
    
  3. Does my response in 2 answer your question? If not, please clarify.

  4. SQLiteOpenHelper is a convenience class - it takes care of certain calls to SQLiteDatabase for you. For example, here's a portion of a method from SQLiteOpenHelper that creates a database using calls to SQLiteDatabase:

    private SQLiteDatabase getDatabaseLocked(boolean writable) {
        // ...
        if (db != null) {
            // ...
        } else if (mName == null) {
            // ...
        } else {
            try {
                if (DEBUG_STRICT_READONLY && !writable) {
                    final String path = mContext.getDatabasePath(mName).getPath();
                    db = SQLiteDatabase.openDatabase(path, mFactory,
                        SQLiteDatabase.OPEN_READONLY, mErrorHandler);
                } else {
                    db = mContext.openOrCreateDatabase(mName, mEnableWriteAheadLogging ?
                        Context.MODE_ENABLE_WRITE_AHEAD_LOGGING : 0,
                        mFactory, mErrorHandler);
                }
            } catch (SQLiteException ex) {
                // ...
            }
        }
        //...
    }
    
  5. In the code you've posted there SQLiteOpenHelper's constructor will recieve the context object. It stores the database name/version so it can use those when it needs to construct the database.

    public class DatabaseHandler extends SQLiteOpenHelper {
        public StorageDbHelper (Context context) {
            // this calls SQLiteOpenHelper's constructor
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    }
    
  6. From SQLiteOpenHelper's source code:

    /**
     * Called when the database is created for the first time. This is where the
     * creation of tables and the initial population of the tables should happen.
     *
     * @param db The database.
     */
    public abstract void onCreate(SQLiteDatabase db);
    

    In other words onCreate is invoked when SQLiteOpenHelper creates the database. Typically at that point you initialize any tables you want to use in your database; that's what you're doing in the SQL command you're executing at that point:

    public class DatabaseHandler extends SQLiteOpenHelper {
        public StorageDbHelper (Context context) {
            // this calls SQLiteOpenHelper's constructor
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_PH_NO + " TEXT" + ")";
    
            // this command creates the table TABLE_CONTACTS in db (that is,
            // the DATABASE_NAME database SQLiteOpenHelper created for you)
            db.execSQL(CREATE_CONTACTS_TABLE);
        }
    }
    

— modified on Mar 24, 2016, 8:01:05 AM

Vinoth and Vino

Reply
Vinoth and Vino
  • Forum posts: 7

Mar 24, 2016, 8:11:34 AM via Website

Hey developer!!! You explained very well...Thank a ton for your effort... :)

Reply
itterN
  • Forum posts: 12

Mar 24, 2016, 8:14:06 AM via Website

No problem, I'm glad it helped :)

Reply
Vinoth and Vino
  • Forum posts: 7

Mar 24, 2016, 8:17:41 AM via Website

Shall I ask you any doubts about Android at anytime ?

Reply
itterN
  • Forum posts: 12

Mar 24, 2016, 8:28:11 AM via Website

Feel free - I can't promise I'll respond, however I'm sure someone here will be able to help you :)

Reply
Vinoth and Vino
  • Forum posts: 7

Mar 24, 2016, 8:33:05 AM via Website

Anyway Tnx :)

Reply