ListAdapter does not work - java

I have a mainActivity which has a button named monitoring. When I press the button it should show the nearby beacons. When I press the button an error shows up which say's my application stopped working. Here is the code of the button activity:
public class MonitoringBeacons extends AppCompatActivity {
private ProximityManagerContract proximityManager;
ListAdapter beaconsAdapter;
ListView listView;
List<String> beaconsList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitoring_beacons);
KontaktSDK.initialize("kasjdhioasjkdoasdjo");
proximityManager = new ProximityManager(this);
proximityManager.setEddystoneListener(createEddystoneListener());
setAdapter();
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String beacon = String.valueOf(adapterView.getItemAtPosition(position));
Toast.makeText(MonitoringBeacons.this, beacon, Toast.LENGTH_SHORT).show();
}
}
);
}
protected void setAdapter() {
if(beaconsList.isEmpty()) {
Toast.makeText(MonitoringBeacons.this, "No beacons found", Toast.LENGTH_SHORT).show();
return ;
}
beaconsAdapter = new CustomListAdapter(this, beaconsList);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(beaconsAdapter);
}
#Override
protected void onStart() {
super.onStart();
startScanning();
}
#Override
protected void onStop() {
proximityManager.stopScanning();
super.onStop();
}
#Override
protected void onDestroy() {
proximityManager.disconnect();
proximityManager = null;
super.onDestroy();
}
private void startScanning() {
proximityManager.connect(new OnServiceReadyListener() {
#Override
public void onServiceReady() {
proximityManager.startScanning();
}
});
}
private EddystoneListener createEddystoneListener() {
return new SimpleEddystoneListener() {
#Override
public void onEddystoneDiscovered(IEddystoneDevice eddystone, IEddystoneNamespace namespace) {
beaconsList.add(eddystone.getUniqueId());
setAdapter();
}
#Override
public void onEddystoneLost(IEddystoneDevice eddystone, IEddystoneNamespace namespace) {
beaconsList.remove(eddystone.getUniqueId());
setAdapter();
}
};
}
}
and the code of CustomListAdapter:
public class CustomListAdapter extends BaseAdapter {
private List<String> beaconsList;
private Activity activity;
private LayoutInflater inflater;
public CustomListAdapter(Activity activity, List<String> beaconsList) {
this.activity = activity;
this.beaconsList = beaconsList;
}
#Override
public int getCount() {
return beaconsList.size();
}
#Override
public Object getItem(int location) {
return beaconsList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.custom_row, null);
String singleBeaconItem = String.valueOf(getItem(position));
TextView beaconText = (TextView) convertView.findViewById(R.id.BeaconText);
ImageView beaconImage = (ImageView) convertView.findViewById(R.id.BeaconImage);
beaconText.setText(singleBeaconItem);
beaconImage.setImageResource(R.drawable.tough_beacon_1);
return convertView;
}
}
Ideally when I press the button the nearby beacons should be appeared as a list, and when a beacon is discovered or lost the list should automaticaly be updated.
EDITED
Stack trace in LogCat
--------- beginning of crash
08-06 17:02:15.276 2559-2559/com.example.panagiotis.beaconsproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.panagiotis.beaconsproject, PID: 2559
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.panagiotis.beaconsproject/com.example.panagiotis.beaconsproject.MonitoringBeacons}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' 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 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at com.example.panagiotis.beaconsproject.MonitoringBeacons.onCreate(MonitoringBeacons.java:44)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
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)
08-06 17:02:18.087 2559-2559/com.example.panagiotis.beaconsproject I/Process: Sending signal. PID: 2559 SIG: 9
08-06 17:02:22.298 3433-3433/com.example.panagiotis.beaconsproject W/System: ClassLoader referenced unknown path: /data/app/com.example.panagiotis.beaconsproject-1/lib/x86
08-06 17:02:22.455 3433-3433/com.example.panagiotis.beaconsproject W/System: ClassLoader referenced unknown path: /data/app/com.example.panagiotis.beaconsproject-1/lib/x86
08-06 17:02:22.604 3433-3433/com.example.panagiotis.beaconsproject W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
08-06 17:02:22.715 3433-3460/com.example.panagiotis.beaconsproject D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
[ 08-06 17:02:22.718 3433: 3433 D/ ]
HostConnection::get() New Host Connection established 0xaa9a71c0, tid 3433
[ 08-06 17:02:22.754 3433: 3460 D/ ]
HostConnection::get() New Host Connection established 0xaa9a6920, tid 3460
08-06 17:02:22.768 3433-3460/com.example.panagiotis.beaconsproject I/OpenGLRenderer: Initialized EGL, version 1.4
08-06 17:02:24.070 3433-3460/com.example.panagiotis.beaconsproject E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaa9b17f0
08-06 17:02:26.685 3433-3433/com.example.panagiotis.beaconsproject W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=397.5, y[0]=956.6797, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=70853, downTime=67680, deviceId=0, source=0x1002 }
08-06 17:02:26.685 3433-3433/com.example.panagiotis.beaconsproject W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=397.5, y[0]=956.6797, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=70853, downTime=67680, deviceId=0, source=0x1002 }
08-06 17:02:26.686 3433-3433/com.example.panagiotis.beaconsproject W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=397.5, y[0]=956.6797, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=70853, downTime=67680, deviceId=0, source=0x1002 }
08-06 17:02:26.686 3433-3433/com.example.panagiotis.beaconsproject W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=397.5, y[0]=956.6797, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=70853, downTime=67680, deviceId=0, source=0x1002 }
08-06 17:02:28.817 3433-3460/com.example.panagiotis.beaconsproject E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaa9b17f0
08-06 17:02:29.373 3433-3460/com.example.panagiotis.beaconsproject E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb40938f0
08-06 17:02:29.375 3433-3460/com.example.panagiotis.beaconsproject D/OpenGLRenderer: endAllStagingAnimators on 0xa1d53580 (RippleDrawable) with handle 0xa203f910
08-06 17:02:30.806 3433-3460/com.example.panagiotis.beaconsproject E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4094e60
08-06 17:02:32.811 3433-3460/com.example.panagiotis.beaconsproject E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb40938f0
08-06 17:02:35.874 3433-3433/com.example.panagiotis.beaconsproject D/AndroidRuntime: Shutting down VM
08-06 17:02:35.874 3433-3433/com.example.panagiotis.beaconsproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.panagiotis.beaconsproject, PID: 3433
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.panagiotis.beaconsproject/com.example.panagiotis.beaconsproject.MonitoringBeacons}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' 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 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at com.example.panagiotis.beaconsproject.MonitoringBeacons.onCreate(MonitoringBeacons.java:44)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
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)
08-06 17:02:39.204 3433-3433/com.example.panagiotis.beaconsproject I/Process: Sending signal. PID: 3433 SIG: 9
Any idea?

The stacktrace explains what is happening.
When this line of code executes:
listView.setOnItemClickListener(...
The listView has not yet been initialized, so it is null. This causes a NullPointerException.
That variable is initialized in the setAdapter() method, but it may not be because the method exits early if beaconsList.isEmpty() evaluates to true.
The simple solution is to move the code that initializes listView to top of that method.

Related

Android java.lang.NullPointerException error with BroadcastReceiver

Everytime the application gets to my second activity it crashes, giving the error.
My activity:
public class SecondActivity extends AppCompatActivity {
EditText barcodeText = findViewById(R.id.barcodeText);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction(getResources().getString(R.string.activity_intent_filter_action));
registerReceiver(myBroadcastReceiver, filter);
}
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
if (action.equals(getResources().getString(R.string.activity_intent_filter_action))) {
try {
displayScanResult(intent);
} catch (Exception e) {
}
}
}
};
private void displayScanResult(Intent initiatingIntent)
{
String decodedSource = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_source));
String decodedData = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_data));
String decodedLabelType = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
barcodeText.setText(decodedData);
}
}
Logcat:
07-01 12:37:03.373 349-349/com.example.provatimer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.provatimer, PID: 349
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.provatimer/com.example.provatimer.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5256)
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 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:438)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.provatimer.SecondActivity.<init>(SecondActivity.java:14)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5256) 
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) 
I think it may have something to do with the context in the BroadcastReceiver, but I tried to declare it in the onCreate method but nothing changed.
Maybe I don't initialize correctly the intent in which the data should be stored, if so, how can I do it correctly?
All the Strings should be correct int the string.xml file, if the error may come from that I'll write them.
I think the error is happening here:
EditText barcodeText = findViewById(R.id.barcodeText);
You are invoking findViewById() directly in the class member declaration.
You have invoke findViewById() after setContentView()
EditText barcodeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
barcodeText = findViewById(R.id.barcodeText);
}

Why is my app is crashing while using async task?

I have used asynctask for the first time. I also used a thread to automatically start a new activity after some time in the same activity.
Android studio shows no error in codes but my app crashes if I login or wait for my new activity to begin.
It is a test app for me using asynctask & connecting with my MySQL.
My code:
public class MainActivity extends AppCompatActivity {
EditText bQ,bR;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread=new Thread(){
#Override
public void run() {
try {
sleep(5*1000);
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
startActivity(i);
}
catch (Exception ex)
{}
}
};
thread.start();
ImageView ImageView = (ImageView) findViewById(R.id.imageView);
ImageView.setImageResource(R.drawable.fb);
bQ = (EditText)findViewById(R.id.username);
bR = (EditText)findViewById(R.id.password);
}
public void insertIntoDatabase() {
final String username = bQ.getText().toString();
final String password = bR.getText().toString();
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
try {
URL url = new URL("http://passwds.esy.es/upload.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
//OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
String userPass = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(paramUsername, "UTF-8") + "&"
+ URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(paramPassword, "UTF-8");
bufferedWriter.write(userPass);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = httpURLConnection.getInputStream();
inputStream.close();
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.v("Result:", result);
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(username, password);
}
public void submit(View view) {
insertIntoDatabase();
}
}
LogCat:
04-08 09:54:30.929 6707-6707/? I/art: Late-enabling -Xcheck:jni
04-08 09:54:30.957 6707-6714/? I/art: Debugger is no longer active
04-08 09:54:30.957 6707-6714/? I/art: Starting a blocking GC Instrumentation
04-08 09:54:30.986 6707-6707/? D/LenovoAppIconTheme: ExtraResources;cleanCachedIcon;clear cache..
04-08 09:54:31.145 6707-6707/? W/System: ClassLoader referenced unknown path: /data/app/com.books.admin.foxbooks-1/lib/arm
04-08 09:54:31.159 6707-6707/? I/InstantRun: starting instant run server: is main process
04-08 09:54:31.246 6707-6707/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-08 09:54:31.297 6707-6707/? V/BoostFramework: mAcquireFunc method = public int com.qualcomm.qti.Performance.perfLockAcquire(int,int[])
04-08 09:54:31.297 6707-6707/? V/BoostFramework: mReleaseFunc method = public int com.qualcomm.qti.Performance.perfLockRelease()
04-08 09:54:31.297 6707-6707/? V/BoostFramework: mAcquireTouchFunc method = public int com.qualcomm.qti.Performance.perfLockAcquireTouch(android.view.MotionEvent,android.util.DisplayMetrics,int,int[])
04-08 09:54:31.297 6707-6707/? V/BoostFramework: mIOPStart method = public int com.qualcomm.qti.Performance.perfIOPrefetchStart(int,java.lang.String)
04-08 09:54:31.298 6707-6707/? V/BoostFramework: mIOPStop method = public int com.qualcomm.qti.Performance.perfIOPrefetchStop()
04-08 09:54:31.300 6707-6707/? V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#cb8650
04-08 09:54:31.300 6707-6707/? V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#b74c049
04-08 09:54:31.529 6707-6727/? I/Adreno: QUALCOMM build : c6f59fa, Ie9c95840c4
Build Date : 06/16/17
OpenGL ES Shader Compiler Version: XE031.09.00.03
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.UM.5.5.R1.07.00.00.269.021
Remote Branch : NONE
Reconstruct Branch : NOTHING
04-08 09:54:31.535 6707-6727/? I/OpenGLRenderer: Initialized EGL, version 1.4
04-08 09:54:31.535 6707-6727/? D/OpenGLRenderer: Swap behavior 1
04-08 09:54:31.571 6707-6707/? W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
04-08 09:54:36.623 6707-6707/com.books.admin.foxbooks V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#633747d
04-08 09:54:36.623 6707-6707/com.books.admin.foxbooks V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#714df72
04-08 09:54:36.794 6707-6707/com.books.admin.foxbooks D/AndroidRuntime: Shutting down VM
04-08 09:54:36.795 6707-6707/com.books.admin.foxbooks E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.books.admin.foxbooks, PID: 6707
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.books.admin.foxbooks/com.books.admin.foxbooks.MainActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.books.admin.foxbooks.MainActivity2.onCreate(MainActivity2.java:21)
at android.app.Activity.performCreate(Activity.java:6705)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
You are Calling Activity in a Background Thread Thats Why you are getting Error
You Need to Call Like this
Thread thread=new Thread(){
#Override
public void run() {
try {
sleep(5*1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
startActivity(i);
}
});
}
catch (Exception ex)
{}
}
};
thread.start();

Unable to change to another activity

I want to change from main activity to login activity through button log in. i followed all the steps but it still doesn't work when i test it on my device.
this is main.java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View v = findViewById(R.id.buttonlog);
v.setOnClickListener((View.OnClickListener) this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.buttonlog)
{
Intent intent = new Intent(this,LoginActivity.class);
this.startActivity(intent);
}
}}
Login activity is:
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
}
The Logcat:
12-06 19:57:03.960 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl#c94e23f[MainActivity]: ViewPostImeInputStage processPointer 0
12-06 19:57:03.961 6374-6374/com.example.ancaalexandra.proiectandroidd E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]
12-06 19:57:03.961 6374-6374/com.example.ancaalexandra.proiectandroidd V/BoostFramework: BoostFramework() : mPerf = null
12-06 19:57:04.046 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl#c94e23f[MainActivity]: ViewPostImeInputStage processPointer 1
12-06 19:57:04.435 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl#c94e23f[MainActivity]: ViewPostImeInputStage processPointer 0
12-06 19:57:04.522 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl#c94e23f[MainActivity]: ViewPostImeInputStage processPointer 1
12-06 19:57:04.791 6374-6374/com.example.ancaalexandra.proiectandroidd D/ViewRootImpl#c94e23f[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0
12-06 19:57:04.837 6374-6374/com.example.ancaalexandra.proiectandroidd D/AndroidRuntime: Shutting down VM
12-06 19:57:04.838 6374-6374/com.example.ancaalexandra.proiectandroidd E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ancaalexandra.proiectandroidd, PID: 6374
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ancaalexandra.proiectandroidd/com.example.ancaalexandra.proiectandroidd.LoginActivity}: java.lang.ClassCastException: com.example.ancaalexandra.proiectandroidd.LoginActivity cannot be cast to android.view.View$OnClickListener
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Caused by: java.lang.ClassCastException: com.example.ancaalexandra.proiectandroidd.LoginActivity cannot be cast to android.view.View$OnClickListener
at com.example.ancaalexandra.proiectandroidd.LoginActivity.onCreate(LoginActivity.java:19)
at android.app.Activity.performCreate(Activity.java:6956)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6776) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408) 
I declared both activities in the manifest file. What i did wrong? thank you!
Your way of handling findViewById() and setting onClick listener is quite unusual.
Change this code :
View v = findViewById(R.id.buttonlog);
v.setOnClickListener((View.OnClickListener) this);
to this code :
Button loginButton = (Button)findViewById(R.id.buttonlog);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
}
});
And it should work just fine.
Your error is on this line:
v.setOnClickListener((View.OnClickListener) this);
which is explained in your stacktrace:
LoginActivity cannot be cast to android.view.View$OnClickListener
You are trying to cast your Activity LoginActivityto an OnClickListener, which won't work.
If your Activity implements an OnClickListener you just need to pass this :
class LoginActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
v.setOnClickListener(this)
}
}

java.lang.RuntimeException: Unable to resume activity : java.lang.NullPointerException

I am facing issue with my code.I am getting RuntimeException.Kindly please do help me with this.
I'm getting the following error log :
06-17 18:11:32.646 13750-13750/? E/Zygote: v2
06-17 18:11:32.646 13750-13750/? E/Zygote: accessInfo : 0
06-17 18:11:33.226 13750-13750/com.example.cocol.timisoara2021 E/MotionRecognitionManager: mSContextService = android.hardware.scontext.ISContextService$Stub$Proxy#f847827
06-17 18:11:33.226 13750-13750/com.example.cocol.timisoara2021 E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#d2d3ad4
06-17 18:11:33.226 13750-13750/com.example.cocol.timisoara2021 E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#d2d3ad4
06-17 18:11:36.566 13750-14348/com.example.cocol.timisoara2021 E/GooglePlayServicesUtil: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
06-17 18:11:36.666 13750-13750/com.example.cocol.timisoara2021 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cocol.timisoara2021, PID: 13750
java.lang.RuntimeException: Unable to resume activity {com.example.cocol.timisoara2021/com.example.cocol.timisoara2021.Main2Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.wikitude.common.orientation.internal.a.a()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4226)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4328)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3427)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7407)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.wikitude.common.orientation.internal.a.a()' on a null object reference
at com.wikitude.architect.ArchitectView.onResume(ProGuard:818)
at com.example.cocol.timisoara2021.Main2Activity.onResume(Main2Activity.java:59)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1287)
at android.app.Activity.performResume(Activity.java:7015)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4215)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4328) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3427) 
at android.app.ActivityThread.access$1100(ActivityThread.java:229) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7407) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
And here is the line 53:architectView.onResume();
And the code:
package com.example.cocol.timisoara2021;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.wikitude.architect.ArchitectStartupConfiguration;
import com.wikitude.architect.ArchitectView;
public class Main2Activity extends AppCompatActivity {
private ArchitectView architectView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
this.architectView = (ArchitectView) this.findViewById(R.id.architectView);
final ArchitectStartupConfiguration config = new ArchitectStartupConfiguration();
config.setLicenseKey("KKvjW60rM1+LoIdIXdMFdqLeXM8rI6uDFqScJycG9rTXI7GHrRdOx9dycHtxv8Ef6Y6jHB/abqr26X6+eqQXyb+ci4ETEEzCQAQFg3h4/+7DhpwYxY3ayzp3jh/+THcSLe2aKZPAvImpV5Ci0Y7yW891E7d+ionYP0iqJJt6mbNTYWx0ZWRfX05DoEhYDMgfmFUvxnY5fbtk7wnaNnJf4Orfhl+Zfp9DmwItjh/lTSX7MTbprDG700m7vZfWqY1j41pA5vYMiBTiiE1vn6qK66jZ8H5nxjsi3Jp3iAynh2VltO95P6CQy5IKBC9HYdWDtvL/lEmWk1lCOhs4xX8kxwsfD1rxqICVD+zP5Uv+4wnug4++E6vFSwUtDgSN+hY38QnTmh6wXKO5aO7PUm20UXC/7k2lvWNwywwX6LMwF4H4ShnIDQDdWSMSuLshIHvR4SWPNN3r+wK5ImnI/fl/yWmkpH66wB5jWSuE6PvIOSIKz+esUzxprAfQxT6bkpenU/jxNwPaYB8ZbhUHCSCN7vWvGO7z12V/B98xWCGzRdZE5VZqNEOyPA/AfvjSJBmenYpvgm4dw0hgyBQrkoc56P6jOEc8W1aSKdfXfmv0olhbapaEzSoKubZXoZ0ZgPPfjQ6eHtzSVkoOB2fHCVONXseHnjsj9+LYNx3w+DLn0PY=");
this.architectView.onCreate(config);
}
protected void OnPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
architectView.onPostCreate();
try {
this.architectView.load("file:///android_asset/POI/index.html");
}catch (Exception e) {
}
}
#Override
protected void onPause() {
super.onPause();
architectView.onPause();
}
#Override
protected void onResume() {
super.onResume();
architectView.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
architectView.onDestroy();
}
}
How can I fix this ?
Your onPostCreate method has an uppercase "O". Because of this i assume it is never called which means that the ArchitectView is in an invalid state when you call architectView.onResume.
Try:
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
architectView.onPostCreate();
try {
this.architectView.load("file:///android_asset/POI/index.html");
}catch (Exception e) {
}
}

Fatal exception at main android during dropbox authentication [duplicate]

This question already exists:
Dropbox Core API is not working. I don't want to hardcode app key and secret?
Closed 7 years ago.
I am getting fatal exception error at main nullpointer exception. basically i have 2 activities login and main activity.you will enter app key and app secret in login activity then after authentication it will take you to main activity any help ??
login activity
public class login_activity extends AppCompatActivity {
public String APP_kEY ;
public String APP_SECRET;
public String accessToken;
EditText app_key_view;
EditText App_secret_view;
Button dropbox;
public DropboxAPI<AndroidAuthSession> mDBApi;
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences pref = getSharedPreferences("login",MODE_PRIVATE);
APP_kEY = pref.getString("appkey",null);
APP_SECRET = pref.getString("appsecret",null);
accessToken = pref.getString("access",null);
if (accessToken != null){
AppKeyPair appkeys = new AppKeyPair(APP_kEY,APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appkeys);
session.setOAuth2AccessToken(accessToken);
Intent i = new Intent(login_activity.this,MainActivity.class);
startActivity(i);
finish();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_activity);
app_key_view=(EditText)findViewById(R.id.app_key_text);
App_secret_view=(EditText)findViewById(R.id.app_secret_text);
dropbox = (Button)findViewById(R.id.link_dropbox);
//////////////////////////////////////////////////////////////
dropbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
APP_kEY = app_key_view.getText().toString();
APP_SECRET = App_secret_view.getText().toString();
AppKeyPair appKeys = new AppKeyPair(APP_kEY,APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys);
mDBApi = new DropboxAPI<>(session);
mDBApi.getSession().startOAuth2Authentication(login_activity.this);
}
});
}
#Override
protected void onResume () {
super.onResume();
if(mDBApi.getSession().authenticationSuccessful()){
try {
mDBApi.getSession().finishAuthentication();
accessToken = mDBApi.getSession().getOAuth2AccessToken();
SharedPreferences.Editor editor = getSharedPreferences("login",MODE_PRIVATE).edit();
editor.putString("appkey",APP_kEY);
editor.putString("appsecret",APP_SECRET);
editor.putString("access",accessToken);
editor.commit();
Intent i = new Intent(login_activity.this,MainActivity.class);
startActivity(i);
finish();
}
catch (IllegalStateException e){
Log.i("DbAuthLog", "Error authenticationg", e);
}
}
}
Logcat
09-11 21:06:01.947 3842-3842/? I/art﹕ Late-enabling -Xcheck:jni
09-11 21:06:01.975 3842-3851/? I/art﹕ Debugger is no longer active
09-11 21:06:02.370 3842-3857/? I/art﹕ Background sticky concurrent mark sweep GC freed 2909(253KB) AllocSpace objects, 2(32KB) LOS objects, 0% free, 50MB/50MB, paused 36.891ms total 133.660ms
09-11 21:06:02.803 3842-3842/? D/AndroidRuntime﹕ Shutting down VM
09-11 21:06:02.803 3842-3842/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.ayzaz.timescopev1.timescope, PID: 3842
java.lang.RuntimeException: Unable to resume activity {com.example.ayzaz.timescopev1.timescope/com.example.ayzaz.timescopev1.timescope.login_activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.dropbox.client2.session.Session com.dropbox.client2.DropboxAPI.getSession()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2986)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.dropbox.client2.session.Session com.dropbox.client2.DropboxAPI.getSession()' on a null object reference
at com.example.ayzaz.timescopev1.timescope.login_activity.onResume(login_activity.java:77)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2975)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            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:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-11 21:06:05.849 3842-3842/com.example.ayzaz.timescopev1.timescope I/Process﹕ Sending signal. PID: 3842 SIG: 9
onResume() always gets called after onCreate().
When onResume() begins, mDBApi is null, because this field is only ever assigned in the onClick() method.
You either need to assign mDBApi in onCreate() directly, or you need to check that it is not null before you try to use it.

Categories

Resources