I am new to android development. My current application crashes on onClick event from the XML, but it seems to work just fine with onClickListner.
public static String URL_WEB;
NsdUtils mNsdUtils;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final NsdUtils mNsdUtils = new NsdUtils(this);
mNsdUtils.initializeNsd();
/*Button button =(Button) findViewById(R.id.btn_discover_networks);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View view)
{
mNsdUtils.discoverServices();
}
});*/
}
public void onClickDiscover(View view){
mNsdUtils.discoverServices();
}
Logs:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.implicitintents, PID: 6397
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.android.implicitintents.Utils.NsdUtils.discoverServices()' on a null object reference
at com.example.android.implicitintents.MainActivity.onClickDiscoverAura(MainActivity.java:40)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
It seems I am missing a very basic detail. Any help will be great.
NsdUtils
public class NsdUtils {
Context mContext;
NsdManager mNsdManager;
NsdManager.ResolveListener mResolveListener;
NsdManager.DiscoveryListener mDiscoveryListener;
//To find all the available networks SERVICE_TYPE = "_services._dns-sd._udp"
public static final String SERVICE_TYPE = "_http._tcp";
public static final String TAG = "NsdUtils";
public String mServiceName = "_hap";
NsdServiceInfo mService;
public NsdUtils(Context context) {
mContext = context;
mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
}
public void initializeNsd() {
initializeDiscoveryListener();
initializeResolveListener();
}
public void initializeDiscoveryListener() {
mDiscoveryListener = new NsdManager.DiscoveryListener() {
#Override
public void onDiscoveryStarted(String regType) {
Log.d(TAG, "Service discovery started " + regType);
}
#Override
public void onServiceFound(NsdServiceInfo service) {
Log.d(TAG, "Service discovery success" + service);
if(!service.getServiceType().equals(SERVICE_TYPE)){
Log.d(TAG, "Unknown Service Type: " + service.getServiceType());
}
else if(service.getServiceName().equals(mServiceName)){
Log.d(TAG, "Same Machine: " + mServiceName);
}
else if(service.getServiceName().contains(mServiceName)){
mNsdManager.resolveService(service, mResolveListener);
}
}
#Override
public void onServiceLost(NsdServiceInfo service) {
Log.e(TAG, "service lost" + service);
if (mService == service) {
mService = null;
}
}
#Override
public void onDiscoveryStopped(String serviceType) {
Log.i(TAG, "Discovery stopped: " + serviceType);
}
#Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
#Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
};
}
public void initializeResolveListener() {
mResolveListener = new NsdManager.ResolveListener() {
#Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e(TAG, "Resolve failed" + errorCode);
}
#Override
public void onServiceResolved(NsdServiceInfo serviceInfo) {
Log.e(TAG, "Resolve Succeeded. " + serviceInfo);
if (serviceInfo.getServiceName().equals(mServiceName)) {
Log.d(TAG, "Same IP.");
return;
}
mService = serviceInfo;
}
};
}
public void stopDiscovery() {
mNsdManager.stopServiceDiscovery(mDiscoveryListener);
}
public NsdServiceInfo getChosenServiceInfo() {
return mService;
}
public void discoverServices() {
mNsdManager.discoverServices(
SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
}
}
XML
<Button
android:id="#+id/btn_discover_networks"
android:layout_width="match_parent"
android:layout_height="50dp"
android:onClick="onClickDiscover"
android:text="Discover Networks"/>
Why don't you make mNsdUtils to be a member field if it should be accessed from the outside of the function?
The root cause saying mNsdUtils is null from the MainActivity.onClickDiscover() implementation.
Implement in the method itself, as the context is different throwing a null pointer exception.
A small tip for you: read the stack trace and find your source code(for your case, MainActivity.java) to locate what was the first error from bottom to up.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.android.implicitintents.Utils.NsdUtils.discoverServices()' on a null object reference
at com.example.android.implicitintents.MainActivity.onClickDiscoverAura(MainActivity.java:40)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
This is the one you need.
at com.example.android.implicitintents.MainActivity.onClickDiscoverAura(MainActivity.java:40)
There is nothing wrong with onClick. Please read your following log :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.android.implicitintents.Utils.NsdUtils.discoverServices()' on a null object reference
It means that inside onClick "mNsdUtils" is null. For more assistance please post your NsdUtils class.
Do the following and your app won't crash:
public void onClickDiscover(View view){
if(mNsdUtils != null) //add this line
mNsdUtils.discoverServices();
}
onClickListener is working just fine. You have to instantiate NSD object globally and then use it.
Related
I have the following code:
MainActivity.java
package com.example.bluejob;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void scheduleJob(View v) {
ComponentName componentName = new ComponentName(this, BlueJobM.class);
JobInfo info = new JobInfo.Builder(821, componentName)
.setRequiresCharging(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setPersisted(true)
.setPeriodic(15 * 60 * 1000)
.build();
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode;
resultCode = scheduler.schedule(info);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Job scheduled");
} else {
Log.d(TAG, "Job scheduling failed");
}
}
public void cancelJob(View v) {
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
scheduler.cancel(821);
Log.d(TAG, "Job cancelled");
}
}
OnStartJob method in BlueJobM.java
#Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job started");
doBackgroundWork(params);
return true;
}
When I start the code on my Redmi I revive di series of errors:
2021-09-22 15:33:56.527 21306-21306/com.example.bluejob E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bluejob, PID: 21306
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.IllegalArgumentException: No such service ComponentInfo{com.example.bluejob/com.example.bluejob.BlueJobM}
at android.os.Parcel.createException(Parcel.java:1957)
at android.os.Parcel.readException(Parcel.java:1921)
at android.os.Parcel.readException(Parcel.java:1871)
at android.app.job.IJobScheduler$Stub$Proxy.schedule(IJobScheduler.java:184)
at android.app.JobSchedulerImpl.schedule(JobSchedulerImpl.java:44)
"I THINK THE ERROR IS HERE" at com.example.bluejob.MainActivity.scheduleJob(MainActivity.java:32)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: android.os.RemoteException: Remote stack trace:
at com.android.server.job.JobSchedulerService$JobSchedulerStub.enforceValidJobRequest(JobSchedulerService.java:2538)
at com.android.server.job.JobSchedulerService$JobSchedulerStub.schedule(JobSchedulerService.java:2600)
at android.app.job.IJobScheduler$Stub.onTransact(IJobScheduler.java:60)
at android.os.Binder.execTransact(Binder.java:735)
When I start the App I can enter in the CancelJob method which correctly calls onStopJob on BlueJobM.java (i can see the log).
When I remove this part of code form MainActivity.java
int resultCode;
resultCode = scheduler.schedule(info);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Job scheduled");
} else {
Log.d(TAG, "Job scheduling failed");
}
the error does not show up but the job doesn't start anyway.
I suspect the program has some problem building the Job but I'm not sure.
I put more code on Github if is needed https://github.com/jaxis/BlueJob.
I was following this tutorial soo the code should be similar to this one https://www.youtube.com/watch?v=3EQWmME-hNA&t .
Thanks in advance.
java.lang.IllegalArgumentException: No such service
ComponentInfo{com.example.bluejob/com.example.bluejob.BlueJobM}
That means it doesn't know anything about that class as a component. Generally this means you didn't add it to the manifest. Every Service and Activity you want to use needs to be in the manifest. In some cases BroadcastReceivers do as well (although not all).
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Null pointer Exception - findViewById()
(12 answers)
Closed 5 years ago.
My app is crashing everytime I try to click a button that inputs text into a listView, I am getting the "java.lang.IllegalStateException: Could not execute method for android:onClick"; I've tried other solutions to the problem but I can't seem to find my own solution. Any help is appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> arrayList;
ArrayAdapter<String> arrayAdapter;
String infoText;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable(){
#Override
public void run(){
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean isFirstStart = getPrefs.getBoolean("started",true);
if(isFirstStart)
{
startActivity(new Intent (MainActivity.this,Intro.class));
SharedPreferences.Editor e = getPrefs.edit();
e.putBoolean("started", false);
e.apply();
}
}
});
thread.start();
listView = (ListView) findViewById(R.id.ListView);
arrayList = new ArrayList<>();
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
intent.setClass(MainActivity.this,EditMessageClass.class);
intent.putExtra(Intent_Constants.INTENT_INFO_DATA,arrayList.get(position).toString());
intent.putExtra(Intent_Constants.INTENT_ITEM_POSITION,position);
startActivityForResult(intent,Intent_Constants.INTENT_REQUEST_CODE_2);
}
});
}
public void onClick(View v){
Intent intent = new Intent();
intent.setClass(MainActivity.this,EditFieldClass.class);
startActivityForResult(intent,Intent_Constants.INTENT_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode==Intent_Constants.INTENT_REQUEST_CODE){
infoText = data.getStringExtra(Intent_Constants.INTENT_INFO_FIELD);
arrayList.add(infoText);
arrayAdapter.notifyDataSetChanged();
}
else if(resultCode==Intent_Constants.INTENT_REQUEST_CODE_2){
infoText = data.getStringExtra(Intent_Constants.INTENT_CHANGED_INFO);
position = data.getIntExtra(Intent_Constants.INTENT_ITEM_POSITION,-1);
arrayList.remove(position);
arrayList.add(position,infoText);
arrayAdapter.notifyDataSetChanged();
}
}
}
Intent_Constants.java
public class Intent_Constants {
public final static int INTENT_REQUEST_CODE=1;
public final static int INTENT_RESULT_CODE=1;
public final static int INTENT_REQUEST_CODE_2=2;
public final static int INTENT_RESULT_CODE_2=2;
public final static String INTENT_INFO_FIELD="info_field";
public final static String INTENT_INFO_DATA="info_data";
public final static String INTENT_ITEM_POSITION="item_position";
public final static String INTENT_CHANGED_INFO="changed_info";
EditMessageClass.java
public class EditMessageClass extends AppCompatActivity {
String infoText;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_promo_layout);
Intent intent = getIntent();
infoText = intent.getStringExtra(Intent_Constants.INTENT_INFO_DATA);
position = intent.getIntExtra(Intent_Constants.INTENT_ITEM_POSITION,-1);
EditText infoData = (EditText) findViewById(R.id.info);
infoData.setText(infoText);
}
public void saveButtonClicked(View v){
String changedinfoText = ((EditText)findViewById(R.id.info)).getText().toString();
Intent intent = new Intent();
intent.putExtra(Intent_Constants.INTENT_CHANGED_INFO,changedinfoText);
intent.putExtra(Intent_Constants.INTENT_ITEM_POSITION, position);
setResult(Intent_Constants.INTENT_RESULT_CODE_2,intent);
finish();
}
}
EditFieldClass.java
public class EditFieldClass extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_promo_layout);
}
public void saveButtonClicked(View v){
String infoText = ((EditText)findViewById(R.id.info)).getText().toString();
if(infoText.equals("")){
}
else{
Intent intent = new Intent();
intent.putExtra(Intent_Constants.INTENT_INFO_FIELD,infoText);
setResult(Intent_Constants.INTENT_RESULT_CODE,intent);
finish();
}
}
}
Logs
FATAL EXCEPTION: main
Process: gabriel.com.prototype, PID: 15435
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at gabriel.com.prototype.EditFieldClass.saveButtonClicked(EditFieldClass.java:27)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
According to your logcat message, I can say that your EditText object is null
the problem is caused by this line.
((EditText)findViewById(R.id.info)).getText().toString()
Make sure you have EditText with id 'info' in EditFieldClass.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at gabriel.com.prototype.EditFieldClass.saveButtonClicked(EditFieldClass.java:27)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
your EditText is null , check editText id .
This question already has answers here:
Can not find a View with findViewById()
(4 answers)
Closed 6 years ago.
When I start my SettingsActivity, I get the following Error, but I don't know why, because I have done everything as always.
ERROR:
FATAL EXCEPTION: main Process: com.android.niklasvlach.vertretung, PID: 9175
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.niklasvlach.vertretung/com.android.niklasvlach.vertretung.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setOnItemSelectedListener(android.widget.AdapterView$OnItemSelectedListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) at android.app.ActivityThread.access$900(ActivityThread.java:154) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5294) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setOnItemSelectedListener(android.widget.AdapterView$OnItemSelectedListener)' on a null object reference at com.android.niklasvlach.vertretung.SettingsActivity.onCreate(SettingsActivity.java:28) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) at android.app.ActivityThread.access$900(ActivityThread.java:154) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5294) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
The Code:
public class SettingsActivity extends AppCompatActivity {
Spinner select;
EditText username;
EditText password;
#Override
protected void onCreate(Bundle savedInstanceState) {
select = (Spinner) findViewById(R.id.selectclass);
username = (EditText) findViewById(R.id.username_view);
password = (EditText) findViewById(R.id.password_view);
select.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long text) {
Toast.makeText(SettingsActivity.this,"" + text,Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
}
If anything else is needed, I will post it!
You need to do your UI work after setting the layout of the Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
select = (Spinner) findViewById(R.id.selectclass);
username = (EditText) findViewById(R.id.username_view);
password = (EditText) findViewById(R.id.password_view);
select.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long text) {
Toast.makeText(SettingsActivity.this,"" + text,Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
I'm creating a simple Android Class that update a variable with the most recent value readed from some specific sensors (Light, temp and more), which I access it(sensor value) by getData() method, but i'm getting an error. I hope u can help me!
Here is my generic sensor class.
MySensor
public class mySensor extends Service implements SensorEventListener {
private SensorManager mSensorManager =null;
private Sensor s=null;
float data = 0;
public void onCreate(){
super.onCreate();
mSensorManager= (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
public mySensor(int type){
//HERE I'M GETTING THE ERROR
s= mSensorManager.getDefaultSensor(type);
}
public String getData(){
return String.valueOf(data);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
data = event.values[0];
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
protected void onResume() {
mSensorManager.registerListener((SensorEventListener) this, s, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
// super.onPause();
mSensorManager.unregisterListener((SensorEventListener) this);
}
}
Here is the log
...
E/AndroidRuntime: FATAL EXCEPTION: main
Process: project.luke.com.sensorreader, PID: 25297
java.lang.RuntimeException: Unable to start activity ComponentInfo{project.luke.com.sensorreader/project.luke.com.sensorreader.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.hardware.Sensor android.hardware.SensorManager.getDefaultSensor(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2460)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522)
at android.app.ActivityThread.access$800(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5546)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:967)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.hardware.Sensor android.hardware.SensorManager.getDefaultSensor(int)' on a null object reference
at project.luke.com.sensorreader.mySensor.<init>(mySensor.java:39)
at project.luke.com.sensorreader.MainActivity.onCreate(MainActivity.java:32)
at android.app.Activity.performCreate(Activity.java:5975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522)
at android.app.ActivityThread.access$800(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5546)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:967)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
In my MainActivity class I simple call mLight=new mySensor(Sensor.TYPE_LIGHT); but this trigger the error, cause mSensorManager=null, always.
From your MainActivity:
Intent intent = new Intent(this, mySensor.class);
intent.putExtra("type", Sensor.TYPE_LIGHT);
and within your service:
#Override
public IBinder onBind(Intent intent) {
mSensorManager= (SensorManager) getSystemService(Context.SENSOR_SERVICE);
int type = intent.getExtras().get("type");
s= mSensorManager.getDefaultSensor(type);
return null;
}
then you can remove:
public mySensor(int type){
...
}
and eventually the code you wrote within the onCreate.
I need to disable headers in BrowseFragment, and add to the ArrayObjectAdapter card. When I do a setHeadersState(HEADERS_DISABLED) application crushes. If I run setHeadersState(HEADERS_DISABLED) method later, for example in onLoadFinished, the application does not crash, but the header bar immediately visible and then hidden, not every time an item is displayed in the adapter.
MainFragment.class
public class MainFragment extends BrowseFragment implements LoaderManager.LoaderCallbacks<List<Module>> {
private static final int MODULES_LOADER_ID = 100;
private ArrayObjectAdapter mRowsAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setupUIElements();
setupRowAdapter();
setupListeners();
getLoaderManager().initLoader(MODULES_LOADER_ID, null, this);
}
private void setupUIElements() {
setTitle(getActivity().getString(R.string.app_name));
setBadgeDrawable(getResources().getDrawable(R.drawable.title, getActivity().getTheme()));
setHeadersTransitionOnBackEnabled(false);
setBrandColor(getActivity().getResources().getColor(R.color.fastlane_background));
setHeadersState(HEADERS_DISABLED);
}
private void setupRowAdapter() {
mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
setAdapter(mRowsAdapter);
}
private void setupListeners() {
setOnItemViewSelectedListener(new ItemViewSelectedListener());
setOnItemViewClickedListener(new ItemViewClickedListener());
}
private void loadModules(List<Module> modules) {
ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new ModulesCardPresenter());
for (Module module : modules) {
listRowAdapter.add(module);
}
HeaderItem header = new HeaderItem(0, "Меню");
mRowsAdapter.add(new ListRow(header, listRowAdapter));
}
#Override
public Loader<List<Module>> onCreateLoader(int id, Bundle args) {
switch (id) {
case MODULES_LOADER_ID:
return new ModulesLoader(getActivity());
default:
return null;
}
}
#Override
public void onLoadFinished(Loader<List<Module>> loader, List<Module> data) {
switch (loader.getId()) {
case MODULES_LOADER_ID:
loadModules(data);
break;
}
}
#Override
public void onLoaderReset(Loader<List<Module>> loader) {
}
static class ModulesLoader extends SimpleAsyncTaskLoader<List<Module>> {
public ModulesLoader(Context context) {
super(context);
}
#Override
public List<Module> loadInBackground() {
Call<Modules> mCall = ServiceHolder.getService()
.getModules(Constants.GET_MODULES_REQUEST);
try {
return mCall.execute().body().getModules();
} catch (Exception e) {
e.printStackTrace();
return Collections.EMPTY_LIST;
}
}
}
private final class ItemViewSelectedListener implements OnItemViewSelectedListener {
#Override
public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item,
RowPresenter.ViewHolder rowViewHolder, Row row) {
}
}
private final class ItemViewClickedListener implements OnItemViewClickedListener {
#Override
public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
RowPresenter.ViewHolder rowViewHolder, Row row) {
}
}
Log:
08-18 16:06:08.331 29647-29647/ E/AndroidRuntime: FATAL EXCEPTION: main
Process: , PID: 29647
**java.lang.RuntimeException: Unable to start activity ComponentInfo{.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Fragment.getView()' on a null object reference**
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
**Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Fragment.getView()' on a null object reference**
at android.support.v17.leanback.app.BrowseFragment.onStart(BrowseFragment.java:1511)
at android.app.Fragment.performStart(Fragment.java:2244)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1002)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1130)
at android.app.FragmentManagerImpl.dispatchStart(FragmentManager.java:1958)
at android.app.FragmentController.dispatchStart(FragmentController.java:163)
at android.app.Activity.performStart(Activity.java:6274)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) </code>
I have setHeadersState(HEADERS_DISABLED) in my fragment onCreate() method. It looks like you have yours in onActivityCreated(). You should try moving it. Let me know if that works.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHeadersState(HEADERS_DISABLED)
}
Maybe it'll be useful to you
code.google.com issue
As Viktor Dolgalyov has mentioned, there is a bug filed. #214795 which is followed by #223942 where there is an official reply that this will be fixed around December.