尝试在空对象引用上调用虚拟方法'void android.widget.TextView.setText(int)'

时间:2019-01-22 08:50:26

标签: android json android-studio nullpointerexception

我正在制作图书应用,但出现错误

  

尝试调用虚拟方法'void   空对象引用上的android.widget.TextView.setText(int)'

我尝试解决它,但是没有解决。它给出了致命异常错误。 当我按搜索书按钮时,我的应用程序崩溃了,并且没有按原样显示该书。 我在setTextMethod中遇到错误。

这是我的 Fetchbook.java 文件:

private TextView mTitleText;
        private TextView mAuthorText;

        // Class name for Log tag
        private static final String LOG_TAG = FetchBook.class.getSimpleName();

        public FetchBook(TextView mTitleText, TextView mAuthorText) {
            this.mTitleText = mTitleText;
            this.mAuthorText = mAuthorText;

        }

        @Override
        protected String doInBackground(String... strings) {

            return NetworkUtils.getBookInfo(strings[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray itemsArray = jsonObject.getJSONArray("items");

                for (int i = 0; i < itemsArray.length(); i++) {
                    JSONObject book = itemsArray.getJSONObject(i);
                    String title = null;
                    String authors = null;
                    JSONObject volumeInfo = book.getJSONObject("volumeInfo");

                    try {
                        title = volumeInfo.getString("title");
                        authors = volumeInfo.getString("authors");

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


                    //if both a title and auther exits, update the TextView and return
                    if (title != null && authors != null) {
                        mTitleText.setText(title);
                        mAuthorText.setText(authors);
                        return;
                    }
                }

                mTitleText.setText(R.string.no_found);
                mAuthorText.setText("");

            } catch (Exception e){
                mTitleText.setText(R.string.no_found_all);
                mAuthorText.setText("");
                e.printStackTrace();
            }
        }

这是我的 Main.java 文件:

private static final String TAG = MainActivity.class.getSimpleName();

        private EditText mBookInput;
        private TextView mAuthorText,mTitleText;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            mBookInput = (EditText)findViewById(R.id.book_input);
            mAuthorText = (TextView)findViewById(R.id.author_text);
            mTitleText = (TextView)findViewById(R.id.titleText);
        }

        public void searchBooks(View view){

            String queryString = mBookInput.getText().toString();
            Log.i(TAG,"Searched" +queryString);
            new FetchBook(mTitleText,mAuthorText).execute(queryString);
        }

这是我的 NetworkUtils.java 文件:

private static final String LOG_TAG = NetworkUtils.class.getSimpleName();
        //Base URl KEY for the book API
        private static final String BOoks_API_KEY = "https://www.googleapis.com/books/v1/volumes?";
        private static final String QUERY_PARAM = "q";//Parameter for the search string
        private static final String MAX_RESULTS = "maxResults";//Parameter that limit search limit
        private static final String PRINT_TYPE = "print_type";//Parameter to filter the result

        static String getBookInfo(String queryString){
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            String bookJSONString = null;


            try {
                // Build up query uri,
                Uri builtUri = Uri.parse(BOoks_API_KEY).buildUpon()
                        .appendQueryParameter(QUERY_PARAM,queryString)
                        .appendQueryParameter(MAX_RESULTS, "10")
                        .appendQueryParameter(PRINT_TYPE,"books")
                        .build();

                URL requestURL = new URL(builtUri.toString());

                urlConnection = (HttpURLConnection)requestURL.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                //Read the response using an inputStream and a StringBuffer,then convert it to a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null){
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null ){
                    buffer.append(line + "\n");

                }

                if (buffer.length()== 0){
                    //Stream is empty, nothing to parse
                    return null;
                }
                bookJSONString = buffer.toString();

            }catch (IOException ex){
              ex.printStackTrace();


            }finally {
                if (urlConnection != null){
                    urlConnection.disconnect();
                }
                if (reader!= null){
                    try{
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                return bookJSONString;
            }
        }

这是我的 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:orientation="vertical"
        tools:context=".MainActivity">

        <TextView
            android:id="@+id/Instruction"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/Instruction"
            android:textAppearance="@style/TextAppearance.AppCompat.Title" />

        <EditText
            android:id="@+id/book_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint"
            android:inputType="text" />

        <Button
            android:id="@+id/search_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="searchBooks"
            android:text="@string/button_text" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@+id/titleText"
            android:textAppearance="@style/TextAppearance.AppCompat.Headline" />

        <TextView
            android:id="@+id/author_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="@style/TextAppearance.AppCompat.Headline" />
    </LinearLayout>

0 个答案:

没有答案