Tuesday, November 15, 2016

Android : Context

Context 

Context = Current Screen

Assuming MainActivity is currently being displayed on the screen it will hold the context.If any other method require context ,  than needs to be passed as an argument as "MainActivity.this" and receiving method receives as (Context c)

Synatx:
Method_name(ParentClass.this); // assuming ParentClass holding the context

public void Method_name(Context c){
}

Eg : 
public class MainActivity extends AppCompatActivity {

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

       DBOperations oDBOperations=new DBOperations(MainActivity.this);
       oDBOperations.get_db_location(MainActivity.this);

    }
}

public class DBOperations {

    SQLiteOpenHelper sql_helper;
    DBOperations(Context context){
        sql_helper=new sqllitehelperclass(context);
    }
 
 public void get_db_location(Context c){
        String dbname = "mydb.db";
        Log.d("db path",c.getDatabasePath(dbname).toString());
    }
}

No comments:

Post a Comment