So I've got this error code: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
The line: Intent callMode = new Intent(MainActivity.this, IncallActivity.class);
What I'm trying to do is to set a new activity when I receive a call. The following function is what should "switch" to that activity.
public void callMode() {
Intent callMode = new Intent(MainActivity.this, IncallActivity.class);
startActivity(callMode);
}
And it is located inside of the MainActivity class, outside of the onCreate function.
When I try to put it inside of the onCreate function (without public void callMode() of course) it works, but that's not the goal.
I'm trying to activate this new activity from another class, which listens for calls.
public class CallReceiver extends BroadcastReceiver {
IncallActivity incallActivity = new IncallActivity();
public MainActivity mainActivity;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
mainActivity.callMode();
} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)) {
incallActivity.endCallMode();
}
}
}
So why does this error show up?
I found a way to do it.
You need to add a public static Context context to your code, and then in onCreate, do context = getBaseContext();
From there you can launch the second activity from any class you'd like.
Related
I have a service from where I want to send a broadcast using:
public class BackgroundService extends Service {
public BackgroundService() {
Log.i(MainActivity.TAG, "Background service started");
Intent broadcastIntent = new Intent("android.intent.action.CUSTOM_INTENT");
sendBroadcast(broadcastIntent);
}
The service is started from the Main Activity like so:
public void buttonClick(View view) {
Intent serviceIntent = new Intent(this, BackgroundService.class);
startService(serviceIntent);
}
However this does not work, it shows this error:
.BackgroundService: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.sendBroadcast(android.content.Intent)' on a null object reference
Can anyone point out why? or provide a working example?
Thanks
You can do this with localBroadcastReceiver like below in service
val intent = Intent()
intent.setAction(YOUR_ACTION_STRING)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
and on activity write below code
intentFilter.addAction(YOUR_ACTION_STRING);
LocalBroadcastManager.getInstance(context).registerReceiver(yourReceiver, intentFilter)
and yourReceiver param extends from broadcastReceiver
I have a java Class that extends Plugin (PhoneGap), but when inside this class, i call another class that extends Activity, it just doesn't work !. i mean, it seems like it doesn't get called. To confirm this, i have change my second class, this time, not extending from Activity and it works fine. i need teh second one to extends from Activity because i am using this two utilities (getFileStreamPath and openFileOutput) to create a file
File filepath = getFileStreamPath("filename.CPCL"); and openFileOutput
FileOutputStream os = this.openFileOutput(fileName, Context.MODE_PRIVATE);
I have an app with a class which extends a custom Service that calls another class which extends Activity.
First I instantiate the Activity. In the onCreate of your Plugin class use:
// get a handle on your Application
Application app = getApplication();
Intent intent = new Intent(getApplicationContext(), YourActivity.class);
app.startActivity(intent);
This will start your Activity and call the standard Lifecycle events.
The way I handle continued communication with the running Activity is by using a Handler to send a broadcast from your plugin which the Activity picks up in its receiver. In the onCreate of your plugin:
mHandler.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Call the Activity");
Intent intent = new Intent(YourActivity.CALL_FROM_PLUGIN);
intent.putExtra("request", <<Any extras you might want to send through>>);
sendBroadcast(intent);
}
});
In the Activity I declare the variable:
public static final String CALL_FROM_PLUGIN= "CALL_FROM_PLUGIN";
then in onCreate() I added the following;
IntentFilter filter = new IntentFilter();
filter.addAction(CALL_FROM_PLUGIN);
registerReceiver(mBroadcastReceiver, filter);
and then implemented a BroadcastReceiver:
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "BroadcastReceiver.onReceive()");
if (CALL_FROM_PLUGIN.equals(action)) {
Log.d(TAG, "Received call from Plugin");
// DO YOUR STUFF HERE
}
}
};
Someone else might be able to point out why this is necessary from a framework point of view, but this is the way I understand that Activities should be called. I hope this applies to your plugin class the way it does with my service class!
I'm having trouble starting my mainActivity after I have gotten a response from a httpUrlConnection.
Here is my onPostExecute method
protected void onPostExecute(String[] result) {
serv.httphelper.handleResults(result);
}
In the method handleResult() im handling the response code. If the response code is 200 i want to run a new method inside my loginActivity class
public void handleResults(String[] result) {
status = result[0].toString();
instructions = result[1].toString();
jsonString = result[2];
Log.d("DEBUG", status);
if (status.equals("200")) {
serv.loginActivity.proceed();
} else if (status.equals("400")) {
serv.loginActivity.loginError();
} else if (status.equals("401")) {
serv.loginActivity.loginError();
}
}
When i try to start a new activity from the proceed() method i get a nullpointerexception
public void proceed(){
startActivity(new Intent (LoginActivity.this, MainActivity.class));
Log.d("TEST", "Proceed success");
}
My service class for anyone wondering:
public class Service {
public static HttpHelper httphelper = new HttpHelper();
public static HttpConnect conn = new HttpConnect();
public static LoginActivity loginActivity = new LoginActivity();
}
And here is my logCat:
Thanks in advance!
Your problem is when you start the activity at the line:
startActivity(new Intent (LoginActivity.this, MainActivity.class));
Well, you creates an intent that tries to get to LoginActivity.this which probably does not exists!
Instead of this, you have to give an instance of a real activity that is currently running.
A solution that I can suggest you is to pass to proceed() the instance of the currently running activity and put it instead of LoginActivity.this.
In case you don't have a current activity, try to put your application's context instead and add it a flag of a new task.
I'm new to android and I have a problem with this code. I'm trying to get a JSON String and start another activity to display it as a ListView.
I'm not able to start the activity. It says that the The constructor Intent(RequestJsonString, Class) is undefined and The constructor Intent(RequestJsonString, Class) is undefined .
Here:
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
and Here:
RequestJsonString.this.startActivity(intent);
I have read many posts on this on stackoverflow and tried with activity, context and this. But still I'm not getting it right. I think I should be missing something. Any help is appreciated.
public class RequestJsonString extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... urls) {
// Code HTTP Get Request and get JSONObject
return jsonObject;
}
protected void onPostExecute(JSONObject jsonObj){
try {
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
intent.putExtra("JSON_Object", jsonObj.toString());
RequestJsonString.this.startActivity(intent);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("Json_OutPut","Done");
}
}
To start the activity from AsyncTask.
Intent intent = new Intent(YourActivityName.this,DisplayResults.class);
or you can do same like below.
Declare the context instance variable and initialize it in onCreate method.
private Context context;
public void onCreate(Bundle bundle) {
............
context = this;
........
}
Start the activity like this.
Intent intent = new Intent(context,DisplayResults.class);
intent.putExtra("JSON_Object", jsonObj.toString());
startActivity(intent);
In your case you are referring to asynctask class context
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
Use a Activity Context
Intent intent = new Intent(ActivityName.this,DisplayResults.class);
Check the link to know when to use getApplicationContext() and when to use Activity Context
When to call activity context OR application context?
Edit:
Pass the Activity context to the asynctask constructor
new RequestJsonString(ActivityName.this).execute(params..);
In your asynctask constructor
Context c;
public RequestJsonString( Context context)
{
c= context;
}
Then
Intent intent = new Intent(c,DisplayResults.class);
startActivity(intent);
I'm android beginner so please be easy on me. I'm doing some "exercises" and i'm writing simple app which will tell RSSI strength of home wifi network. Getting that number is pretty easy, but updating it and showing that on screen it's a little more complicated as i thought.
First this is my onCreate Activity. In this activity i'm launching another android component - Service. Because the code will run in background (i know i could use thread or something else, but this is for "practice" sake, and i have a few ideas what to do with this app, while running service and not interacting with UI )
public class MainActivity extends Activity {
TextView wifi_check;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
referenceViews();
startService(new Intent(this, CheckingWifiService.class));
//wifi_check.setText(""+getIntent().getExtras().getInt("RSSI"));
}
private void referenceViews() {
wifi_check = (TextView) findViewById(R.id.wifiCheck_TV);
}
}
Because my code will run every second or so, i will use TimerTask for this purpose. And here is my TimerTask class, which includes run() method, and code for executing inside
public class TimerTsk extends TimerTask {
Context act;
WifiManager wifiMan;
WifiInfo info;
Bundle sendInfo;
Intent intent;
int rssi;
public TimerTsk(Context context) {
act = context;
}
#Override
public void run() {
intent = new Intent();
sendInfo = new Bundle();
wifiMan = (WifiManager) act.getSystemService(Activity.WIFI_SERVICE);
info = wifiMan.getConnectionInfo();
rssi = info.getRssi();
Log.d("WORKED", "RUNNING SUCESSFULLY");
// i want to send info to my activity
sendInfo.putInt("RSSI", rssi);
intent.putExtras(sendInfo);
}
}
From this class , i want to send result of RSSI to my activity and then update a text. But when i call this code below, on activity i always get NullPointerException.
wifi_check.setText(""+getIntent().getExtras().getInt("RSSI"));
To be honest i had hard time figuring out which part of code is throwing an exepction. And i found that more exactly, this part of code is throwing an exepction.
getInt("RSSI")
Overall i see that service is running, because in my LOGCAT i see a message that i create with Log.d in TimerTsk class.
Any ideas why is this happening?
Here is my service class:
public class CheckingWifiService extends Service{
int rssi;
Timer time;
TimerTsk ttsk;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
time = new Timer();
time.schedule(new TimerTsk(getApplicationContext()), 500);
return START_STICKY;
}
}
Here is my LogCat:
I see a common mistake. Don't do this:
sendInfo.putInt("RSSI", rssi);
intent.putExtras(sendInfo); // This adds a Bundle to your existing Bundle!
You are creating an Intent, with a Bundle of extras, with a Bundle that holds rssi. Leave out this unnecessary Bundle:
intent.putExtras("RSSI", rssi);
Now in your next Activity you can use:
getIntent().getIntExtra("RSSI", 0);
However you should always check to make sure there aren't any surprise null variables:
Intent in = getIntent();
if(in != null) {
int rssi = in.getIntExtra("RSSI", -1);
if(rssi < 0)
wifi_check.setText(""+rssi);
else
wifi_check.setText("Unknown");
}
is your activity starting? I don't see any call to startActivity(). In any case as mentioned by Sam you just need to call putExtra for your intent. don't forget to call
is your activity starting? I don't see any call to startActivity(). In any case as mentioned by Sam you just need to call putExtra for your intent. don't forget to call
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
you need to put this flag when start activies from background