ListView中没有任何内容,它没有加载内容

时间:2017-10-12 14:17:18

标签: android listview

我的bookListing app有问题,问题是我从https://www.googleapis.com/books/v1/volumes?q=android&maxResults=40得到的json内容 没有出现在列表视图中我现在不知道这是什么原因可以任何人帮我这个?我正面临着与装载机打交道的艰难时期:)  BookActivity.java

 package com.example.android.booklistingapp;

import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class BookActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<VolumeInfo>> {

    EditText searchFeild;
    ListView booksListView;
    BookApdapter apdapter;
    String url ;

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

        booksListView = (ListView) findViewById(R.id.MyList);
        searchFeild = (EditText) findViewById(R.id.Search_EditText);

        apdapter = new BookApdapter(this, new ArrayList<VolumeInfo>());
        booksListView.setAdapter(apdapter);
       /* InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(searchFeild.getWindowToken(), 0);*/

        Button searchButton = (Button) findViewById(R.id.Search_Button);
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userInputSearchFeild = searchFeild.getText().toString().toLowerCase();
                Toast.makeText(getApplicationContext(), "yesssss", Toast.LENGTH_LONG).show();
                try {
                    userInputSearchFeild = URLEncoder.encode(userInputSearchFeild, "UTF-8");
                    url = "https://www.googleapis.com/books/v1/volumes?q=" + userInputSearchFeild + "&maxResults=3";

                } catch (UnsupportedEncodingException e) {
                    Log.i("","Encode ERRor");
                    e.printStackTrace();
                }
            }
        });
        LoaderManager loaderManager=getSupportLoaderManager();
        loaderManager.initLoader(0,null,BookActivity.this).forceLoad();
    }

    @Override
    public Loader<List<VolumeInfo>> onCreateLoader(int id, Bundle args) {
        return new VolumeInfoLoader(this,url);
    }

    @Override
    public void onLoadFinished(Loader<List<VolumeInfo>> loader, List<VolumeInfo> data) {
        apdapter.clear();
        if(data != null && !data.isEmpty())
            apdapter.addAll(data);
    }

    @Override
    public void onLoaderReset(Loader<List<VolumeInfo>> loader) {
        apdapter.clear();
    }
}

volumeinfoloader.java

package com.example.android.booklistingapp;


import  android.support.v4.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

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

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.util.ArrayList;
import java.util.List;

/**
 * Created by Hazem_Khaled on 2017-10-12.
 */

public class VolumeInfoLoader extends AsyncTaskLoader<List<VolumeInfo>> {

    String mUrl;

    public VolumeInfoLoader(Context context, String url) {
        super(context);
        mUrl = url;
    }

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

    @Override
    public List<VolumeInfo> loadInBackground() {
        if (mUrl == null) {
            Log.i("This ", "null ERROR");
            return null;
        }
        try {
            Toast.makeText(getContext(),"Start",Toast.LENGTH_LONG).show();
            URL url = new URL(mUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(15000);
            connection.setRequestMethod("GET");
            connection.connect();

            InputStream IS = connection.getInputStream();
            InputStreamReader ISR = new InputStreamReader(IS);

            int data = ISR.read();
            String urlContent = "";
            Log.i("This is", urlContent);
            while (data != -1) {

                char c = (char) data;
                urlContent += c;
                data = ISR.read();
            }

           Toast.makeText(getContext(),urlContent,Toast.LENGTH_LONG).show();
            JSONObject root = new JSONObject(urlContent);
            JSONArray items = root.getJSONArray("item");
            List<VolumeInfo> booksInfo = new ArrayList<>();
            for (int i = 0; i < items.length(); i++) {
                JSONObject volInfo = items.getJSONObject(i);
                String bookTitle = volInfo.getString("title");
                String publisher = volInfo.getString("publisher");
                JSONArray authors = volInfo.getJSONArray("authors");

                StringBuilder authorsList = new StringBuilder();
                for (int j = 0; j < authors.length(); j++) {
                    authorsList.append("-" + authors.getString(i) + "\n");
                }
                VolumeInfo volumeInfo = new VolumeInfo(bookTitle, publisher, authorsList);
                booksInfo.add(volumeInfo);
            }
            return booksInfo;

        } catch (MalformedURLException e) {
            Log.i("This ", "URL ERROR");
            e.printStackTrace();
        } catch (JSONException e) {
            Log.i("This ", "json ERROR");
            e.printStackTrace();
        } catch (IOException e) {
            Log.i("This ", "io ERROR");
            e.printStackTrace();
        }

        return null;
    }
}

BookApdater.java

package com.example.android.booklistingapp;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Hazem_Khaled on 2017-10-06.
 */

public class BookApdapter extends ArrayAdapter<VolumeInfo>{
    public BookApdapter(Activity context, ArrayList<VolumeInfo> booksInfo){
        super(context,0,booksInfo);
    }

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

        View listView = convertView;
        if (listView == null)
            listView = LayoutInflater.from(getContext()).inflate(R.layout.author_list_item, parent, false);


        VolumeInfo volumeInfo=getItem(position);
        TextView bookTitle = (TextView) listView.findViewById(R.id.bookTitle_TextView);
        TextView bookAuthors = (TextView) listView.findViewById(R.id.bookAuthors_TexttView);
        TextView bookPublisher = (TextView) listView.findViewById(R.id.bookPublisher_TextView);

        if(volumeInfo!=null) {

            bookTitle.setText("Book Title:\n" + volumeInfo.getTitle() + "\n");

            StringBuilder authors = volumeInfo.getAuthorsList();
            bookAuthors.setText("Author(s):\n" + authors.toString() + "\n");
            bookPublisher.setText("Publisher:\n" + volumeInfo.getPublisher() + "\n");
        }
        else{
            bookTitle.setText("there is no books for this category you have entered,please try valid category");
            bookAuthors.setText("");
            bookPublisher.setText("");
        }

        return listView;
    }
}

1 个答案:

答案 0 :(得分:0)

首先 url将null传递给VolumeInfoLoader: 这应该是BookActivity:`public class BookActivity扩展AppCompatActivity实现LoaderManager.LoaderCallbacks&gt; {

EditText searchFeild;
ListView booksListView;
BookApdapter apdapter;
String url ;

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

    booksListView = (ListView) findViewById(R.id.MyList);
    searchFeild = (EditText) findViewById(R.id.Search_EditText);

    apdapter = new BookApdapter(this, new ArrayList<VolumeInfo>());
    booksListView.setAdapter(apdapter);
   /* InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(searchFeild.getWindowToken(), 0);*/

    Button searchButton = (Button) findViewById(R.id.Search_Button);
    searchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String userInputSearchFeild = searchFeild.getText().toString().toLowerCase();
            Toast.makeText(getApplicationContext(), "yesssss", Toast.LENGTH_LONG).show();
            try {
                userInputSearchFeild = URLEncoder.encode(userInputSearchFeild, "UTF-8");
                url = "https://www.googleapis.com/books/v1/volumes?q=" + userInputSearchFeild + "&maxResults=3";
                LoaderManager loaderManager=getSupportLoaderManager();
                loaderManager.initLoader(0,null,BookActivity.this).forceLoad();
            } catch (UnsupportedEncodingException e) {
                Log.i("","Encode ERRor");
                e.printStackTrace();
            }
        }
    });

}

@Override
public Loader<List<VolumeInfo>> onCreateLoader(int id, Bundle args) {
    Log.i("Loader"," onCreateLoader");

    return new VolumeInfoLoader(this,url);

}

@Override
public void onLoadFinished(Loader<List<VolumeInfo>> loader, List<VolumeInfo> data) {
    Log.i("Loader"," onLoadFinished");

    apdapter.clear();
    if(data != null && !data.isEmpty())
        apdapter.addAll(data);
    apdapter.notifyDataSetChanged();
}

@Override
public void onLoaderReset(Loader<List<VolumeInfo>> loader) {
    apdapter.clear();
    Log.i("Loader"," onLoaderReset");

}

}`

第二次基于此API测试 “https://www.googleapis.com/books/v1/volumes?q=arab&maxResults=10”:您必须正确使用API​​:使用 JSONArray items = root.getJSONArray(“items”); 而不是JSONArray items = root.getJSONArray(“item”); ... VolumeInfoLoader应如下所示:`public class VolumeInfoLoader extends AsyncTaskLoader&gt; {

String mUrl;

public VolumeInfoLoader(Context context, String url) {
    super(context);
    mUrl = url;
}

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

@Override
public List<VolumeInfo> loadInBackground() {
    if (mUrl == null) {
        Log.i("This ", "null ERROR");
        return null;
    }
    try {
        URL url = new URL(mUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000);
        connection.setConnectTimeout(15000);
        connection.setRequestMethod("GET");
        connection.connect();

        InputStream IS = connection.getInputStream();
        InputStreamReader ISR = new InputStreamReader(IS);

        int data = ISR.read();
        String urlContent = "";
        Log.i("This is", urlContent);
        while (data != -1) {

            char c = (char) data;
            urlContent += c;
            data = ISR.read();
        }
        JSONObject root = new JSONObject(urlContent);
        JSONArray items = root.getJSONArray("items");
        List<VolumeInfo> booksInfo = new ArrayList<>();
        for (int i = 0; i < items.length(); i++) {
            JSONObject volInfo = items.getJSONObject(i);
            volInfo=volInfo.getJSONObject("volumeInfo");
            String bookTitle = volInfo.getString("title");
            String publisher="Not Mention";
            if(volInfo.has("publisher")){
               publisher=volInfo.getString("publisher");
            }

            JSONArray authors = volInfo.getJSONArray("authors");

            StringBuilder authorsList = new StringBuilder();
            for (int j = 0; j < authors.length(); j++) {
                authorsList.append("-" + authors.getString(j) + "\n");
            }
            VolumeInfo volumeInfo = new VolumeInfo(bookTitle, publisher, authorsList);
            booksInfo.add(volumeInfo);
        }
        return booksInfo;

    } catch (MalformedURLException e) {
        Log.i("This ", "URL ERROR");
        e.printStackTrace();
    } catch (JSONException e) {
        Log.i("This ", "json ERROR");
        e.printStackTrace();
    } catch (IOException e) {
        Log.i("This ", "io ERROR");
        e.printStackTrace();
    }

    return null;
}

}

`