简体   繁体   中英

listView setAdapter null pointer exception?

I read a lot of post about this situation but ı can't find where ı'am wrong I need your help end advise :)

I try to make popoverView which show a search result. User post the searchKey. I have to parse json object which return from web services, and show the result in popoverView. I don't think the problemis in my parseJson class because when ı try only parseJson class it's work good so ı don't take in here.

ParseJsonSearchItem is parse class and SearchAdapter is costum adapter class.

Spend 2 days this situation but I don't have any solution please help me ?

Note: Sorry my English.

Thats the main activty to setAdapter.

package com.ip_dergi;

import org.brickred.socialauth.android.DialogListener;
import org.brickred.socialauth.android.SocialAuthAdapter;
import org.brickred.socialauth.android.SocialAuthAdapter.Provider;
import org.brickred.socialauth.android.SocialAuthError;
import org.brickred.socialauth.android.SocialAuthListener;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.daniel.lupianez.casares.PopoverView;
import com.daniel.lupianez.casares.PopoverView.PopoverViewDelegate;
import com.ip_dergi.loader.ImageLoader;
import com.ip_dergi.utils.ParseJsonSearchItem;
import com.ip_dergi.utils.SearchAdapter;
import com.ip_dergi.utils.Singleton;
import com.ip_dergi.utils.Singleton1;
import com.ip_dergi.utils.Typefaces;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

//içerik göstermek için içinde textVİew image view falan olacak

public class ItemContent extends Activity implements View.OnClickListener,
        PopoverViewDelegate, OnItemClickListener, OnEditorActionListener {

    TextView contentTxt, contentHeader;
    ImageView contentİmage;
    Intent intent;

    private Typefaces typeFaceTwitter;

    Typeface KlavikaMedium, KlavikaRegular;
    View menuButton;
    Button shareButton;
    View videoButton, backButton;
    TextView contentCategoryName;

    EditText searchEditText;
    ImageButton searcButton;
    SlidingMenu smenu;
    ListView lvSliding, lvSearch;

    PopoverView popoverView;
    boolean sendEmail = false, twittera = false, searchEditTextVisible = false;
    int screenWidth, screenHeight;
    ParseJsonSearchItem parseJsonSearchItem;
    SearchAdapter searchAdapter;

    private SocialAuthAdapter adapter;

    private StringBuilder message;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        setContentView(R.layout.activity_item_content);
        getScreenDimensions();

        // ------------------------------------- slidingMenu
        smenu = new SlidingMenu(this);
        smenu.setMode(SlidingMenu.LEFT);
        smenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        smenu.setShadowWidth(25);
        smenu.setFadeDegree(0.0f);
        smenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        smenu.setBehindWidth(250);
        smenu.setMenu(R.layout.sliding_menu1);

        lvSliding = (ListView) findViewById(R.id.listView_sliding_menu);
        lvSliding.setOnItemClickListener(this);

        Singleton b = Singleton.getInstance();
        ListAdapter adapter1 = new SimpleAdapter(ItemContent.this,
                b.getContentCategoryName(), R.layout.list_item, new String[] {
                        "catName", "id" }, new int[] { R.id.categoryName,
                        R.id.categoryID });
        lvSliding.setAdapter(adapter1);
        //--------------------------------------

        // ----------------------------------------------- social login
        adapter = new SocialAuthAdapter(new ResponseListener());
        adapter.addProvider(SocialAuthAdapter.Provider.FACEBOOK,
                R.drawable.white_color);
        message = new StringBuilder();
        //-------------------------------------------------

        lvSearch = (ListView) findViewById(R.id.search_item_listview);
        searchAdapter = new SearchAdapter(this, getApplication());
        lvSearch.setAdapter(searchAdapter);  // ***SETADAPTER HERE***

        searchEditText = (EditText) findViewById(R.id.searchEditText);
        searchEditText.setOnEditorActionListener(this);
        menuButton = (View) findViewById(R.id.menuButton);
        menuButton.setOnClickListener(this);
        shareButton = (Button) findViewById(R.id.share_button_view);
        shareButton.setOnClickListener(this);
        videoButton = (View) findViewById(R.id.video_button_view);
        videoButton.setOnClickListener(this);
        backButton = (View) findViewById(R.id.back_button_view);
        backButton.setOnClickListener(this);
        searcButton = (ImageButton) findViewById(R.id.searchButton);
        searcButton.setOnClickListener(this);

        KlavikaMedium = Typeface.createFromAsset(getAssets(),
                "font/Klavika-Medium.otf");
        KlavikaRegular = Typeface.createFromAsset(getAssets(),
                "font/KlavikaRegular-Plain.otf");

        typeFaceTwitter = new Typefaces();

        contentTxt = (TextView) findViewById(R.id.item_content_txt);
        contentTxt.setTypeface(KlavikaRegular);
        contentHeader = (TextView) findViewById(R.id.item_content_header);
        contentHeader.setTypeface(KlavikaMedium);
        contentİmage = (ImageView) findViewById(R.id.item_content_image);
        contentCategoryName = (TextView) findViewById(R.id.contentCategoryName);

        intent = getIntent();
        contentHeader.setText(intent.getStringExtra("contentHeader"));
        contentTxt.setText(intent.getStringExtra("contentTxt"));
        contentCategoryName.setText(intent
                .getStringExtra("contentCategoryName"));

        ImageLoader imgLoader = new ImageLoader(ItemContent.this);
        imgLoader.DisplayImage(intent.getStringExtra("contentİmageUrl"),
                R.anim.progress_anim, contentİmage);

    }

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub

        switch (view.getId()) {

        case R.id.searchButton:

            if (searchEditTextVisible == false) {
                searchEditText.setVisibility(View.VISIBLE);
                searchEditTextVisible = true;

            } else {
                searchEditText.setVisibility(View.GONE);
                searchEditText.setText("");
                searchEditTextVisible = false;
            }

            break;
        case R.id.menuButton:
            smenu.toggle();
            break;
        case R.id.back_button_view:
            finish();
            break;
        case R.id.video_button_view:

            break;
        case R.id.share_button_view:

            popoverViewShare(view);

            TextView faceText = (TextView) popoverView
                    .findViewById(R.id.facebookButton);
            faceText.setTypeface(KlavikaMedium);
            faceText.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    authorize(Provider.FACEBOOK);

                }
            });

            TextView twitText = (TextView) popoverView
                    .findViewById(R.id.twitterButton);
            twitText.setTypeface(typeFaceTwitter.get(getApplicationContext(),
                    "font/PICOBLA_.TTF"));
            twitText.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(), "click twitter",
                            Toast.LENGTH_LONG).show();

                }
            });

            TextView emailText = (TextView) popoverView
                    .findViewById(R.id.emailButton);

            emailText.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    sendEmail();
                    if (sendEmail == false) {
                        Log.d("sendEmail", "faild");
                    } else {
                        Log.d("sendEmail", "succes");
                        sendEmail = false;
                    }

                }
            });

            Log.d("ıtemContent", "share button press");

            break;

        default:
            break;
        }

    }

    private void authorize(final Provider provider) {
        adapter.authorize(ItemContent.this, provider);
        Toast.makeText(getApplicationContext(), "connect facebook",
                Toast.LENGTH_SHORT).show();
    }

    private void sendEmail() {
        final Intent intentEmail = new Intent(Intent.ACTION_SEND);
        intentEmail.setType("text/plain");
        intentEmail.putExtra(Intent.EXTRA_SUBJECT,
                intent.getStringExtra("contentHeader"));
        intentEmail.putExtra(Intent.EXTRA_TEXT,
                intent.getStringExtra("contentTxt"));

        startActivity(Intent.createChooser(intentEmail, "Send Email"));
        sendEmail = true;

    }

    private final class ResponseListener implements DialogListener {
        @Override
        public void onCancel() {
        }

        @Override
        public void onBack() {
        }

        @Override
        public void onComplete(final Bundle values) {
            if (message.length() >= 0) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                        .permitAll().build();
                StrictMode.setThreadPolicy(policy);
                if (adapter.getCurrentProvider().getProviderId()
                        .equalsIgnoreCase("facebook")) {
                    adapter.updateStory("Ip Dergi tarafından gönderildi",
                            intent.getStringExtra("contentHeader"), "",
                            intent.getStringExtra("contentTxt"), "",
                            intent.getStringExtra("contentİmageUrl"),
                            new MessageListener());

                    Log.d("send", "facebook");
                } else
                    adapter.updateStatus(message.toString(),
                            new MessageListener(), false);

            }

        }

        @Override
        public void onError(SocialAuthError socialAuthError) {
        }

        private final class MessageListener implements
                SocialAuthListener<Integer> {
            @Override
            public void onExecute(String provider, Integer status) {
                if (status == 200 || status == 201 || status == 204)
                    Toast.makeText(ItemContent.this,
                            "gönderildi : " + provider, Toast.LENGTH_LONG)
                            .show();
                else
                    Toast.makeText(ItemContent.this,
                            "Gönderilemedi" + provider, Toast.LENGTH_LONG)
                            .show();
            }

            @Override
            public void onError(SocialAuthError e) {
            }
        }
    }

    @Override
    public void popoverViewWillShow(PopoverView view) {
        // TODO Auto-generated method stub

    }

    @Override
    public void popoverViewDidShow(PopoverView view) {
        // TODO Auto-generated method stub

    }

    @Override
    public void popoverViewWillDismiss(PopoverView view) {
        // TODO Auto-generated method stub

    }

    @Override
    public void popoverViewDidDismiss(PopoverView view) {
        // TODO Auto-generated method stub

    }

    public void getScreenDimensions() {

        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        screenWidth = size.x;
        screenHeight = size.y;

        Toast.makeText(
                getApplicationContext(),
                "width" + Integer.toString(screenWidth) + "heigt"
                        + Integer.toString(screenHeight), Toast.LENGTH_LONG)
                .show();

    }

    public void popoverViewShare(View view) {

        RelativeLayout rootPopoView = (RelativeLayout) findViewById(R.id.content_item_layout);
        popoverView = new PopoverView(this, R.layout.share_item);
        popoverView.setContentSizeForViewInPopover(new Point(250, 250));
        popoverView.setDelegate(this);
        popoverView.showPopoverFromRectInViewGroup(rootPopoView,
                popoverView.getFrameForView(view),
                popoverView.PopoverArrowDirectionDown, true);

    }

    public void popoverViewSearch(View view) {

        RelativeLayout rootPopoView = (RelativeLayout) findViewById(R.id.content_item_layout);
        popoverView = new PopoverView(this, R.layout.search_result_listview);

        if (screenHeight > screenWidth) {
            popoverView.setContentSizeForViewInPopover(new Point(
                    screenWidth - 100, screenHeight / 2));

        } else {
            popoverView.setContentSizeForViewInPopover(new Point(
                    screenWidth / 2, screenHeight));
        }

        popoverView.showPopoverFromRectInViewGroup(rootPopoView,
                popoverView.getFrameForView(view),
                popoverView.PopoverArrowDirectionUp, true);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long İd) {
        // TODO Auto-generated method stub

        switch (parent.getId()) {
        case R.id.listView_sliding_menu:

            Singleton1 x = Singleton1.getInstance();
            x.setContentItemSelection(((TextView) view
                    .findViewById(R.id.categoryID)).getText().toString());
            Log.d("ıtemContent",
                    ((TextView) view.findViewById(R.id.categoryID)).getText()
                            .toString());

            finish();

            break;

        default:
            break;
        }

    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        View searchView = findViewById(R.id.searchButton);
        // TODO Auto-generated method stub
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            Toast.makeText(getApplicationContext(), searchEditText.getText(),
                    Toast.LENGTH_LONG).show();

            if (searchEditText != null) {

                String searchKey = searchEditText.getText().toString();
                popoverViewSearch(searchView);
                parseJsonSearchItem = new ParseJsonSearchItem(ItemContent.this,
                        this.getApplication(),searchAdapter);

                parseJsonSearchItem.execute(searchKey);
            }

            return true;
        }
        return false;
    }

}

And the adapter class extends baseAdapter

package com.ip_dergi.utils;

import java.util.ArrayList;

import android.app.Application;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.ip_dergi.R;
import com.ip_dergi.loader.ImageLoader;

public class SearchAdapter extends BaseAdapter {

    private Context mContext;
    private Application mApplication;
    private ArrayList<Utils> mUtilsArraylist = new ArrayList<Utils>();

    public SearchAdapter(Context con, Application app) {
        this.mContext = con;
        this.mApplication = app;
    }

    public void GetMoreItem(ArrayList<Utils> arrayList) {
        mUtilsArraylist = arrayList;
        notifyDataSetChanged();

    }

    @Override
    public int getCount() {
        return mUtilsArraylist == null ? 0 : mUtilsArraylist.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;

        final Utils utils=mUtilsArraylist.get(position);

        String searchImageUrl=utils.searchImageUrl;

        if (convertView == null) {
            SearchHolder holder = new SearchHolder();
            view = View.inflate(mContext, R.layout.search_row_item, null);

            holder.searchImageArea = (ImageView) view
                    .findViewById(R.id.searchImage);
            holder.searchTextArea = (TextView) view
                    .findViewById(R.id.searchDesc);
            holder.searchDateArea = (TextView) view
                    .findViewById(R.id.searchDate);
            holder.searchCategoryArea = (TextView) view
                    .findViewById(R.id.searchCategory);

            view.setTag(holder);

        } else {
            return convertView;
        }

        final SearchHolder searchHolder= (SearchHolder) view.getTag();

        searchHolder.searchCategoryArea.setText(utils.searchContentCategory);
        searchHolder.searchDateArea.setText(utils.searchContentDate);
        searchHolder.searchTextArea.setText(utils.searchTextDesc);


        ImageLoader searchImageLoader= new ImageLoader(mApplication);
        searchImageLoader.DisplayImage(searchImageUrl, searchHolder.searchImageArea);

        return view;
    }

    public class SearchHolder {

        ImageView searchImageArea;
        TextView searchTextArea;
        TextView searchDateArea;
        TextView searchCategoryArea;

    }

}

now Layouts

search_result_listview.xml

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <ListView
            android:id="@+id/search_item_listview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true" >
        </ListView>

    </RelativeLayout>

search_row_item.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_marginTop="15dp"
        android:background="@color/white"
        android:minHeight="70dp" 
        android:id="@+id/search_listview_row">

        <ImageView
            android:id="@+id/searchImage"
            android:layout_width="150dp"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:background="@color/gray"
            android:scaleType="fitXY" />

        <TextView
            android:id="@+id/searchDesc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="17dp"
            android:layout_marginTop="10dp"
            android:layout_toRightOf="@+id/searchImage"
            android:text="Some text"
            android:textColor="@color/black"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/searchCategory"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/searchDesc"
            android:layout_centerVertical="true"
            android:layout_marginLeft="17dp"
            android:layout_marginTop="10dp"
            android:layout_toRightOf="@+id/searchImage"
            android:text="Some text"
            android:textColor="@color/black"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/searchDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/searchCategory"
            android:layout_marginLeft="17dp"
            android:layout_toRightOf="@+id/searchImage"
            android:text="Some text"
            android:textColor="@color/black"
            android:textSize="16sp" />

    </RelativeLayout>

Finally the error message

10-03 04:44:26.201: E/ViewRootImpl(20281): sendUserActionEvent() mView == null
10-03 04:44:29.431: E/AndroidRuntime(20281): FATAL EXCEPTION: main
10-03 04:44:29.431: E/AndroidRuntime(20281): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ip_dergi/com.ip_dergi.ItemContent}: java.lang.NullPointerException
10-03 04:44:29.431: E/AndroidRuntime(20281):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at android.app.ActivityThread.access$700(ActivityThread.java:150)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at android.os.Handler.dispatchMessage(Handler.java:99)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at android.os.Looper.loop(Looper.java:137)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at android.app.ActivityThread.main(ActivityThread.java:5279)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at java.lang.reflect.Method.invokeNative(Native Method)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at java.lang.reflect.Method.invoke(Method.java:511)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at dalvik.system.NativeStart.main(Native Method)
10-03 04:44:29.431: E/AndroidRuntime(20281): Caused by: java.lang.NullPointerException
10-03 04:44:29.431: E/AndroidRuntime(20281):    at com.ip_dergi.ItemContent.onCreate(ItemContent.java:115)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at android.app.Activity.performCreate(Activity.java:5267)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
10-03 04:44:29.431: E/AndroidRuntime(20281):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
10-03 04:44:29.431: E/AndroidRuntime(20281):    ... 11 more

I'll take a guess (you really need to answer the earlier questions of where is line 115).

In getView, you properly inflate a new view when convertView is null:

   if (convertView == null) {
        SearchHolder holder = new SearchHolder();
        view = View.inflate(mContext, R.layout.search_row_item, null);
        ...
    } else {
        return convertView;
    }

And then you follow with some more initialization. I suspect that initialization needs to happen for the not-null case, too. For example, you fetch "utils" from your array and use it for some of the initialization when convertView is null. But when you reuse convertView, you appear to keep the old values, which belong to the old "position", not the current one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM