2016-07-29 123 views
0

我沒有問題,我運行一個仿真器的應用程序,但是當我嘗試玩手機我得到這個錯誤ListAdapter「錯誤顯示java.lang.NullPointerException」

「無法啓動活動ComponentInfo上{br.com.pedro.pedrodaumas/br.com.pedro.pedrodaumas.MainActivity}:java.lang.NullPointerException:試圖調用虛擬方法'void android.widget.ListView.setAdapter(android.widget.ListAdapter)'on a空對象引用「。

我已經嘗試將setContentView設置爲(activity_main.xml),(content_main.xml),並且我嘗試了兩個setContentViews,並且不斷收到錯誤。即使我已經將EditText更改爲TextInputEditText,我也得到「添加的EditText不是TextInputEditText」。

MainActivity.java

package br.com.pedro.pedrodaumas; 

import android.annotation.TargetApi; 
import android.content.Context; 
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.view.View; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.inputmethod.InputMethodManager; 
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.content_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(); 
       } 

      } 
     }); 
    } 

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

     //noinspection SimplifiableIfStatement 
     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); 
       JSONObject multimedia = movie.getJSONObject("multimedia"); 
       movieList.add(new Movie(movie.getString("display_title"), 
         movie.getString("publication_date"), 
         multimedia.getString("src"))); 

      } 
     } 
     catch (JSONException e){ 
      e.printStackTrace(); 
     } 
    } 
} 

Movie.java

package br.com.pedro.pedrodaumas; 

import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.TimeZone; 

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

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

MovieArrayAdapter.java

package br.com.pedro.pedrodaumas; 

import android.annotation.TargetApi; 
import android.content.Context; 
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 (bitmaps.containsKey(review.iconURL)){ 
      viewHolder.movieImage.setImageBitmap(bitmaps.get(review.iconURL)); 
     } 
     else{ 
      new LoadImageTask (viewHolder.movieImage).execute (review.iconURL); 
     } 

     Context context = getContext(); 
     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> 

    <include layout="@layout/content_main" /> 

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

</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)  
+0

我只是想幫助你與你的格式。是的。 – Elltz

+0

thx,首先在這裏^^ –

+0

減慢先生,請將其改回activity_main,當錯誤發生時,請張貼紅色的東西,顯示在這裏。 – Elltz

回答

0

對不起,我真的很笨,因爲我的項目是爲Android 4.0 +而我在我的佈局上使用elvation(僅支持5.0 +),android studio製作了2種不同的佈局,一個用於5.0+,由於某種原因,5.0+的佈局沒有ListView。我只是在v21/content_main上添加了ListView,它工作正常!

Thx爲大家的幫助和歉意與錯誤的錯誤解釋不好

0

你打電話setContentView(arg0)兩次,這可能是沒有幫助。

+0

當我這樣做時,我正在嘗試一些東西,但它不適用於一個'setContentView(arg0)'也 –

+0

你需要在setContentView()之後調用findViewById(),所以確保你刪除了正確的。 –

相關問題