【问题标题】:Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()'尝试调用接口方法'java.lang.Object[] java.util.Collection.toArray()'
【发布时间】:2015-12-27 16:48:52
【问题描述】:

代码从网页获取 JSON 对象并将其放入列表中。这里出现异常。请帮助我...

import android.content.Context;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

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

import java.io.IOException;
import java.util.ArrayList;


public class FeedActivity extends Activity implements OnFeedListener{


ListView listview;
FeedAdapter adapter;
ArrayList<Post> posts;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_feed);

    listview = (ListView)findViewById(R.id.listView);


    //Data ->adapter -> ListView
    adapter = new FeedAdapter(getApplicationContext(),R.layout.layout_feed_item);


    listview.setAdapter(adapter);

    FeedTask task = new FeedTask(this);
    task.execute("https://public-api.wordpress.com/rest/v1.1/sites/androsiv.wordpress.com/posts/");
}

@Override
public void onFeed(JSONArray array) {
    int length = array.length();
    for(int i = 0; i<length; i++)
    {
        JSONObject object = array.optJSONObject(i);
         Post post = new Post(object.optString("title"),object.optString("excerpt"),object.optString("featured_image"));

        posts = new ArrayList<>();
        posts.add(post);
    }
    adapter.addAll(posts);
    adapter.notifyDataSetChanged();
}


public class FeedTask extends AsyncTask<String, Void, JSONArray>
{
    private OnFeedListener listener;
    public FeedTask(OnFeedListener listener)
    {
        this.listener = listener;
    }


    @Override
    protected JSONArray doInBackground(String... params) {
        String url = params[0];

        OkHttpClient client = new OkHttpClient();
        Request.Builder builder = new Request.Builder();

        Request request = builder.url(url).build();

        try {
            Response response = client.newCall(request).execute();
            String json = response.body().string();
            try {
                JSONObject object = new JSONObject(json);
                JSONArray array = object.optJSONArray("posts");
                return array;
            }
            catch(JSONException e)
                {
                    e.printStackTrace();
                }
         } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(JSONArray array) {
        super.onPostExecute(array);

        if(null == array)
           return;

        if(null != listener)
            listener.onFeed(array);
    }
}

public class FeedAdapter extends ArrayAdapter<Post>
{
    private int resource;
    public FeedAdapter(Context context, int resource) {
        super(context, resource);
        this.resource = resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(null == convertView)
        {
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(resource,null);
        }
        //Binding data
        Post post = getItem(position);
        TextView title = (TextView) convertView.findViewById(R.id.title);
        TextView desc = (TextView) convertView.findViewById(R.id.description);

        title.setText(post.title);
        desc.setText(post.description);
        return convertView;
    }

}

public class Post
{
    public String title;
    public String description;
    public String thumbnail; //url

    public Post(String title, String desc, String thumbnail)
    {
        this.description=desc;
        this.thumbnail=thumbnail;
        this.title=title;
    }
}
}

上面程序的日志猫如下... nullpointer 程序中遇到异常...有人请帮帮我..在以前的类似问题中,我找不到解释.. 日志猫: 通过更改上述行,我得到以下异常:

 java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:300)
FATAL EXCEPTION: AbstractCallbackSender
Process: jp.co.translimit.braindots, PID: 7444
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:300)
 FATAL EXCEPTION: AsyncTask #5
Process: jp.co.translimit.braindots, PID: 8498
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:300)
 java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:300)

【问题讨论】:

    标签: java android nullpointerexception


    【解决方案1】:

    问题是这样的声明:

    adapter.addAll(posts);
    

    此时,在您的 onCreate 方法中,posts 尚未初始化并包含 NULL 作为值。你应该

    1. 使用前初始化posts (posts = new ArrayList&lt;Post&gt;())
    2. 由于addAll(posts) 可能在posts 为空时不会有任何影响,所以一起跳过。您在 onFeed 方法中再次调用 addAll(posts)

    附注:我看到您在 onFeed() 方法的循环中使用空数组重新初始化posts。那不会有任何好处。您应该在循环之前初始化posts 集合。

    【讨论】:

      【解决方案2】:

      adapter.addAll(帖子); 在不创建初始化的情况下,您正在尝试添加适配器。这里的帖子数组列表为空,您正在将帖子数组填充到在上述行之后启动的 asynctask 中。删除上面的行就可以了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-17
        • 1970-01-01
        • 2020-09-28
        • 1970-01-01
        • 2019-03-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        相关资源
        最近更新 更多