2016-09-28 2 views
-3

Android에서 앱을 만들어야합니다. 나는 몇 가지 버그를 디버깅에 성공했다하지만 난 이해가 안 돼요이 하나이 java.lang.NullPointerException을 피하는 방법?

FATAL EXCEPTION: main 
Process: com.example.android.bookapp, PID: 7450 
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' 
on a null object reference 
나는 안드로이드 스튜디오 내 코드의 일부가 java.lang.NullPointerException이 생성 될 수 있음을 나에게 경고하기 위해 오렌지 배경을 넣을 것을 알 수 있습니다

그러나 나는 그것을 피하기 위해 무엇을 바꾸어야하는지 알지 못한다. 심지어 내 앱을 실행할 때이 오류가 발생하는 이유를 모르겠다. 나는 약간에게 get 메소드를 수정하지만 도움이되지 않았다

public class MainActivity extends AppCompatActivity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    /** find the button view, set an onclick listener on it, define & execute the bookListAsyncTask */ 
    Button searchButton = (Button) findViewById(R.id.search_button); 
    searchButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      BookListAsyncTask bookListAsyncTask = new BookListAsyncTask(); 
      bookListAsyncTask.execute(); 
     } 
    }); 
} 

/** 
* define the URL 
*/ 
public String makeUrl() { 
    EditText searchBookEditText = (EditText) findViewById(R.id.search_edit_text); 
    String searchBook = searchBookEditText.getText().toString(); 
    String searchBookModified = searchBook.replaceAll(" ", "+"); 
    final String REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q=" + searchBookModified + "&maxResults=3&printType=books"; 
    return REQUEST_URL; 
} 

private class BookListAsyncTask extends AsyncTask<URL, Void, ArrayList<Book>> { 

    @Override 
    protected ArrayList<Book> doInBackground(URL... urls) { 
     // Create URL object 
     URL url = createUrl(makeUrl()); 

     // Perform HTTP request to the URL and receive a JSON response back 
     String jsonResponse = ""; 
     try { 
      jsonResponse = makeHttpRequest(url); 
     } catch (IOException e) { 
     } 

     // Extract relevant fields from the JSON response and create an ArrayList<Book> object 
     ArrayList<Book> allBooks = extractFeatureFromJson(jsonResponse); 

     return allBooks; 
    } 

    /** 
    * Update the screen with the given books (which was the result of the 
    * {@link BookListAsyncTask}). 
    */ 
    @Override 
    protected void onPostExecute(ArrayList<Book> allBooks) { 
     if (allBooks == null) { 
      return; 
     } 
     BookAdapter bookAdapter = new BookAdapter(MainActivity.this, allBooks); 
     ListView listView = (ListView) findViewById(R.id.list_view); 
     listView.setAdapter(bookAdapter); 
    } 

    /** 
    * Returns new URL object from the given string URL. 
    */ 
    private URL createUrl(String stringUrl) { 
     URL url = null; 
     try { 
      url = new URL(stringUrl); 
     } catch (MalformedURLException exception) { 
      Log.e("MainActivity", "Error with creating URL", exception); 
      return null; 
     } 
     return url; 
    } 

    /** 
    * Make an HTTP request to the given URL and return a String as the response. 
    */ 
    private String makeHttpRequest(URL url) throws IOException { 
     String jsonResponse = ""; 
     HttpURLConnection urlConnection = null; 
     InputStream inputStream = null; 
     try { 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setRequestMethod("GET"); 
      urlConnection.setReadTimeout(10000 /* milliseconds */); 
      urlConnection.setConnectTimeout(15000 /* milliseconds */); 
      urlConnection.connect(); 
      inputStream = urlConnection.getInputStream(); 
      int responseCode = urlConnection.getResponseCode(); 
      if (responseCode == 200) { 
       jsonResponse = readFromStream(inputStream); 
      } else { 
       jsonResponse = ""; 
       Log.e("MainActivity", "error response code" + String.valueOf(responseCode)); 
      } 

     } catch (IOException e) { 
      // TODO: Handle the exception 
      Log.e("MainActivity", "Problem retrieving the earthquake JSON results", e); 

     } finally { 
      if (urlConnection != null) { 
       urlConnection.disconnect(); 
      } 
      if (inputStream != null) { 
       // function must handle java.io.IOException here 
       inputStream.close(); 
      } 
     } 
     return jsonResponse; 
    } 

    /** 
    * Convert the {@link InputStream} into a String which contains the 
    * whole JSON response from the server. 
    */ 
    private String readFromStream(InputStream inputStream) throws IOException { 
     StringBuilder output = new StringBuilder(); 
     if (inputStream != null) { 
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8")); 
      BufferedReader reader = new BufferedReader(inputStreamReader); 
      String line = reader.readLine(); 
      while (line != null) { 
       output.append(line); 
       line = reader.readLine(); 
      } 
     } 
     return output.toString(); 
    } 

    /** 
    * Return a book ArrayList 
    */ 
    public ArrayList<Book> extractFeatureFromJson(String bookJSON) { 

     ArrayList<Book> allBooks = new ArrayList<>(); 
     try { 
      JSONObject baseJsonResponse = new JSONObject(bookJSON); 
      JSONArray items = baseJsonResponse.getJSONArray("items"); 

      // If there are results in the features array 
      if (items.length() > 0) { 
       for (int i = 0; i < items.length(); i++) 
       // Parse the JSON and fill the allBooks ArrayList) 
       { 
        JSONObject currentBook = items.getJSONObject(i); 
        JSONObject currentVolumeInfo = currentBook.getJSONObject("volumeInfo"); 
        String currentTitle = currentVolumeInfo.getString("title"); 
        String currentFirstAuthor = "Author Unknown"; 
        Book book = new Book(currentTitle, currentFirstAuthor); 
        allBooks.add(book); 
       } 

       return allBooks; 
      } 
     } catch (JSONException e) { 
      Log.e("MainActivity", "Problem parsing the earthquake JSON results", e); 
     } 
     return null; 
    } 
} 


public class BookAdapter extends ArrayAdapter<Book> { 

    public BookAdapter(Activity context, ArrayList<Book> books) { 
     super(context, 0, books); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     // Check if the existing view is being reused, otherwise inflate the view 
     View listItemView = convertView; 
     if (listItemView == null) { 
      listItemView = LayoutInflater.from(getContext()).inflate(
        R.layout.list_item_view, parent, false); 
     } 

     Book currentBook = getItem(position); 

     TextView title = (TextView) findViewById(R.id.title_text_view); 
     title.setText(currentBook.getTitle()); 

     TextView author = (TextView) findViewById(R.id.author_text_view); 
     author.setText(currentBook.getAuthor()); 

     return listItemView; 
    } 
} 
} 

와 책 클래스 :

public class Book { 

private String mTitle; 
private String mAuthor; 

public Book(String title, String author){ 
    mTitle = title; 
    mAuthor = author; 
} 

public String getTitle(){ 
    if (mTitle == null){ 
     return mTitle = "";} 
    else {return mTitle;}} 
public String getAuthor(){ 
    if (mAuthor == null){ 
     return mAuthor = ""; 
    } else {return mAuthor;}} 
} 

당신이 무슨 일이야 볼 수 있나요 여기

내 코드?

+0

TextView title = (TextView) findViewById(R.id.title_text_view); TextView author = (TextView) findViewById(R.id.author_text_view); 

(...)를 호출한다. – Corgs

+0

어떤 이유로 든 제목 또는 도서가 null입니다. XML에 해당 변수 이름과 같은 ID가 있는지 확인하십시오. – Corgs

+0

당신이 예외를 얻고있는 줄을 –

답변

4

변경 라인 바로 author.setText 위

TextView title = (TextView) listItemView.findViewById(R.id.title_text_view); 
TextView author = (TextView) listItemView.findViewById(R.id.author_text_view); 



@Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      // Check if the existing view is being reused, otherwise inflate the view 
      View listItemView = convertView; 
      if (listItemView == null) { 
       listItemView = LayoutInflater.from(getContext()).inflate(
         R.layout.list_item_view, parent, false); 
      } 

      Book currentBook = getItem(position); 

      TextView title = (TextView) listItemView.findViewById(R.id.title_text_view); 
      title.setText(currentBook.getTitle()); 

      TextView author = (TextView) listItemView.findViewById(R.id.author_text_view); 
      author.setText(currentBook.getAuthor()); 

      return listItemView; 
     } 
+0

솔루션이 당신을 위해 일하기를 희망합니다 .. 답변을 수락하십시오 .. – somia

+0

여러분 안녕하십니까. Sonia 당신이 조언 한 것처럼 findViewById를 listItemView.findViewById로 변경 했으므로 이제 작동합니다. 고맙습니다 ! 왜 그것이 효과가 있는지 설명해 주시겠습니까? 나는 그것을 정말로 이해하지 못한다. 나의 제목과 저자 textview는 더 이상 NullPointerException 경고가 없기 때문에 null이 될 수있다. – Alex9494

+0

이 링크가 유용 할 것입니다. https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/ – somia

관련 문제