Cannot Resolve Method getContext() in Android - android

I am trying to implement GCM Push notification and try to get Android emulator id, and add the following code, but it shows me the following error. I cam relatively new on this platform.
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String android_id= Settings.Secure.getString(getContext().getContentResolver(), Settings.Secure.ANDROID_ID);
}

getContext() method available in View class. Use MainActivity.this to access getContentResolver method:
String android_id= Settings.Secure.getString(MainActivity.this.getContentResolver(),
Settings.Secure.ANDROID_ID)

Hey here is the solution for your question:-
You are using activity so You don't need to use getcontext() or this
Just use below line of code to get you the string:-
String string =Settings.Secure.getString( getContentResolver(),Settings.Secure.ANDROID_ID);

You can use this
String android_id= Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);

Related

Robolectric: how to test class which use application instance inside?

I want to test a fragment UserConnectFragment which contains a variable PlateformConnect. This class has a method to initialise Facebook SDK:
#Override
public void create() {
FacebookSdk.sdkInitialize(MyApplication.getInstance().getApplicationContext());
}
I extended Android application with MyApplication class.
In UserConnectFragment, I use PlateformConnect like that:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Must be done before the content view assignement!
PlateformConnect.getInstance().create();
...
In my Robolectric class test:
#Before
public void setUp() throws Exception {
// Create basic activity, and add fragment
mActivity = Robolectric.buildActivity(FragmentActivity.class).create().start().resume().get();
mUserConnectFragment = new UserConnectFragment();
addMapFragment(mActivity, mUserConnectFragment);
//mLoginButton = (Button) mActivity.findViewById(R.id.facebook_button);
}
There is a crash when this test runs:
java.lang.NullPointerException
at com.xxx.yyyy.ui.intro.UserConnectFragment.onViewCreated(UserConnectFragment.java:77)
And this error appears because I use:
MyApplication.getInstance().getApplicationContext()
... and getInstance() returns null.
In my application I use MyApplication.getInstance() in a lot of class, so how can I do to test with Robolectric ??
Thanks guys!
I found the solution: just add #Config(xxx) to set the Application class name.
#RunWith(RobolectricTestRunner.class)
#Config(application = MyApplication.class)
public class UserConnectFragmentTest {
...
More details here: http://robolectric.org/custom-test-runner/
ApplicationProvider.getApplicationContext() worked for me.

Telephony manager in Application class

When I try to use telephony manager to retrieve the phone number from an Activity class, I am able to do it successfully. But I will be using the phone number in multiple places of the app, therefore I shifted the phone number to be a static field in my application class.
public class FourApplication extends Application {
static String phonenumber ;
#Override
public void onCreate() {
super.onCreate();
ParseObject.registerSubclass(Post.class);
// Add your initialization code here
Parse.initialize(this, "**********", "*********");
ParseACL defaultACL = new ParseACL();
// If you would like all objects to be private by default, remove this
// line.
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
phonenumber = getPhoneNumber();
}
public String getPhoneNumber()
{
TelephonyManager tMgr =(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number(); ;
Log.i("mPhoneNumber : ", mPhoneNumber);
return mPhoneNumber;
}
}
What is the mistake I am making here? I read through a few Context related questions and threads, Not able to figure out what's going wrong in my code as I am noob here.
Edit : My question is, When I move the telephony manager part to the application class, it doesn't return a phone number. Why is that?
#55597
Please use the following piece of code.You got your problem
TelephonyManager tMgr =(TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
You are not passing the correct context of Activity for TelephonyManager, So that its return null.

Why can't I make the ArrayList static?

I have the following code.
public class Start extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
ArrayList<String> aPlayerList = getIntent().getStringArrayListExtra("playerList");
static ArrayList<Integer> aScores = getIntent().getIntegerArrayListExtra("scores");
...
I get an error when trying to make the ArrayList<Integer> aScores static: Non-static method getIntent() cannot be referenced from a static context , and I don't know how to fix this.
If it helps, this is how the intent was passed:
Bundle bund = new Bundle();
bund.putStringArrayList("playerList", playerList);
bund.putIntegerArrayList("scores", scores);
Intent intent = new Intent(Players.this, Start.class);
intent.putExtras(bund);
startActivity(intent);
Any help would be appreciated, and if you could add the code that would fix it that would be great. Thanks,
Because your syntax is wrong.
You can't make a variable inside a method static what would be the use of this? Static means that the field is related to the class so you can access it without any reference (ClassName.staticField).
Variables inside methods are related to the method, so you can't access them outside it so how static could be used here?
Are you sure you don't get confused with final? Which is a valid here.
To resolve your problem, you just need to make static ArrayList<Integer> aScores as field of the class so you can access it anywhere in your code. Then edit your onCreate method to this
aScores = getIntent().getIntegerArrayListExtra("scores");
so it will save the array list inside aScores field.
That is because getIntent() is a non static method and should not be referenced to a static field.
solution:
Remove the static of your arrayList.
Static methods get created only once, so you can't reference getIntent() because Java doesn't know which instance of the method you are referencing.
Check here for more information on how static methods work.

getApplicationContext issue

I have VideoApplication class which extends Application class. I have created my other java class's object in this class so that I can pass it through activities.
public class VideoApplication extends Application {
private Client client;
public Client getClient(){
return client;
}
public void setClient(Client client){
this.client = client;
}
}
I have added following line in androidManifest file:
android.name=".VideoApplication".
But when I add the following line to my code(MainActivity.java), the application throws a ClassCastException exception.
VideoApplication appInstance = (VideoApplication)getApplicationContext();
Where am I going wrong? Please help.
You might be causing a ClassCastException. Try using getApplication() not getApplicationContext():
VideoApplication appInstance = (VideoApplication) getApplication();
Since you really want an Application object not a Context object.
Sure I am late to answer this but
android.name=".VideoApplication
doesn't seem right. I think it should be
android:name=".VideoApplication
I hope its not a typo.
You could try using getClass().getName() on the instance to see actually which type is it and then do the proper cast.

why does getContentResolver() within Application cause NullPointerException?

in the following code:
public class ApplicationContext extends Application
{
private static ApplicationContext instance;
public ApplicationContext()
{
instance = this;
final String strID = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
}
public static Context getContext()
{
return instance;
}
}
getContentResolver() causes a NullPointerException. Why ?
I find this exception especially confusing because Google states "You get a ContentResolver by calling getContentResolver() from within the implementation of an Activity or other application component"
http://developer.android.com/guide/topics/providers/content-providers.html
Do this when overriding oncreate better than in your constructor. I guess your app doesn't have a context yet.
Actually, here is what I did yesterday for some LVL code :
/** Called when the activity is first created. */
#Override
public void onCreate() {
super.onCreate();
LICENSED_APP_ID = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
}//cons
And it works like a charm...
The "Application" class is not an "Application Component".
http://developer.android.com/guide/topics/fundamentals.html#Components
To solve this problem, my plan is to grab the ANDROID_ID from within a service.

Categories

Resources