显示/隐藏ImageView的可见性时,Android应用程序崩溃

时间:2014-05-20 08:15:37

标签: android if-statement crash android-imageview

我一直在尝试创建我的第一个Android应用程序,是的...因应用程序崩溃而陷入困境......

我的片段(主要)中有两个ImageView,在相对布局中将imageview2与imageview2重叠。我想要做的是,如果有互联网连接, imageview1(不是imageview 2)应该出现。反之亦然,如果没有互联网连接。根据教程,我创建了一个单独的类来检测连接:

   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;
    }
}

在mainactivity.class中调用了这个类,用一个布尔变量为两个连接实例(连接/断开连接)做了一个if语句...最后,我在if语句中为每个ImageViews使用了setVisibility()的onCreate()。这是代码:

@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);
    }
}

此外,如果您需要我的布局文件

<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" />

每次,当我在平板电脑上运行程序时,它会在活动中崩溃。我尝试删除连接检测器和if语句,活动进展顺利。

编辑:唯一的问题是if语句中的 setVisiblity(),因为删除它时,其他一切都能正常工作。有可能解决吗?或者我们可以用不同的方法控制两个图像视图的可见性吗?

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

感谢。

4 个答案:

答案 0 :(得分:1)

你应该移动

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

之后的setContentView(R.layout.activity_main);

答案 1 :(得分:1)

请将此代码移至setContentView().

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

在设置视图内容之前,您正在查找视图。这就是为什么它不起作用。

答案 2 :(得分:0)

由于布局是您的片段布局而不是活动布局,因此在findViewById()之后将onCreate()移动到setContentView()的其他几个答案的解决方案仍然不起作用。< / p>

相反,请将代码移至PlaceholderFragment onCreateView()getActivity()使用Context并在充气的rootView.findViewById()布局上调用rootView

参见NullPointerException accessing views in onCreate()  更多。

答案 3 :(得分:0)

在给xml充气后,将代码写入onCreateView()的片段PlaceholderFragment()

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

确保您在清单文件中添加了以下权限

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