ModelLayer(Context appContext) Singleton Constructor in Android...what does the following code with comments exactly do? -


in model layer of android project learning big nerd ranch android programming book, there specific singleton - model layer class, goes this:

 public class modellayerclass            {  private static modellayerclass class_instance;   //its clear singleton here !   private context context_instance;   private modellayerclass(context appcontext)  //why parameter being passed?  {  context_instance = appcontext;             //how helps  here ?      }  public static modellayerclass get(context c)  {  if(class_instance=null)   {      class_instance = new modellayerclass(c.getapplicationcontext());    } return class_instance;  } }  

when went through book, saying that, common practice in android have context parameter allows singleton "start activities", access project resources, find apps private storage , more.....doesnt classes in our project have default access of these (except starting activities). can direct me proper online resources or give me explanation this...thnx :)

from activity, have access within application, through use of context. here's android documentation context.

for example, when write

startactivity(new intent(mainactivity.this, newactivity.class)); 

you have access startactivity method because activity class extends activity. if want start activity singleton or class or that, need have context start activity.

for example, if wanted start same activity above, outside of activity class, must have context:

context.startactivity(new intent(context, newactivity.class)); 

same goes number of other things might want outside of activity class.

accessing resources:

bitmap imagefromres = bitmapfactory.decoderesource(context.getresources(), r.drawable.image); 

creating new android views:

imageview iv = new imageview(context); 

basically, context "catch-all" parameter allows non-android classes still utilize methods use in android classes (like activity, service, dialog, etc).


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -