简体   繁体   English

尝试调用接口方法“ java.lang.Object [] java.util.Collection.toArray()”

[英]Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()'

The code gets JSON object from a webpage and makes it to a list..somewhere here an exception is arising..Please help me... 该代码从网页获取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;
    }
}
}

The log cat of the above program is given below...nullpointer exception is encountered in the program...someone please help me.. In the previous similar question,i couldnt find explanation.. Log cat: By changing the mentioned line i am getting the following EXCEPTION: 上面程序的日志猫在下面给出...在程序中遇到空指针异常...有人请帮助我..在前面的类似问题中,我找不到解释。.日志猫:通过更改上述行我正在获得以下例外情况:

 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)

The issue is this statement: 问题是这样的声明:

adapter.addAll(posts);

At this point in your onCreate method, posts is not yet initialized and contains NULL as value. 此时,在您的onCreate方法中, posts尚未初始化,并且包含NULL作为值。 You should either 你应该

  1. initialize posts before using it ( posts = new ArrayList<Post>() ) 在使用之前初始化postsposts = new ArrayList<Post>()
  2. since addAll(posts) probably won't have any effect when posts is empty, skip it alltogether. 由于在posts为空时addAll(posts)可能不会产生任何效果,因此请将其全部跳过。 You're calling addAll(posts) again anway in your onFeed method. 您将在onFeed方法中再次调用addAll(posts)

On a side note : I saw what you're re-initializing posts with an empty array within a loop in your onFeed() method. 附带说明 :我看到了您要在onFeed()方法的循环内用空数组重新初始化posts That won't do any good. 那不会有任何好处。 You should initialize your posts collection before the loop. 您应该在循环之前初始化posts集合。

adapter.addAll(posts); adapter.addAll(公告); Without creating a initializing you are trying to add it adapter. 没有创建初始化,您正在尝试添加适配器。 Here posts arraylist is null and you are filling the posts array in asynctask which was started after the above line. 这里posts arraylist为null,您将在上一行之后开始的asynctask中填充posts数组。 Remove the above line will work. 删除上面的行将起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试在空对象引用上调用接口方法&#39;java.lang.Object [] java.util.Collection.toArray()&#39; - Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference 搜索适配器 - 空对象引用上的“java.lang.Object[] java.util.Collection.toArray()” - Search adapter - 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference 在 null object 参考错误上实现搜索栏并获取“java.lang.Object[] java.util.Collection.toArray()” - Implementing search bar and getting 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference error java.lang.NullPointerException:尝试调用接口方法&#39;java.lang.Object java.util.List.get(int)&#39; - java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' 尝试在空对象引用上调用接口方法“java.lang.Object java.util.Map$Entry.getValue()” - Attempt to invoke interface method 'java.lang.Object java.util.Map$Entry.getValue()' on a null object reference java.lang.NullPointerException:尝试在 JSoup 库上调用接口方法“int java.lang.Comparable.compareTo(java.lang.Object)” - java.lang.NullPointerException: Attempt to invoke interface method 'int java.lang.Comparable.compareTo(java.lang.Object)' on JSoup Library 尝试在空对象引用上调用虚拟方法&#39;boolean java.util.ArrayList.add(java.lang.Object)&#39; - Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference Android NullPointer 尝试在空对象引用上调用虚拟方法“boolean java.util.ArrayList.add(java.lang.Object)” - Android NullPointer Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“boolean java.util.ArrayList.add(java.lang.Object)” - java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference java.lang.NullPointerException:尝试在空对象引用上调用接口方法“java.util.Iterator java.util.List.iterator()” - java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM