android网络问题-udacity android网络最终项目(使用google book api和loadmanager/asynctaskloader)

gzjq41n4  于 2021-06-26  发布在  Java
关注(0)|答案(0)|浏览(187)

我正在进行udacity android网络的最后一个项目——让一个应用程序在google book api中搜索书籍,但我的应用程序一直崩溃,我不知道如何工作,也不知道从哪里开始调试。我是个android新手,所以我还不太懂。如果你知道为什么我的应用程序不断崩溃,请告诉我。非常感谢。
主活动.java

package com.example.networkingfinals;

import androidx.appcompat.app.AppCompatActivity;

import android.app.LoaderManager;
import android.content.Loader;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import java.util.List;

public abstract class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks {

    private String url;
    private String input;
    private BookAdapter bookAdapter;

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

        Button button = (Button) findViewById(R.id.submit);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText editText = (EditText) findViewById(R.id.input);
                input = String.valueOf(editText.getText());
                url = "https://www.googleapis.com/books/v1/volumes?q="+input+"&maxResults=3";
            }
        });
        LoaderManager loaderManager = getLoaderManager();
        getLoaderManager().initLoader(0, null, this);//Set loader manager to call asyncloader in onCreateLoader

    }

    @Override
    public Loader<List<BookInfo>> onCreateLoader(int id, Bundle args) {

        return new BookAsync(this, url);
        //Call oncreate Loader , fetching List of Book Info

    }

    public void onLoadFinished(Loader loader, List<BookInfo> bookInfos) {

        //Print\Load the List of BookInfo in the main threat ->Printing our UI

    }

    @Override
    public void onLoaderReset(Loader loader) {
        bookAdapter.clear();

    }
}

ultils.java文件

package com.example.networkingfinals;

import android.util.Log;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class Utils {

    public static URL makeURL(String url){
        //Convert string (include user input) into processable URL
        URL mURL = null;
        try {
            mURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return mURL;
    }

    public static String makeHTTPRequest(URL url) {

        String jsonRead = null;//Where the return JSON data will be save

        if (url == null) {
            return null;
        }

        HttpURLConnection httpURLConnection = null;
        InputStream inputStreamReader = null;
        //Establish server connection and receiver

        try {
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(1000);
            httpURLConnection.setReadTimeout(1000);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            //Ask for needed data
            if (httpURLConnection.getResponseCode() == 200) {
                //Receive/catch received data
                inputStreamReader = httpURLConnection.getInputStream();
                jsonRead = readFromInput(inputStreamReader);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonRead;
    }

    public static String readFromInput(InputStream inputStream) throws IOException {

        String lines = null;//BufferedREader string in a line collection
        StringBuilder stringBuilder = new StringBuilder();//Build String from all the lines
        if (inputStream == null){
            //Check to end program early
            return null;
        }else {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            //inputstreamreader read inputstream
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            //BufferedREader read from input stream reader - buffered in charactor
            lines = bufferedReader.readLine();//MAke String lines
            while (lines != null){
                stringBuilder.append(lines);
                //Add lines of string to string builder -> json doc
                lines = bufferedReader.readLine();

            }

        }
        return stringBuilder.toString();
    }

    public static List<BookInfo> extractJsonBookData(String json) throws JSONException {

        //TODO: Write method extracting json from HTTPRequest
        List<BookInfo> bookInfos = new ArrayList<BookInfo>();// List object store BookInfo object

        JSONObject jsonObject = new JSONObject(json);
        Log.v("JsonExtract", "FirstJson Object "+jsonObject);
        JSONArray jsonArray = jsonObject.getJSONArray("items");
        Log.v("JsonExtract", "FirstJson Object "+jsonArray);

        for(int i = 0; i<=jsonArray.length();i++){
            String tittle = jsonArray.getJSONObject(i).getJSONObject("volumeInfo").getString("title");
            String author = jsonArray.getJSONObject(i).getJSONObject("volumeInfo").getString("authors");
            Integer pageCount = Integer.valueOf(jsonArray.getJSONObject(i).getJSONObject("volumeInfo").getString("pageCount"));

            bookInfos.add(new BookInfo(tittle, author, pageCount));
        }
        return bookInfos;
    }

    public static List<BookInfo> fetchData(String url) throws JSONException {
        URL murl = makeURL(url);
        String jsonData = makeHTTPRequest(murl);
        List<BookInfo> bookInfoList = extractJsonBookData(jsonData);
        return bookInfoList;
    }

}

bookadapter.java文件

package com.example.networkingfinals;

import android.app.LoaderManager;
import android.content.Context;
import android.content.Loader;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.List;

public class BookAdapter extends ArrayAdapter<BookInfo> {
    //Don't forget to add ArrayAdapter`<BookInfo>`
    public BookAdapter(@NonNull Context context, List<BookInfo> books) {
        super(context, 0, books);//Get input of List of BookInfo objects

    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.book_list_view, parent, false);
            //Set convertView to get UI object from book list view xml
        }

        BookInfo bookInfo = (BookInfo) getItem(position);//Get current position of BookInfo object

        TextView tittle = (TextView) convertView.findViewById(R.id.tittle);
        tittle.setText(bookInfo.getTittile());

        TextView author = (TextView) convertView.findViewById(R.id.author);
        author.setText(bookInfo.getAuthor());

        TextView pageCount = (TextView) convertView.findViewById(R.id.pageNumber);
        pageCount.setText(bookInfo.getPageCount());

        return convertView;
    }

}

bookasync.java文件

package com.example.networkingfinals;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.content.AsyncTaskLoader;// Make sure to get this import

import org.json.JSONException;

import java.net.URL;
import java.util.List;

public class BookAsync extends AsyncTaskLoader {

    private String mUrl;

    public BookAsync(@NonNull Context context, String url) {
        super(context);
        mUrl = url;
    }

    @Override
    protected void onStartLoading() {
        forceLoad();
    }

    @Nullable
    @Override
    public List<BookInfo> loadInBackground() {

        if (mUrl == null){
            return null;
        }
        List<BookInfo> mainBookInfos = null;
        try {
            mainBookInfos = Utils.fetchData(mUrl);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mainBookInfos;

    }
}

图书信息.java

package com.example.networkingfinals;

public class BookInfo {
    String mTittile;
    String mAuthor;
    Integer mPageCount;

    public BookInfo(String tittle, String author, Integer pageCount){
        mTittile = tittle;
        mAuthor = author;
        mPageCount = pageCount;
    }

    public String getAuthor(){
        return mAuthor;
    }
    public String getTittile(){
        return mTittile;
    }
    public Integer getPageCount(){
        return mPageCount;
    }
}

活动\u main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:orientation="vertical">

    <EditText
        android:layout_width="209dp"
        android:layout_height="wrap_content"
        android:id="@+id/input"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit"
        android:id="@+id/submit"/>

</LinearLayout>

图书列表视图.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/listView">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tittle"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/author"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/pageNumber"/>

</ListView>

堆栈跟踪

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.networkingfinals, PID: 10059
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.networkingfinals/com.example.networkingfinals.MainActivity}: java.lang.InstantiationException: java.lang.Class<com.example.networkingfinals.MainActivity> cannot be instantiated
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3197)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3412)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2019)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7458)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
     Caused by: java.lang.InstantiationException: java.lang.Class<com.example.networkingfinals.MainActivity> cannot be instantiated
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1251)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3185)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3412) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2019) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7458) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935) 
I/Process: Sending signal. PID: 10059 SIG: 9

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题