Android app crashes when showing/hiding visiblity

2019-03-07 04:24发布

问题:

I've been trying to create my first android app, and yes... got stuck up with an app crash...

I had two ImageViews in my fragment (main), overlapping imageview 1 with imageview2 in a relative layout. What I wanted to do was, imageview1 (not imageview 2) should be showing up if there's an Internet connection. and vice versa if no internet connection. As per a tutorial, i created a separate class for detecting connection:

   package com.mypackage.myapp;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context){
        this._context = context;
    }

    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
          return false;
    }
}

And called up the class in my mainactivity.class, made an if statement for two instances of connection (connected/disconnected) with a boolean variable... finally, i used setVisibility() for each ImageViews in the if statement in onCreate(). here's the code:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    } 
    Intent cd = getIntent();
    ConnectionDetector cdr = new ConnectionDetector(getApplicationContext());
    boolean isInternetPresent = cdr.isConnectingToInternet();
    ImageView glss2 = (ImageView)findViewById(R.id.glass2);
    ImageView glss1 = (ImageView) findViewById(R.id.glass1);
    if (isInternetPresent) {
        glss1.setVisibility(View.VISIBLE);
        glss2.setVisibility(View.GONE);
    } else {
       glss1.setVisibility(View.GONE);
       glss2.setVisibility(View.VISIBLE);
    }
}

Additionally, if you want my layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/backrepeatlinen"
tools:context="com.mypackage.myapp.MainActivity$PlaceholderFragment" >

<ImageView
    android:id="@+id/glass1"
    android:layout_width="160dp"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:src="@drawable/glass" android:contentDescription="@string/hello_world"/>

<ImageView
    android:id="@+id/glass2"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/glass1"
    android:layout_centerHorizontal="true"
    android:contentDescription="@string/hello_world"
    android:src="@drawable/broken" />

Everytime, when I run the program in my tablet, it crashes at the activity. i tried removing the connection detector and if statement thing, the activity moves well.

Edit: the only problem is on the setVisiblity() in the if statement, because when removing it, everything else works properly. Is it possible to solve? or can we controll the visiblity of two imageviews with a different method?.

logcat:

05-21 11:05:38.432: E/filePathInTheme(23435): fallback to res
05-21 11:05:38.462: E/filePathInTheme(23435): fallback to res
05-21 11:05:38.482: E/filePathInTheme(23435): fallback to res
05-21 11:05:38.652: E/filePathInTheme(23435): fallback to res
05-21 11:05:38.802: I/Adreno200-EGLSUB(23435): <ConfigWindowMatch:2081>: Format RGBA_8888.
05-21 11:05:38.812: D/memalloc(23435): /dev/pmem: Mapped buffer base:0x50c32000 size:11960320 offset:10485760 fd:54
05-21 11:05:39.122: D/memalloc(23435): /dev/pmem: Mapped buffer base:0x51a3b000 size:13434880 offset:11960320 fd:57
05-21 11:05:41.542: E/filePathInTheme(23435): fallback to res
05-21 11:05:41.572: W/dalvikvm(23435): threadid=1: thread exiting with uncaught exception (group=0x40a659f0)
05-21 11:05:41.582: E/AndroidRuntime(23435): FATAL EXCEPTION: main
05-21 11:05:41.582: E/AndroidRuntime(23435): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lemonaade.watchr/com.lemonaade.watchr.MainActivity}: java.lang.NullPointerException
05-21 11:05:41.582: E/AndroidRuntime(23435):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1961)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1986)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1152)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at android.os.Looper.loop(Looper.java:137)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at android.app.ActivityThread.main(ActivityThread.java:4450)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at java.lang.reflect.Method.invokeNative(Native Method)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at java.lang.reflect.Method.invoke(Method.java:511)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at dalvik.system.NativeStart.main(Native Method)
05-21 11:05:41.582: E/AndroidRuntime(23435): Caused by: java.lang.NullPointerException
05-21 11:05:41.582: E/AndroidRuntime(23435):    at com.lemonaade.watchr.MainActivity.onCreate(MainActivity.java:35)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at android.app.Activity.performCreate(Activity.java:4465)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-21 11:05:41.582: E/AndroidRuntime(23435):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1925)
05-21 11:05:41.582: E/AndroidRuntime(23435):    ... 11 more

thanks.

回答1:

You should move

ImageView glss1 = (ImageView) findViewById(R.id.glass1);
ImageView glss2 = (ImageView)findViewById(R.id.glass2);

under onCrete(....) after setContentView(R.layout.activity_main);



回答2:

please move this code below setContentView().

ImageView glss1 = (ImageView) findViewById(R.id.glass1);
ImageView glss2 = (ImageView)findViewById(R.id.glass2);

You are finding view before you set the content of the view. thats why it is not working.



回答3:

Write the code to the fragment onCreateView() of PlaceholderFragment() after inflating your xml .

ImageView glss1 = (ImageView) findViewById(R.id.glass1);
ImageView glss2 = (ImageView)findViewById(R.id.glass2);

Make sure you have added Following Permission in your Manifest file

 <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


回答4:

Since the layout is your fragment layout and not activity layout, the solution from a couple of other answers of moving the findViewById() to onCreate() after setContentView() still won't work.

Instead, move the code to the PlaceholderFragment onCreateView(), using getActivity() for Context and calling rootView.findViewById() on the inflated rootView layout.

See NullPointerException accessing views in onCreate() for more.