AndroidRuntime关闭致命异常:主Android Studio 2.2

时间:2016-09-25 04:17:49

标签: android android-studio

在应用上工作,只有在手机上运行时遇到问题。

这是运行信息:

09/24 21:02:00: Launching app
Cold swapped changes.
$ adb shell am start -n "com.example.crow.page3/com.example.crow.page3.Page3main" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Connected to process 1154 on device oneplus-a0001-793b4d36
I/art: Late-enabling -Xcheck:jni
W/System: ClassLoader referenced unknown path: /data/app/com.example.crow.page3-2/lib/arm
I/InstantRun: Instant Run Runtime started. Android package is com.example.crow.page3, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.example.crow.page3-2/lib/arm
I/LoadedApk: No resource references to update in package common
I/LoadedApk: No resource references to update in package com.blinq.theme.CleanUI.blue
I/LoadedApk: No resource references to update in package com.blinq.theme.CleanUI.blue
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
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.crow.page3, PID: 1154
                  Theme: themes:{default=overlay:com.blinq.theme.CleanUI.blue, iconPack:com.blinq.theme.CleanUI.blue, fontPkg:com.blinq.theme.CleanUI.blue, com.android.systemui=overlay:com.blinq.theme.CleanUI.blue, com.android.systemui.navbar=overlay:com.blinq.theme.CleanUI.blue}
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.crow.page3/com.example.crow.page3.Page3main}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TabHost.setup()' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)
                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5461)
                      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.TabHost.setup()' on a null object reference
                      at com.example.crow.page3.Page3main.onCreate(Page3main.java:54)
                      at android.app.Activity.performCreate(Activity.java:6251)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510) 
                      at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:148) 
                      at android.app.ActivityThread.main(ActivityThread.java:5461) 
                      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) 
I/Process: Sending signal. PID: 1154 SIG: 9
Application terminated.

我已经尝试了好几件事并多次使用代码。下面是com.example.crow.page3.Page3main:

的代码
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Button;
import android.widget.TabHost;
import android.app.Activity;


import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

public class Page3main extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    EditText nameTxt, phoneTxt, emailTxt, addressTxt;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        //add new contact:--------------------------------------------------
        setContentView(R.layout.activity_page3main);
        nameTxt = (EditText) findViewById(R.id.txtName);
        phoneTxt = (EditText) findViewById(R.id.txtPhone);
        emailTxt = (EditText) findViewById(R.id.txtEmail);
        addressTxt = (EditText) findViewById(R.id.txtAddress);

        //define tabs for from add contact tabs
        TabHost tabHost = (TabHost) findViewById(R.id.tabHost);

        tabHost.setup();

        TabHost.TabSpec tabSpec = tabHost.newTabSpec("creator");
        tabSpec.setContent(R.id.tabAddContact);
        tabSpec.setIndicator("Creator");
        tabHost.addTab(tabSpec);

        tabSpec = tabHost.newTabSpec("list");
        tabSpec.setContent(R.id.tabContactList);
        tabSpec.setIndicator("List");
        tabHost.addTab(tabSpec);

        final Button addBtn = (Button) findViewById(R.id.btnAdd);

        //What happens on :
        nameTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int i, int i2, int i3) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i2, int i3) {
                //check if there was input in the text
                addBtn.setEnabled(!nameTxt.getText().toString().trim().isEmpty());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        //-------------------------------------------------------------------


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.page3main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        FragmentManager fragmentManager = getFragmentManager();

        if (id == R.id.nav_logbook) {
            fragmentManager.beginTransaction()
                    .replace(R.id.content_frame, new FirstFragmentLogbook()).commit();
        } else if (id == R.id.nav_contacts) {
            fragmentManager.beginTransaction()
                    .replace(R.id.content_frame, new SecondFragmentContacts()).commit();
        } else if (id == R.id.nav_map) {
            fragmentManager.beginTransaction()
                    .replace(R.id.content_frame, new ThirdFragmentMap()).commit();
        } else if (id == R.id.nav_site_info) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Page3main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
}

任何想法都将不胜感激。感谢

布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    tools:context=".Page3main"
    android:orientation="vertical"
    android:baselineAligned="false"
    android:weightSum="1">


    <TabHost
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/tabHost"
        android:layout_gravity="left|center_vertical">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
            </TabWidget>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

                <LinearLayout
                    android:id="@+id/tabContactList"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">

                    <TextView
                        android:text="TextView"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:id="@+id/textView3"
                        android:textAppearance="@android:style/TextAppearance.Material.Large"
                        android:layout_margin="10dp"
                        android:layout_gravity="center"
                        android:textAlignment="center" />

                    <ListView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/tabAddContact"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical">

                    <TextView

                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:id="@+id/lblCreatorTitle"
                        android:layout_gravity="center"
                        android:textAppearance="?android:attr/textAppearanceLarge"
                        android:text="New Contact"
                        android:layout_margin="10dp" />

                    <EditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:ems="10"
                        android:id="@+id/txtName"
                        android:hint="Name"
                        android:inputType="textPersonName"
                        android:layout_gravity="center"
                        android:layout_weight="0.10"
                        android:drawableStart="@drawable/ic_contacts_black_24dp" />

                    <EditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:inputType="phone"
                        android:ems="10"
                        android:id="@+id/txtPhone"
                        android:hint="Phone"
                        android:layout_gravity="center"
                        android:layout_weight="0.10"
                        android:drawableStart="@drawable/ic_call_black_24dp" />

                    <EditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:inputType="textEmailAddress"
                        android:ems="10"
                        android:id="@+id/txtEmail"
                        android:hint="Email"
                        android:layout_gravity="center"
                        android:layout_weight="0.10"
                        android:drawableStart="@drawable/ic_email_black_24dp" />

                    <EditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:inputType="textPostalAddress"
                        android:ems="10"
                        android:id="@+id/txtAddress"
                        android:hint="Address"
                        android:layout_gravity="center"
                        android:layout_weight="0.10"
                        android:drawableStart="@drawable/ic_place_black_24dp" />

                    <Button
                        android:text="Add"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:id="@+id/btnAdd"
                        android:textAlignment="center"
                        android:layout_gravity="center" />
                </LinearLayout>

            </FrameLayout>
        </LinearLayout>
    </TabHost>

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

根据您的日志,您在android.widget.TabHost.setup()

处获得空指针异常

问题可能在以下代码行中

//define tabs for from add contact tabs
    TabHost tabHost = (TabHost) findViewById(R.id.tabHost);

    tabHost.setup();

在上面的代码中,R.id.tabHost返回一个空指针。请检查您的布局中是否已定义此ID。此外,如果您发布此ID的代码,我可以进一步帮助您。

修改

好的问题是你在使用findViewById加载了标签后调用了setup方法。在通过findViewByid加载制表符之前,必须调用setup方法。

请参阅开发人员文档的下方屏幕截图。 enter image description here

以下是文档页面的link。我希望这会有所帮助。