Switch between fragments with MapView - java

I have a main_activity with a bottom bar. I am using this bottom bar to navigate between fragments. However, there's this one fragment that's not directly navigatable via that bottom bar. It must be accessible from the fragment with MapView and upon onInfoWindowClick. However, the app crashes whenever I consume the infoWindow. Here's my code
public void onMapReady(GoogleMap googleMap) {
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.tesla);
mMap=googleMap;
for (Location item : array_list) {
String _title = item.getLocation_name();
String _snippet = item.getLocation_address();
LatLng _latLng = new LatLng(item.getLatitude(), item.getLongitude());
final MarkerOptions mMarkerOptions = new MarkerOptions().icon(icon);
mMarkerOptions.position(_latLng).title(_title).snippet(_snippet).flat(true);
Marker marker = mMap.addMarker(mMarkerOptions);
mMarkerHashMap.put(marker, item);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(marker.getPosition())
.zoom(12.0f)
.build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
LocationDetailFragment detailedlocation = new LocationDetailFragment();
detailedlocation.LOCATION = mMarkerHashMap.get(marker);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content, detailedlocation);
ft.addToBackStack(null);
ft.commit();
}
});
}
--------- beginning of crash 04-23 19:41:11.380 2573-2573/com.teslaqubitsins.fasih.teslahcm E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.teslaqubitsins.fasih.teslahcm, PID: 2573
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.View.findViewById(int)' on a null
object reference
at
com.teslaqubitsins.fasih.teslahcm.LocationDetailFragment.onCreateView(LocationDetailFragment.java:35)
at
android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at
android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at
android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at
android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at
android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at
android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at
android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
at
android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
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) 04-23
19:41:11.383 1564-1957/system_process W/ActivityManager: Force
finishing activity com.teslaqubitsins.fasih.teslahcm/.MainActivity
04-23 19:41:11.414 1296-1653/? E/SurfaceFlinger: ro.sf.lcd_density
must be defined as a build property
[ 04-23 19:41:11.456 1564: 3367 D/ ]
HostConnection::get() New Host Connection established 0x87cb5680, tid 3367 04-23
19:41:11.457 1296-1653/? D/gralloc_ranchu: gralloc_alloc: format 1 and
usage 0x900 imply creation of host color buffer 04-23 19:41:11.457
1564-3367/system_process I/OpenGLRenderer: Initialized EGL, version
1.4 04-23 19:41:11.458 1564-3367/system_process D/OpenGLRenderer: Swap behavior 1 04-23 19:41:11.458 1564-3367/system_process
W/OpenGLRenderer: Failed to choose config with
EGL_SWAP_BEHAVIOR_PRESERVED, retrying without... 04-23 19:41:11.458
1564-3367/system_process D/OpenGLRenderer: Swap behavior 0 04-23
19:41:11.462 1296-1653/? D/gralloc_ranchu: gralloc_alloc: format 1 and
usage 0x900 imply creation of host color buffer 04-23 19:41:11.476
1296-1653/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900
imply creation of host color buffer 04-23 19:41:11.892
1564-1591/system_process W/ActivityManager: Activity pause timeout for
ActivityRecord{34a233 u0
com.teslaqubitsins.fasih.teslahcm/.MainActivity t141 f} 04-23
19:41:11.921 1296-1962/? D/gralloc_ranchu: gralloc_alloc: format 1 and
usage 0x900 imply creation of host color buffer 04-23 19:41:11.940
1296-1962/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900
imply creation of host color buffer 04-23 19:41:11.951 1296-1962/?
D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply
creation of host color buffer 04-23 19:41:11.968 1296-1426/?
D/PermissionCache: checking android.permission.READ_FRAME_BUFFER for
uid=1000 => granted (252 us) 04-23 19:41:12.025 1296-1426/?
D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x333 imply
creation of host color buffer
Blockquote
package com.teslaqubitsins.fasih.teslahcm;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class LocationDetailFragment extends Fragment {
public static Location LOCATION;
TextView _campusName;
TextView _campusAddress;
public LocationDetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_location_detail, container, false);
_campusName = (TextView) getView().findViewById(R.id.campus_name);
_campusAddress = (TextView) getView().findViewById(R.id.campus_address);
_campusName.setText(LOCATION.getLocation_name());
_campusAddress.setText(LOCATION.getLocation_address());
return view;
}
public void onClick_call(View view) {
dialPhoneNumber(LOCATION.getLocation_phone());
}
public void dialPhoneNumber(String phoneNumber) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + phoneNumber));
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivity(intent);
}
}
}
04-23 19:58:11.735 6856-6856/com.teslaqubitsins.fasih.teslahcm
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.teslaqubitsins.fasih.teslahcm, PID: 6856
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.View.findViewById(int)' on a null
object reference
at
com.teslaqubitsins.fasih.teslahcm.LocationDetailFragment.onCreateView(LocationDetailFragment.java:35)
at
android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at
android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at
android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at
android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at
android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at
android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at
android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
at
android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
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) 04-23
19:58:12.507 2006-2282/com.google.android.gms.persistent W/GCoreFlp:
No location to return for getLastLocation() 04-23 19:58:42.534
2134-2214/com.google.android.googlequicksearchbox:search
W/GmsLocationProvider: Error removing location updates: 16

Instead of:
_campusName = (TextView) getView().findViewById(R.id.campus_name);
_campusAddress = (TextView) getView().findViewById(R.id.campus_address);
use the fragment's inflated view to get the ID's:
_campusName = (TextView) view.findViewById(R.id.campus_name);
_campusAddress = (TextView) view.findViewById(R.id.campus_address);
the exception occurs as your getView() returns null, it is not associated with the fragment's View. In fragment You have to always use the inflated view's reference.

Related

App Crashes on Splash Screen throwing Null Pointer

According to Playstore ANR & Crashes the app is throwing null pointer on SplashScreen oncreate. I've checked the functioning and it looks good at my end. Not all phones are crashing however are.
My SplashActivity.java
package com.example.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
public class SplashActivity extends AppCompatActivity {
String path = "";
String banner = "";
String title = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
if(getIntent().getExtras() != null){
Log.e("splash", "from push link");
path = getIntent().getExtras().getString("link");
banner = getIntent().getExtras().getString("bannerImage");
title = getIntent().getExtras().getString("title");
String link = String.valueOf(Html.fromHtml(Html.fromHtml(path).toString()));
String imgurl = String.valueOf(Html.fromHtml(Html.fromHtml(banner).toString()));
Log.e("link----", "link--" + link);
SharedPreferences pref = getApplicationContext().getSharedPreferences("Push", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
String pushtitle = pref.getString("pushtitle", "");
StringBuilder sb = new StringBuilder();
sb.append(pushtitle).append(title).append(",");
Log.e("pushtitle===========", sb.toString());
editor.putString("pushtitle", sb.toString());
String links = pref.getString("link", "");
StringBuilder sb2 = new StringBuilder();
sb2.append(links).append(link).append(",");
Log.e("link===========", sb2.toString());
editor.putString("link", sb2.toString());
String imgurlstr = pref.getString("imgurl", "");
StringBuilder sb3 = new StringBuilder();
sb3.append(imgurlstr).append(imgurl).append(",");
Log.e("imgurl===========", sb3.toString());
editor.putString("imgurl", sb3.toString());
editor.commit();
}
int secondsDelayed = 1;
new Handler().postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
if (path != "") {
Log.e("splash", "path==" + path);
intent.putExtra("link", String.valueOf(Html.fromHtml(Html.fromHtml(path).toString())));
}
startActivity(intent);
finish();
}
}, secondsDelayed * 1000);
}
}
The playstore crashes report as following.
java.lang.NullPointerException com.example.app.SplashActivity.onCreate
java.lang.RuntimeException: 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:1496) at com.android.internal.os.ZygoteInit.main
(ZygoteInit.java:1386) Caused by: java.lang.NullPointerException:
at java.io.StringReader. (StringReader.java:50) at
android.text.HtmlToSpannedConverter.convert (Html.java:758) at
android.text.Html.fromHtml (Html.java:245) at
android.text.Html.fromHtml (Html.java:188) at
com.example.app.SplashActivity.onCreate (SplashActivity.java:27)
at android.app.Activity.performCreate (Activity.java:6955) at
android.app.Instrumentation.callActivityOnCreate
(Instrumentation.java:1126) at
android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:2927
EDIT: Debugging the App I got the below error:
Log messages will follow once session has started...
I/art ( 3818): Not late-enabling -Xcheck:jni (already on) W/art
( 3818): Unexpected CPU variant for X86 using defaults: x86 W/System
( 3818): ClassLoader referenced unknown path:
/data/app/com.example.app-1/lib/x86 D/FirebaseApp( 3818):
com.google.firebase.auth.FirebaseAuth is not linked. Skipping
initialization. W/InstanceID/Rpc( 3818): Found 10012 D/FirebaseApp(
3818): com.google.firebase.crash.FirebaseCrash is not linked. Skipping
initialization. I/FA ( 3818): App measurement is starting up,
version: 10084 I/FA ( 3818): To enable debug logging run: adb
shell setprop log.tag.FA VERBOSE I/FA ( 3818): To enable faster
debug mode event logging run: I/FA ( 3818): adb shell setprop
debug.firebase.analytics.app com.example.app I/FirebaseInitProvider(
3818): FirebaseApp initialization successful W/art ( 3818): 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 E/splash ( 3818): from push link
D/AndroidRuntime( 3818): Shutting down VM E/AndroidRuntime( 3818):
FATAL EXCEPTION: main E/AndroidRuntime( 3818): Process:
com.example.app, PID: 3818 E/AndroidRuntime( 3818):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.app/com.example.app.SplashActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'int
java.lang.String.length()' on a null object reference
E/AndroidRuntime( 3818): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
E/AndroidRuntime( 3818): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
E/AndroidRuntime( 3818): at
android.app.ActivityThread.-wrap12(ActivityThread.java)
E/AndroidRuntime( 3818): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
E/AndroidRuntime( 3818): at
android.os.Handler.dispatchMessage(Handler.java:102) E/AndroidRuntime(
3818): at android.os.Looper.loop(Looper.java:154) E/AndroidRuntime(
3818): at android.app.ActivityThread.main(ActivityThread.java:6077)
E/AndroidRuntime( 3818): at java.lang.reflect.Method.invoke(Native
Method) E/AndroidRuntime( 3818): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
E/AndroidRuntime( 3818): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
E/AndroidRuntime( 3818): Caused by: java.lang.NullPointerException:
Attempt to invoke virtual method 'int java.lang.String.length()' on a
null object reference E/AndroidRuntime( 3818): at
java.io.StringReader.(StringReader.java:50) E/AndroidRuntime(
3818): at android.text.HtmlToSpannedConverter.convert(Html.java:758)
E/AndroidRuntime( 3818): at android.text.Html.fromHtml(Html.java:245)
E/AndroidRuntime( 3818): at android.text.Html.fromHtml(Html.java:188)
E/AndroidRuntime( 3818): at
com.example.app.SplashActivity.onCreate(SplashActivity.java:27)
E/AndroidRuntime( 3818): at
android.app.Activity.performCreate(Activity.java:6662)
E/AndroidRuntime( 3818): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
E/AndroidRuntime( 3818): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
E/AndroidRuntime( 3818): ... 9 more
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
if(getIntent().getExtras() != null && this.getIntent().getExtras().containsKey("yourKey")){
try {
Log.e("splash", "from push link");
path = getIntent().getExtras().getString("link");
banner = getIntent().getExtras().getString("bannerImage");
title = getIntent().getExtras().getString("title");
String link = String.valueOf(Html.fromHtml(Html.fromHtml(path).toString()));
String imgurl = String.valueOf(Html.fromHtml(Html.fromHtml(banner).toString()));
Log.e("link----", "link--" + link);
SharedPreferences pref = getApplicationContext().getSharedPreferences("Push", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
String pushtitle = pref.getString("pushtitle", "");
StringBuilder sb = new StringBuilder();
sb.append(pushtitle).append(title).append(",");
Log.e("pushtitle===========", sb.toString());
editor.putString("pushtitle", sb.toString());
String links = pref.getString("link", "");
StringBuilder sb2 = new StringBuilder();
sb2.append(links).append(link).append(",");
Log.e("link===========", sb2.toString());
editor.putString("link", sb2.toString());
String imgurlstr = pref.getString("imgurl", "");
StringBuilder sb3 = new StringBuilder();
sb3.append(imgurlstr).append(imgurl).append(",");
Log.e("imgurl===========", sb3.toString());
editor.putString("imgurl", sb3.toString());
editor.commit();
} catch (NullPointerException e ) {
path = "";
banner = "";
title = "";
}
}

Whats wrong with my Android Studio App keep stopping?

For some reason my app is keep coming up with "app name" has stopped. I have added the error log below but cannot work out what the problem is. I have tried many times to figure it out but still not getting anywhere. Hopefully you can understand the error log.
04-29 12:20:07.016 1296-2069/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
04-29 12:20:07.019 1694-4363/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
04-29 12:20:07.019 1694-4363/system_process D/OpenGLRenderer: Swap behavior 1
04-29 12:20:07.019 1694-4363/system_process W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
04-29 12:20:07.019 1694-4363/system_process D/OpenGLRenderer: Swap behavior 0
04-29 12:20:07.020 1296-2069/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
04-29 12:20:07.070 1296-2069/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
04-29 12:20:07.465 1694-1712/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{6dd3b2c u0 thomashaywoodproductions.buildaempiredesign/.GameLogin t154 f}
04-29 12:20:07.481 1296-2069/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x333 imply creation of host color buffer
[ 04-29 12:20:07.485 1694: 1712 D/ ]
HostConnection::get() New Host Connection established 0x96c6e480, tid 1712
04-29 12:20:07.521 1296-1296/? E/EGL_emulation: tid 1296: eglCreateSyncKHR(1669): error 0x3004 (EGL_BAD_ATTRIBUTE)
04-29 12:20:07.558 1296-1353/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
04-29 12:20:07.559 1296-2069/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
04-29 12:20:07.560 1694-1712/system_process D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread)
04-29 12:20:07.569 1296-1353/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
04-29 12:20:07.586 1296-2069/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
04-29 12:20:07.594 1296-1353/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
04-29 12:20:07.601 1296-2069/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
04-29 12:20:07.687 2343-2343/com.google.android.googlequicksearchbox:search I/OptInState: There is a new client and it does not support opt-in. Dropping request.
04-29 12:20:07.692 2343-2343/com.google.android.googlequicksearchbox:search I/MicroDetectionWorker: Micro detection mode: [mDetectionMode: [1]].
04-29 12:20:07.693 2343-2343/com.google.android.googlequicksearchbox:search I/AudioController: Using mInputStreamFactoryBuilder
04-29 12:20:07.700 2343-18556/com.google.android.googlequicksearchbox:search I/MicroRecognitionRunner: Starting detection.
04-29 12:20:07.701 2343-9163/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting com.google.android.apps.gsa.staticplugins.z.c#6dbc476
04-29 12:20:07.702 1305-1775/? W/APM_AudioPolicyManager: getInputForAttr() failed opening input: samplingRate 16000, format 1, channelMask 10
04-29 12:20:07.702 2343-9163/com.google.android.googlequicksearchbox:search E/AudioRecord: Could not get audio input for session 4025, record source 1999, sample rate 16000, format 0x1, channel mask 0x10, flags 0
04-29 12:20:07.703 2343-9163/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -22.
04-29 12:20:07.703 2343-9163/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
04-29 12:20:07.703 2343-9163/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started com.google.android.apps.gsa.staticplugins.z.c#6dbc476
04-29 12:20:07.703 2343-9163/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
04-29 12:20:07.704 2343-2343/com.google.android.googlequicksearchbox:search I/MicroDetectionWorker: onReady
04-29 12:20:07.706 2343-18556/com.google.android.googlequicksearchbox:search W/SpeechLevelGenerator: Really low audio levels detected. The audio input may have issues.
04-29 12:20:07.715 2343-18556/com.google.android.googlequicksearchbox:search I/MicroRecognitionRunner: Detection finished
04-29 12:20:07.714 2343-9163/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_close com.google.android.apps.gsa.staticplugins.z.c#6dbc476
04-29 12:20:07.715 2343-18556/com.google.android.googlequicksearchbox:search W/ErrorReporter: reportError [type: 211, code: 524300]: Error reading from input stream
04-29 12:20:07.716 2343-2485/com.google.android.googlequicksearchbox:search I/MicroRecognitionRunner: Stopping hotword detection.
04-29 12:20:07.716 2343-18556/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream
at com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)
at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)
at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)
at java.io.InputStream.read(InputStream.java:101)
at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)
at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85) 
04-29 12:20:07.717 2343-18556/com.google.android.googlequicksearchbox:search I/AudioController: internalShutdown
04-29 12:20:07.718 2343-2343/com.google.android.googlequicksearchbox:search I/MicroDetector: Keeping mic open: false
04-29 12:20:07.718 2343-2343/com.google.android.googlequicksearchbox:search I/MicroDetectionWorker: #onError(false)
04-29 12:20:07.718 2343-18555/com.google.android.googlequicksearchbox:search I/DeviceStateChecker: DeviceStateChecker cancelled
04-29 12:20:08.132 1694-1719/system_process D/gralloc_ranchu: gralloc_unregister_buffer: exiting HostConnection (is buffer-handling thread)
04-29 12:20:08.134 1694-1719/system_process W/WindowManager: Failed looking up window
java.lang.IllegalArgumentException: Requested window android.view.ViewRootImpl$W#f29c3c4 does not exist
at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:9415)
at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:9406)
at com.android.server.wm.WindowManagerService.removeWindow(WindowManagerService.java:2387)
at com.android.server.wm.Session.remove(Session.java:193)
at android.view.ViewRootImpl.dispatchDetachedFromWindow(ViewRootImpl.java:3290)
at android.view.ViewRootImpl.doDie(ViewRootImpl.java:5917)
at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3626)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.os.HandlerThread.run(HandlerThread.java:61)
at com.android.server.ServiceThread.run(ServiceThread.java:46)
04-29 12:20:08.146 2216-2360/com.google.android.apps.nexuslauncher W/OpenGLRenderer: Incorrectly called buildLayer on View: ShortcutAndWidgetContainer, destroying layer...
Here is the file code
public class GameLogin extends AppCompatActivity {
SharedPreferences sharedPref = GameLogin.this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
EditText etEmail;
EditText etPassword;
Button bLogin;
TextView registerLink;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_login);
etEmail = (EditText) findViewById(R.id.etEmail);
etPassword = (EditText) findViewById(R.id.etPassword);
bLogin = (Button) findViewById(R.id.bLogin);
registerLink = (TextView) findViewById(R.id.tvRegisterHere);
registerLink.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent registerIntent = new Intent(GameLogin.this, GameRegister.class);
GameLogin.this.startActivity(registerIntent);
}
});
bLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
final String email = etEmail.getText().toString();
final String password = etPassword.getText().toString();
Response.Listener<String> responceListener = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponce = new JSONObject(response);
boolean success = jsonResponce.getBoolean("success");
if (success){
editor.putString(getString(R.string.player_data_gamename), jsonResponce.getString("gamename"));
editor.putString(getString(R.string.player_data_startdate), jsonResponce.getString("startdate"));
editor.putInt(getString(R.string.player_data_userid), jsonResponce.getInt("userid"));
editor.commit();
Intent intent = new Intent(GameLogin.this, GameUserArea.class);
GameLogin.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(GameLogin.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(email, password, responceListener);
}
});
}
}

ListAdapter does not work

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.

NullPointerException on getResources().getDisplayMetrics().density

Context
I'm working on a small test code right now. It selects an image, resizes it to fit the screen based on the screen density. While it does this, it makes a copy of the image at the size it would be in an xxhdpi display, and the converts into a Bitmap, then into a String. The String is then carried through an Intent to the next screen where the String is turned back into a Bitmap and then placed in an ImageButton.
This worked fine until I added in a chunk of code to resize the image given by the string based on the density. The odd thing is I copied and pasted the DPI() method from another activity and there were no issues in that activity.
Code
package com.example.zachary.imagetesting.Resizing;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import com.example.zachary.imagetesting.R;
public class PictureDecoded extends Activity {
TextView Text;
ImageButton Image;
String string;
Bitmap picture;
public float DPI(){return getResources().getDisplayMetrics().density;}
float dpi = DPI() * 180;
int size = (int) dpi;
public Bitmap Pic(String string){
try{
byte[] b = Base64.decode(string, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
return bitmap;
} catch (Exception e) {
e.getMessage();
return null;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resizing);
string = getIntent().getStringExtra("String");
Image = (ImageButton) findViewById(R.id.image);
Text = (TextView) findViewById(R.id.text);
picture = Pic(string);
Image.setImageBitmap(Bitmap.createScaledBitmap(picture,size,size,false));
}
public void next(View view){ }
// I also tried addring DPI() here as well to no success.
//public float DPI(){return getResources().getDisplayMetrics().density;}
}
Error Log
01-15 19:55:17.104 30570-30570/com.example.zachary.imagetesting D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
01-15 19:55:17.194 30570-30570/com.example.zachary.imagetesting E/Bitmap String:: /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAGVAhwDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA
AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK
U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3
uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDuKKKK
/wAVz/UgKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKK
ACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA
KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAo
oooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACii
igAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKK
ACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA
KKKKACiiigAooooAKKKKACiiigA45GemM+3XGeTjOOPx5ODkruPAuv6DpWppYeMtHj1zwhqk0MOt
2qxqur2EO9h/bHhy/UpcadqtlkTeXFKLTU4l+wanBNA0RTtPjP8ABnU/hRqdldW102ueC/EUa3nh
XxKkaKl1bzo1zFYXqoxEWoQ2jQziQKltf2zpe2aoRd2cPBLMaFLH0svxF6NbEwnPBSk17LFqko+2
p056cuIopqc6EleVKUalKdRRrKMe0ipqnLRyTcG9p2spJa6SW/K9WtU3advE6KKK7ywooooAKKKK
ACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA
KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK0NM0jV9buB
Z6LpWo6vdHAFrpdhd39yckgYgtIZpecf3fT1yfcvDv7Lnxx8Rwpcx+Dn0a3fG2XxFqOn6TLg5wWs
J7htTQcZw1lu68E43cOLzLLcAr47H4TCLS31jE0aLe6SjGpUUpN8rsopvye7iVSnBXnOEF3lJR79
3/dfn69fn2ivtPTP2HPiTcgHVfFXhHSxgErA2salKOuRtOnWMeRgYImYHPJGDXWw/sG6gV/0j4oW
cb4HEPhCeZc5OfmfxJAQMYx8pJJOQNvPh1ON+FKTtLOaLa/590MZWXb4qOHqRf3v9TB43CK968dO
0Zvqlpyxafffa9z8/wCivvO8/YQ8RIrHT/iPo1w38K3nh6/s1PJxuaHU74rkY6I2CSPm25PBap+x
b8Y7EObCfwprQXO1bTWZ7OZ+Wxgatp9jApYAcG6wDn5sAtV0eM+Fq+kM6wsdv40a+GXXVvEUqSS0
1bemt72d3HGYWW1eH/b3NHy+0lf+vU+SaK9G8VfCH4oeCXlHiXwPr9hDCCXv47F9Q0kKCRu/tbTD
e6eBxnDXQbGMgE8+cjB5ByPUexx6nv8ArxknmvoMPicNi6aq4XEUcTSdrVKFWnVptO9rTpylHXld
tfn33jKM1eEoyXeLUl16pvt+ers7lfqF8ItCX43/ALKY8H6y8VxqGnHV9A0bULtRI2n6no85vPDV
wJOZIlsrS+06wkZCGbTvtFq2YpJA35e1+q37EW//AIVBrQb/AFf/AAnmseX97J/4p/wnv6nG3OCN
v8RfJyOfifEOc6GR4fG0ZezxOBzTB4nDVUlzQqReIirPezupTje0koqV0cWPbjh1OOkqdWnKL6p3
qLTtsm++zva7/LC5triyurmyu4mhurOea1uYWHzxXEEssM0TDqGjkiZWB5zkdiagr2T9oPQ4/Dvx
s+I+nRALFJrp1aJQOAuu2lvrbqOeiy38igdgGHG3nxuvs8BiY43A4PGR+HFYXD4mPkq9JVEt+zXV
9NW1JvtpyU6cJracIyXpJN9/T/PVtFFFFdRQUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFF
FABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUU
AFFFFABRRRQAUUUUAFH+f5+/t/Png57nwD8NvGfxN1f+x/B+jzahLGEa8vHJg0vTYXZlE+pag6GK
1Qlfkj+e6nO9bW3mkQof0q+E37JHgbwOINW8X+T428RKYZV+22+PD2mzIS2LHS5VYXrpIMrean5m
4CKWGxtZM181n3FeUcPxccVVdbF8t6eBw7jOvK/wyqXko0IPdSqtOUVJ04TkuU5q+Lo4dNTledtK
cdZP4rX1tFOyacnreVruPvfA3w3/AGfvif8AFBUu9E0UabopkRG8Q6+0unaWysTueyUwSXmqBVGd
2nW08AkBimuImJNfdvgH9jP4beGzHeeLrm98cX4jTNvdmTS9BilAfc8enWM32u4weAt9qU1u6lS9
mpyp+wFVUAVFCqAFAUAAKoIUADgADhQOAMADApa/G844+z7NHUp0K39mYWV0qWDlKNdxu7e0xbar
OXnR9jFqTjKDUU341XMMRUuoy9nF9IfFu3rP4uvSytdNO9zG0Lw54f8AC2nrpXhvRdM0LTkwRZaT
Y21halhxveG1iiSSQ4BMjhnJwSxIJOz/AJ/n7/5yeTzkor4qc51JynUnKc5tynOcnKcpdZSlKTcm
+rbb829Tibbbbbbe7bd2+7bbf5+reoUUUVIgooooAMf4Z5zjnv1/+sT1GQfDfH37Onwm+IMd7LqH
hq20fWLs7/8AhIfDqx6Vqqz5YmeZYonsNQd8gSHUrK6Yj7jo43V7lRXVg8bjMvrKvgcVXwtZW/eU
Ks6cmoybUZcskpwvq4T5oSTalFq97hOdN81OcoPvFtXt3s9V5PTvc/I34r/so+Pfh6l7rHh/d408
L2y+c93YW7R67YQguJG1HRlMrzRQgAveaZLdRiMNPcwWkQc19r/shaNcaR8DtFmuYmhfW9W17W1R
1KsYZL4aZbSEH+Ga20mKeMnJMcgOSDX03gf5/H/Pr05OKZHHHFGsUSpFGoCqqIERRuP3UQAAclsK
PzJ4+kzXjLMs6yWnlWYU6VSrTxVKu8bBeznVp06deHs6tGK9nzuVRTdSlyRaUYOjf94+mrjKlagq
NRJtSUvaLRtRUrJxStf3m7rva29/xq/akvY7749+P3iZWS2m0KyLD/n
01-15 19:55:17.194 30570-30570/com.example.zachary.imagetesting I/Timeline: Timeline: Activity_launch_request id:com.example.zachary.imagetesting time:50420468
01-15 19:55:17.244 30570-30570/com.example.zachary.imagetesting D/AndroidRuntime: Shutting down VM
01-15 19:55:17.244 30570-30570/com.example.zachary.imagetesting E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.zachary.imagetesting, PID: 30570
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.zachary.imagetesting/com.example.zachary.imagetesting.Resizing.PictureDecoded}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2546)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:90)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
at com.example.zachary.imagetesting.Resizing.PictureDecoded.DPI(PictureDecoded.java:20)
at com.example.zachary.imagetesting.Resizing.PictureDecoded.<init>(PictureDecoded.java:21)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1650)
at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2536)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758) 
at android.app.ActivityThread.access$900(ActivityThread.java:177) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:5942) 
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:1399) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) 
The large block of text is the String converted from Bitmap that was passed to the Activity. I left it in just in case it was useful. The line before the large block of text was the button click that started the intent to the activity which crashes due to NullPointerException.
I can add the other activities on request, but since it worked before I tried resizing based on screen density I didn't feel it was needed.
An Activity's base Context won't have been setup until after onCreate() has finished executing. Simply move the initialization of dpi to onCreate() after super.onCreate() has been called.

NullPointerException when I try to capture an image (built-in camera) and save it to a file [duplicate]

This question already has answers here:
Android Camera : data intent returns null
(11 answers)
Closed 8 years ago.
Here's what the app does - User clicks button (to take a picture) on Activity A, the captured image gets set as on an ImageView in Activity A, and then the user clicks a "save" button, which takes him/her to Activity B, where the image they took gets displayed (on an ImageView in Activity B)
In order to do this I am trying to find a way to save the image. I tried many different things, but I keep getting a NullPointerException. Here is my code:
I highlighted the area where I think the error is:
public void onClick(View view) {
switch (view.getId()) {
case R.id.take_picture_button:
takePic = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (takePic.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile(); //so photoFile = the file we created up top
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
**takePic.putExtra(MediaStore.EXTRA_OUTPUT**, //extra_output is just the name of the Intent-extra used to indicate a content resolver Uri to be used to store the requested image or video.
**Uri.fromFile(photoFile));**
startActivityForResult(takePic, cameraData);
}
And here is the code for the onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == cameraData && resultCode == RESULT_OK) {
mReturningWithResult = true;
extras = data.getExtras();
And here is where I set my image view to my captured image (on Activity A)
#Override
protected void onPostResume() {
super.onPostResume();
if (mReturningWithResult) {
foodImage = (Bitmap) extras.get("data");
foodImageView.setImageBitmap(foodImage);
}
mReturningWithResult = false;//resetting it for next time
}
Here is the logcat (sorry I'm new to this)
10-15 20:58:59.612 32005-32005/com.example.nikhil.foodshark D/OpenGLRenderer﹕ Enabling debug mode 0
10-15 20:59:21.545 32005-32005/com.example.nikhil.foodshark I/PersonaManager﹕ getPersonaService() name persona_policy
10-15 20:59:23.127 32005-32005/com.example.nikhil.foodshark W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
10-15 20:59:33.678 32005-32005/com.example.nikhil.foodshark D/AndroidRuntime﹕ Shutting down VM
10-15 20:59:33.678 32005-32005/com.example.nikhil.foodshark W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41a39da0)
10-15 20:59:33.678 32005-32005/com.example.nikhil.foodshark E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.nikhil.foodshark, PID: 32005
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.nikhil.foodshark/com.example.nikhil.foodshark.NewDish}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3680)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
at android.app.ActivityThread.access$1400(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.nikhil.foodshark.NewDish.onActivityResult(NewDish.java:144)
at android.app.Activity.dispatchActivityResult(Activity.java:5650)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3676)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
            at android.app.ActivityThread.access$1400(ActivityThread.java:174)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5593)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)
10-15 20:59:56.353 32005-32005/com.example.nikhil.foodshark I/Process﹕ Sending signal. PID: 32005 SIG: 9
10-15 20:59:56.613 378-378/com.example.nikhil.foodshark I/PersonaManager﹕ getPersonaService() name persona_policy
10-15 20:59:56.723 378-378/com.example.nikhil.foodshark I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:381>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050_msm8960_refs/tags/AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050__release_AU ()
OpenGL ES Shader Compiler Version: 17.01.12.SPL
Build Date: 03/28/14 Fri
Local Branch:
Remote Branch: refs/tags/AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050
Local Patches: NONE
Reconstruct Branch: NOTHING
10-15 20:59:56.763 378-378/com.example.nikhil.foodshark D/OpenGLRenderer﹕ Enabling debug mode 0
Do you guys know a way I can fix this? Thank you!
You are passing MediaStore.EXTRA_OUTPUT, in which case, the intent field in onActivityResult can be null.
The solution is to just use the photo file you created, and passed as uri in the putExtra
So instead of trying to get the photo file location from the intent, just use Uri.fromFile(photoFile)
replace
extras = data.getExtras();
...
with
`Uri.fromFile(photoFile)`
or just use photoFile if that is what you want...just dont rely on intent data

Categories

Resources