Andy
Andy

Reputation: 45

Having issues with ANDROID_ID

I'm trying to get ANDROID_ID working in my appn but I'm getting odd behavior in my emulator and also on hardware.

an extract from my app.

import android.provider.Settings.Secure;

public class RssActivity extends ListActivity {

final String android_id = Secure.getString(getContentResolver(),Secure.ANDROID_ID); 

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d("UUID", android_id);

Now in my emulator the app opens but then seems to freeze and does nothing, I don't even get my "UUID" debug message.

On my phone i just get a "the application has stopped unexpectedly" OS 2.3.3

Any ideas, am i implementing this wrong?

If i remove "final String android_id = Secure.getString(getContentResolver(),Secure.ANDROID_ID);" then the app works fine on both emulator and hardware - so the problem must be located here?

Upvotes: 3

Views: 2284

Answers (2)

Chinmoy Debnath
Chinmoy Debnath

Reputation: 2824

Only declare the variable before onCreate and then get device id on the onCreate. Then Your null pointer exception will be solved.

This happens because of getContentResolver() needs fully initiated Context(Activity).

String android_id; 

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tst);
    android_id = Secure.getString(getContentResolver(),Secure.ANDROID_ID);
    Log.d("UUID", android_id);
}    

Upvotes: 10

Manoj Kumar
Manoj Kumar

Reputation: 1520

Try this:

Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID);

Upvotes: 0

Related Questions