使用布局时出现NullPointerException

时间:2016-08-02 21:27:43

标签: java android nullpointerexception

我可以毫无问题地在模拟器上运行我的应用程序,但是当我尝试在手机上播放时出现此错误

  

"无法启动活动ComponentInfo {br.com.pedro.pedrodaumas / br.com.pedro.pedrodaumas.MainActivity}:java.lang.NullPointerException:尝试调用虚方法' void android。 widget.ListView.setAdapter(android.widget.ListAdapter)'在空对象引用"。

据我所知,我应该能够通过我的activity_main访问movieListView = (ListView) findViewById(R.id.movieListView);,就像我拥有的​​那样:

<include android:id="@+id/content"
    layout="@layout/content_main" />

所以我不确定为什么我会收到此错误。

MainActivity.java

package br.com.pedro.pedrodaumas;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private List<Movie> movieList = new ArrayList<>();
    private MovieArrayAdapter movieArrayAdapter;
    private ListView movieListView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        movieListView = (ListView) findViewById(R.id.movieListView);
        movieArrayAdapter = new MovieArrayAdapter(this, movieList);
        movieListView.setAdapter(movieArrayAdapter);
        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) {
                TextInputEditText search_bar;
                search_bar = (TextInputEditText) findViewById(R.id.search_bar);
                URL url = createURL(search_bar.getText().toString());
                if(url != null){
                    dismissKeyboard(search_bar);
                    GetMovieTask getLocalMovieTask = new GetMovieTask();
                    getLocalMovieTask.execute(url);
                }else {
                    Snackbar.make(findViewById(R.id.coordinatorLayout), R.string.invalid_url,
                            Snackbar.LENGTH_LONG).show();
                }

            }
        });
        movieListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    default:
                        Movie review = movieArrayAdapter.getItem(position);
                        Intent nextActivity = new Intent(MainActivity.this, ShortReview.class);
                        nextActivity.putExtra("summary", review.getsummary());
                        startActivity(nextActivity);
                        break;
                }
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, 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();


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

        return super.onOptionsItemSelected(item);
    }


    private void dismissKeyboard (View view){
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(),0);
    }

    private URL createURL (String movie){
        String apiKey = getString (R.string.api_key);
        String baseUrl = getString(R.string.nyt_url);
        try{
            String urlString = baseUrl + "?api_key=" + apiKey + "&query=" + URLEncoder.encode (movie, "UTF-8");
            return new URL(urlString);
        }
        catch( Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private class GetMovieTask extends AsyncTask<URL, Void, JSONObject> {
        @TargetApi(Build.VERSION_CODES.KITKAT)
        @Override
        protected JSONObject doInBackground(URL... params) {
            HttpURLConnection connection = null;
            try {
                connection = (HttpURLConnection) params[0].openConnection();
                int response = connection.getResponseCode();
                if (response == HttpURLConnection.HTTP_OK){
                    StringBuilder builder = new StringBuilder ();
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))){
                        String line;
                        while ((line = reader.readLine()) != null){
                            builder.append(line);
                        }
                    }
                    catch (IOException e){
                        Snackbar.make(findViewById(R.id.coordinatorLayout), R.string.read_error, Snackbar.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                    return new JSONObject(builder.toString());
                }
            }
            catch (Exception e){
                Snackbar.make(findViewById(R.id.coordinatorLayout), R.string.connect_error, Snackbar.LENGTH_LONG).show();
                e.printStackTrace();
            }
            finally{
                if (connection != null){
                    connection.disconnect();
                }
            }
            return null;
        }
        protected void onPostExecute(JSONObject movie) {
            convertJSONToArrayList (movie);
            movieArrayAdapter.notifyDataSetChanged();
            movieListView.smoothScrollToPosition(0);
        }
    }

    private void convertJSONToArrayList (JSONObject forecast){
        movieList.clear();
        try{
            JSONArray results = forecast.getJSONArray("results");
            for (int i = 0; i < results.length(); i++) {
                JSONObject movie = results.getJSONObject(i);
                if(movie.isNull("multimedia")){
                    movieList.add(new Movie(movie.getString("display_title"),
                            movie.getString("publication_date"),
                            "image", movie.getString("summary_short")));
                }else {
                    JSONObject multimedia = movie.getJSONObject("multimedia");
                    movieList.add(new Movie(movie.getString("display_title"),
                            movie.getString("publication_date"),
                            multimedia.getString("src"), movie.getString("summary_short")));
                }
            }
            if(results.length() == 0){
                Snackbar.make(findViewById(R.id.coordinatorLayout), R.string.no_movie,
                        Snackbar.LENGTH_LONG).show();
            }
        }
        catch (JSONException e){
            e.printStackTrace();
        }
    }



}

Movie.java

package br.com.pedro.pedrodaumas;


public class Movie {
    public final String title;
    public final String publication_date;
    public final String iconURL;
    public final String short_summary ;

    public Movie(String title,String publication_date, String iconName, String short_summary) {
        this.title = title;
        this.publication_date = publication_date;
        this.iconURL = iconName;
        this.short_summary = short_summary;
    }

    public String getsummary() {
        return short_summary;
    }

}

MovieArrayAdapter.java

package br.com.pedro.pedrodaumas;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MovieArrayAdapter extends ArrayAdapter<Movie> {

    private static class ViewHolder{
        ImageView movieImage;
        TextView description;
        TextView publication_date;
    }

    private Map<String, Bitmap> bitmaps = new HashMap<>();
    public MovieArrayAdapter (Context context, List<Movie>
            forecast){
        super (context, -1, forecast);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        Movie review = getItem (position);
        ViewHolder viewHolder;
        if (convertView == null){
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.complete_review, parent, false);
            viewHolder.movieImage = (ImageView)convertView.findViewById(R.id.movieImage);
            viewHolder.description = (TextView)convertView.findViewById(R.id.description);
            viewHolder.publication_date = (TextView)convertView.findViewById(R.id.publication_date);
            convertView.setTag(viewHolder);
        }
        else{
            viewHolder = (ViewHolder)convertView.getTag();
        }
        if(review.iconURL == "image"){
            viewHolder.movieImage.setImageResource(R.drawable.ic_import_contacts_white_24dp);
        }
        else{
            new LoadImageTask (viewHolder.movieImage).execute (review.iconURL);
        }
        viewHolder.description.setText(review.title);
        viewHolder.publication_date.setText(review.publication_date);

        return convertView;
    }



    private class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
        private ImageView imageView;
        public LoadImageTask (ImageView imageView){
            this.imageView = imageView;
        }
        @TargetApi(Build.VERSION_CODES.KITKAT)
        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            HttpURLConnection connection = null;
            try{
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                try(InputStream inputStream = connection.getInputStream ()){
                    bitmap = BitmapFactory.decodeStream(inputStream);
                    bitmaps.put (params[0], bitmap);
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
            finally{
                connection.disconnect();
            }
            return bitmap;
        }
        protected void onPostExecute(Bitmap bitmap) {
            imageView.setImageBitmap(bitmap);
        }
    }
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="br.com.pedro.pedrodaumas.MainActivity"
    android:id="@+id/coordinatorLayout">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            android:elevation="@dimen/toolbar_elevation" />

    </android.support.design.widget.AppBarLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|end"
        android:layout_marginTop="@dimen/fab_magin_top"
        android:layout_marginEnd="@dimen/fab_margin"
        android:layout_marginBottom="@dimen/fab_margin"
        android:layout_marginStart="@dimen/fab_margin"
        app:elevation="@dimen/rested_button_elevation"
        android:src="@drawable/ic_action_search" />

    <include android:id="@+id/content"
        layout="@layout/content_main" />


</android.support.design.widget.CoordinatorLayout>

Content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="br.com.pedro.pedrodaumas.MainActivity"
    tools:showIn="@layout/activity_main"
    android:orientation="vertical">

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/view">

        <android.support.design.widget.TextInputEditText android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/search_bar"
            android:singleLine="true"
            android:hint="@string/hint_text"
            android:elevation="@dimen/rested_search_elevation"
            tools:targetApi="lollipop" />
    </android.support.design.widget.TextInputLayout>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:id="@+id/movieListView"
        android:layout_weight="1" />
</LinearLayout>

错误消息

07-28 21:18:00.812 5123-5123/br.com.pedro.pedrodaumas E/Zygote: no v2
07-28 21:18:00.822 5123-5123/br.com.pedro.pedrodaumas I/SELinux: Function: selinux_compare_spd_ram, SPD-policy is existed. and_ver=SEPF_SM-J110M_5.1.1 ver=48
07-28 21:18:00.822 5123-5123/br.com.pedro.pedrodaumas I/SELinux: Function: selinux_compare_spd_ram , priority [1] , priority version is VE=SEPF_SM-J110M_5.1.1_0048
07-28 21:18:00.822 5123-5123/br.com.pedro.pedrodaumas E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
07-28 21:18:00.822 5123-5123/br.com.pedro.pedrodaumas I/art: Late-enabling -Xcheck:jni
07-28 21:18:00.842 5123-5123/br.com.pedro.pedrodaumas I/SAMP: ActivityThread() - SAMP_ENABLE : true
07-28 21:18:00.862 5123-5123/br.com.pedro.pedrodaumas W/ResourcesManager: getTopLevelResources: null for user  0
07-28 21:18:01.012 5123-5123/br.com.pedro.pedrodaumas W/ResourcesManager: getTopLevelResources: null for user  0
07-28 21:18:01.022 5123-5123/br.com.pedro.pedrodaumas D/DisplayManager: DisplayManager()
07-28 21:18:01.022 5123-5123/br.com.pedro.pedrodaumas W/ResourcesManager: getTopLevelResources: null for user  0
07-28 21:18:01.092 5123-5123/br.com.pedro.pedrodaumas 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
07-28 21:18:01.172 5123-5123/br.com.pedro.pedrodaumas D/PhoneWindow: *FMB* installDecor mIsFloating : false
07-28 21:18:01.172 5123-5123/br.com.pedro.pedrodaumas D/PhoneWindow: *FMB* installDecor flags : -2139029248
07-28 21:18:01.362 5123-5138/br.com.pedro.pedrodaumas I/art: Background partial concurrent mark sweep GC freed 3506(700KB) AllocSpace objects, 0(0B) LOS objects, 27% free, 5MB/7MB, paused 7.831ms total 22.235ms
07-28 21:18:01.372 5123-5123/br.com.pedro.pedrodaumas I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
07-28 21:18:01.412 5123-5123/br.com.pedro.pedrodaumas D/AndroidRuntime: Shutting down VM
07-28 21:18:01.412 5123-5123/br.com.pedro.pedrodaumas E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: br.com.pedro.pedrodaumas, PID: 5123
                                                                        java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.pedro.pedrodaumas/br.com.pedro.pedrodaumas.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2697)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2771)
                                                                            at android.app.ActivityThread.access$900(ActivityThread.java:177)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1432)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:135)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5912)
                                                                            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:1405)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
                                                                         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                            at br.com.pedro.pedrodaumas.MainActivity.onCreate(MainActivity.java:44)
                                                                            at android.app.Activity.performCreate(Activity.java:6178)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2650)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2771) 
                                                                            at android.app.ActivityThread.access$900(ActivityThread.java:177) 
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1432) 
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                            at android.os.Looper.loop(Looper.java:135) 
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5912) 
                                                                            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:1405) 
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 
07-28 21:29:10.422 8489-8489/br.com.pedro.pedrodaumas 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
07-28 21:29:10.522 8489-8489/br.com.pedro.pedrodaumas D/PhoneWindow: *FMB* installDecor mIsFloating : false
07-28 21:29:10.522 8489-8489/br.com.pedro.pedrodaumas D/PhoneWindow: *FMB* installDecor flags : -2139029248
07-28 21:29:10.612 8489-8489/br.com.pedro.pedrodaumas I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
07-28 21:29:10.612 8489-8489/br.com.pedro.pedrodaumas D/AndroidRuntime: Shutting down VM
07-28 21:29:10.612 8489-8489/br.com.pedro.pedrodaumas E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: br.com.pedro.pedrodaumas, PID: 8489
                                                                        java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.pedro.pedrodaumas/br.com.pedro.pedrodaumas.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2697)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2771)
                                                                            at android.app.ActivityThread.access$900(ActivityThread.java:177)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1432)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:135)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5912)
                                                                            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:1405)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
                                                                         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                            at br.com.pedro.pedrodaumas.MainActivity.onCreate(MainActivity.java:44)
                                                                            at android.app.Activity.performCreate(Activity.java:6178)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2650)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2771) 
                                                                            at android.app.ActivityThread.access$900(ActivityThread.java:177) 
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1432) 
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                            at android.os.Looper.loop(Looper.java:135) 
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5912) 
                                                                            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:1405) 
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 

1 个答案:

答案 0 :(得分:0)

对不起伙计们,我真的很蠢,因为我的项目是针对Android 4.0 +而我在布局上使用了elvation(只支持5.0 +),android studio制作了2种不同的布局,一种用于5.0 - 和一个5.0 + +由于某种原因5.0 +的layour没有ListView。 我刚刚在v21 / content_main上添加了ListView,它确实有效!

感谢每个人的帮助,并为愚蠢的错误和不良解释感到抱歉