nullpointerexception使用setadapter和自定义类

时间:2014-07-24 09:37:01

标签: java android nullpointerexception

我试图显示一个imageview - textview组合,但在尝试实际显示数据时我一直遇到错误。

我试图从用户那里获取输入以搜索某些内容 - 然后运行一些后台方法来提取数据。然后我将有2个数组充满数据,然后我做"项目" object并将其传递给我的Custom Adapter类。

我试图利用方形毕加索从URL加载一些图像。我认为这可能是问题所在,但错误是来自setadapter。

很抱歉发布了这么多代码!

这是我的MainActivity.java

public class MainActivity extends ActionBarActivity {

    String url = "https://www.google.com/search?hl=en&tbm=shop&q=";
    ProgressDialog mProgressDialog;
    float x1,x2;
    float y1, y2;
    ImageButton button;
    int buttonPressed = 0;
    private ListView listView1;


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

        button = (ImageButton) findViewById(R.id.search_button);
        button.setOnClickListener(new OnClickListener()
        {
            public void onClick(View arg0)
            {
                new Search().execute();
            }
        });


    }

    private class Search extends AsyncTask<Void, Void, Void> {
        String title = "blah";
        String prices[] = new String[10];
        String description[] = new String[10];
        String stores[] = new String[10];
        String full[] = new String[10]; // change this 40
        String linksContainer[] = new String[10];
        String imgContainer[] = new String[10];
        @Override

        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = new ProgressDialog(MainActivity.this);
            mProgressDialog.setTitle("Salert");
            mProgressDialog.setMessage("Searching...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                EditText edit =  (EditText) findViewById(R.id.search_field);
                String search = edit.getText().toString().replaceAll("\\s","\\+");



                // Connect to the web site
                Document document = Jsoup.connect(url+search).get();
                // Get the html document title
                Elements stuff = document.select("div[class=psgicont]"); 
                Iterator<Element> iter = stuff.iterator();
                Element temp;
                //String str = "";
                //int index, index2;
                Elements links = document.select("a[class=psgiimg]");
                Iterator<Element> iterImage = links.iterator();
                Element tempImage;


                for(int i = 0; i < 10; i++) // change this to 40
                {
                    temp = iter.next();
                    full[i] = temp.text();
                    /*

                    index = str.indexOf('$');
                    index2 = str.indexOf("from");
                    description[i] = str.substring(0, index - 1);
                    prices[i] = str.substring(index,index2 - 1);
                    stores[i] = str.substring(index2 + 5, str.length());

                    full[i] = description[i] + "\n" + prices[i] + " from " + stores[i];
                    */
                }
                for(int j=0; j < 10; j++)
                {
                    tempImage = iterImage.next();
                    linksContainer[j] = tempImage.attr("abs:href");
                    //Log.d("message", linksContainer[j]);
                }

                for (int k=0; k < 10; k++)
                { 
                    String url = linksContainer[k];
                    Document document2 = Jsoup.connect(url).get();
                    Elements link = document2.select("div[id=pp-altimg-init-main] > img");
                    imgContainer[k] = link.attr("src");
                    Log.d("img link", imgContainer[k]);
                }

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

        @Override
        protected void onPostExecute(Void result) 
        {
            /*
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                    R.layout.list_view, R.id.label, full);

            ListView listView = (ListView) findViewById(R.id.list);
            listView.setAdapter(adapter);*/

            Item item_data[] = new Item[]
            {
                new Item(imgContainer[0], full[0]),
                new Item(imgContainer[1], full[1]),
                new Item(imgContainer[2], full[2]),
                new Item(imgContainer[3], full[3]),
                new Item(imgContainer[4], full[4]),
                new Item(imgContainer[5], full[5]),
                new Item(imgContainer[6], full[6]),
                new Item(imgContainer[7], full[7]),
                new Item(imgContainer[8], full[8]),
                new Item(imgContainer[9], full[9])
            };

            ItemAdapter adapter = new ItemAdapter(MainActivity.this, R.layout.list_view, item_data);

            listView1 = (ListView)findViewById(R.id.listView1);

            listView1.setAdapter(adapter);

            mProgressDialog.dismiss();
            buttonPressed ++;
        }

    }

}

ItemAdapter.java

package com.example.salert;

import com.squareup.picasso.Picasso;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ItemAdapter extends ArrayAdapter<Item>{

    Context context;
    int layoutResourceId;    
    Item data[] = null;

    public ItemAdapter(Context context, int layoutResourceId, Item[] data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }

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

        View row = convertView;
        ItemHolder holder = null;

        if(row == null)
        {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new ItemHolder();
            holder.url = (ImageView)row.findViewById(R.id.img);
            holder.description = (TextView)row.findViewById(R.id.label);

            row.setTag(holder);
        }
        else
        {
            holder = (ItemHolder)row.getTag();
        }

        Item item = data[position];
        holder.description.setText(item.description);
        //holder.url.setImageURI(item.url);
        Picasso.with(context).load(item.url).into(row);


        return row;
    }

    static class ItemHolder
    {
        ImageView url;
        TextView description;
    }

}

这是我的项目课程 - 基本内容

package com.example.salert;

public class Item{
    public String url;
    public String description;
    public Item(){
        super();
    }

    public Item(String url, String description){
        super();
        this.url = url;
        this.description = description;
    }
}

这是我的list_view.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="wrap_content" 
    android:background="#303541"
    android:id="@+id/listView1">

 <ImageView android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:gravity="center_vertical"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="15dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
  />


<TextView android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center_vertical"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:textStyle="bold"
        android:textSize="22dp"
        android:textColor="#000000"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp" />

  <Button android:text="@string/add"
          android:id="@+id/addButton"
          android:layout_marginTop="2dip"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:onClick="addItemHandler"
          android:gravity="right" />

</ListView>

这是main_activty.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.bigbang.salertapp.MainActivity" 
    android:background ="@drawable/logo" >

           <EditText
            android:id="@+id/search_field"
            android:layout_alignParentLeft="true"
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content"
            android:paddingLeft="12dp"
            android:singleLine="true"
            android:textColor="#737373"
            android:background="@drawable/search"
            android:hint="@string/search" 
            />

       <ImageButton android:id="@+id/search_button"
                android:layout_width="20dip" 
                android:layout_height="20dip"
                android:layout_marginRight="12dip"
                android:layout_marginTop="2dip"
                android:layout_alignRight="@+id/search_field"
                android:layout_alignTop="@+id/search_field"
                android:layout_alignParentRight="true"
                android:contentDescription="@string/searchbuttonCD"
                android:background="@drawable/sbicon1"
            />

    <ListView 
     android:layout_marginTop="2dip"
     android:id="@+id/list"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_below="@id/search_field" 
     android:background="#303541"/> 



</RelativeLayout>

这是logcat

07-24 02:41:21.014: W/dalvikvm(6505): threadid=1: thread exiting with uncaught exception (group=0x413e2438)
07-24 02:41:21.024: E/AndroidRuntime(6505): FATAL EXCEPTION: main
07-24 02:41:21.024: E/AndroidRuntime(6505): java.lang.NullPointerException
07-24 02:41:21.024: E/AndroidRuntime(6505):     at com.example.salert.MainActivity$Search.onPostExecute(MainActivity.java:174)
07-24 02:41:21.024: E/AndroidRuntime(6505):     at com.example.salert.MainActivity$Search.onPostExecute(MainActivity.java:1)
07-24 02:41:21.024: E/AndroidRuntime(6505):     at android.os.AsyncTask.finish(AsyncTask.java:631)
07-24 02:41:21.024: E/AndroidRuntime(6505):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-24 02:41:21.024: E/AndroidRuntime(6505):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
07-24 02:41:21.024: E/AndroidRuntime(6505):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-24 02:41:21.024: E/AndroidRuntime(6505):     at android.os.Looper.loop(Looper.java:137)
07-24 02:41:21.024: E/AndroidRuntime(6505):     at android.app.ActivityThread.main(ActivityThread.java:4905)
07-24 02:41:21.024: E/AndroidRuntime(6505):     at java.lang.reflect.Method.invokeNative(Native Method)
07-24 02:41:21.024: E/AndroidRuntime(6505):     at java.lang.reflect.Method.invoke(Method.java:511)
07-24 02:41:21.024: E/AndroidRuntime(6505):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
07-24 02:41:21.024: E/AndroidRuntime(6505):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
07-24 02:41:21.024: E/AndroidRuntime(6505):     at dalvik.system.NativeStart.main(Native Method)

UPDATE 问题可能来自ItemAdapter类中的picasso.with(context)行。这就是我实际显示网址图片的地方。

1 个答案:

答案 0 :(得分:1)

在您的活动xml中,您声明了一个标识为android:id="@+id/list"的ListView,但在AsyncTask中您正在寻找listView1 = (ListView)findViewById(R.id.listView1);,您将其用作 row_item.xml的root用户。我猜你想改变

listView1 = (ListView)findViewById(R.id.listView1);

listView1 = (ListView)findViewById(R.id.list);

并删除list_view.xml

中的ListView