Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8630123
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T08:59:02+00:00 2026-06-12T08:59:02+00:00

I am new to android programming and ‘ve not thoroughly studied java before .

  • 0

I am new to android programming and ‘ve not thoroughly studied java before . I am really confused on how to use synchronized to ensure thread safety on static variables :

I usually create a class named Utils which has some static functions which are most of the time needed by all my other classes. Is this the correct way of keeping repetitive code out of my classes.

I always suffer from a problem with using Databases. When I create sqliteHelper class for certain Database and try to manage that database from say an Activity and a Background service , I usually get
into trouble. If I use local objects of helper class , I am maximum prone to getting into deadlocking of database when both the helper objects try to acquire write lock together.

For getting out of this trouble , I create a static instance of the helper class in my utils class. Now for performing any operation on database my activity and my service do the following thing :

   public class Utils{
          public static MDatabaseHelper mHelper;
          public static void instantiateHelper(Context context){
          if(mHelper==null)
                mHelper=new MDatabaseHelper(context);

           }
    } 



    public class mActivity extends Activity{
     public void insert some item in database(final Item item)   // this method is called in the Activity at some time
     (new Thread(){
         @Override public void run(){
         Utils.instantiateHelper(getBaseContext());
         mHelper.insertItem(item); }
        }).start();
     }




 public class mService extends Service{
         public void insert some item in database(final Item item)    // this method is called in the service at some time
          (new Thread(){
           @Override public void run{
             Utils.instantiateHelper(getBaseContext());
             mHelper.insertItem(item); }
        }).start();
     }

Now what if both the service and the activity try to insert the item together. I oftentimes get into this situation and an error occurs .
To avoid this I use this workaround :

I put the insert operation in a try block and on failure I wait for random time and try again

    public void insertSomeItemInDatabase(final Item item)
     (new Thread(){
          @Override public void run(){
              int i=0;
              Random rand=new Random();
                 while(true){
                  if(i>10)
                    return;
                  try{ 
                     Utils.instantiateHelper(getBaseContext());
                     mHelper.insertItem(item);
                     break;
                     }catch(Exception e){
                      i++;
                           try{
                              Thread.sleep(rand.nextInt(1000));
                               }catch(Exception e){}
                      }

                      }
          } 
          }
        }).start();
     }

I know this is the Worst method of synchronizing but since I am so new to java can any one please explain how to use synchronized in this Scenario .

Thank You

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T08:59:03+00:00Added an answer on June 12, 2026 at 8:59 am

    I think all your need is to create Application Class

    [1] All those variables you have taken in Util, which are used in about all other class, can be taken in this Application class. So these variables will be available to all other classes.

    [2] Create Singelton instance of Appliction class. Just Google about it.

    [3] Also create Singleton of DataBaseHelper(if possible and can apply), so, single instance helps you every where.


    Application Class is Global class in android, so you can use it to store and access all Global-Data. e.g. :

    public class AppData extends Application {
    
        public static AppData appData;
    
        public int currentUserId; // etc.
    
        //Const.
        public AppData() {
            appData = this;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            loginPreferences = getSharedPreferences(
                SPF_NAME, 0);
    
            pathToSDCard = Environment.getExternalStorageDirectory().getAbsolutePath();
            System.out.println("Path : " + pathToSDCard);
           //etc.
        }
    
     //    MOST IMP  FOR GETTIN SINGELTON INSTANCE     <<<---<<<---<<<---
        public static AppData getAppData() {
            return appData;
        }
    }
    

    HOW TO USE IT, SEE THIS

    class ABC extends Activity {
        AppData appData;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.xyz);
    
            appData = AppData.getAppData();
            ...........
            ...........
    
            appData.VARIABLE_NAME...
        }
    }
    

    One thing more. In AndroidMenifest.xml

        ...
        ...
    <application             //   In Application Tag
            android:name="PACKAGE_NAME.AppData"  //  <<  Add here class name in which you have extended Application
            android:icon="@drawable/ic_launcher"
        ...
        ...
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to Android programming and could really use some help with a program
I am new to Android programming, but not to programming in general or Java.
New to android programming. Getting Following error. 04-07 14:49:05.452: ERROR/AndroidRuntime(1566): FATAL EXCEPTION: main java.lang.OutOfMemoryError
I'm new to Android programming however I do have some Java experience. What I
I am really new in android programming. My question is how does RatingBar actually
I am new to android programming and trying to use webservice in this sample
I'm new to android programming. How do you use android:onClick? Where do I put
I am rather new to Android programming and Java in general (like… one week
I am new to Android and Java Programming and I want to ask if
I'm completely new to Eclipse/Java/Android programming, so this might sound like a dumb question,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.