在从其他类访问变量时获取NullPointerException - Android

时间:2014-02-28 06:49:53

标签: android nullpointerexception rss widget feed

从其他类访问变量时获取NullPointerException。

下面是我在活动中的RSS提要解析器工作得很好,但是当我尝试在另一个类中访问RemoteView(主屏幕小组件)的相同参数时,该参数返回空指针异常,这显然意味着值为null。任何想法我如何使用相同的代码片段并从那里选择价值。在代码中我提到了行“PICK VALUE(从哪个参数值中选择)”和PUT VALUE(放在哪里)以便更好地理解。

我的目标是在“populateListItem()”方法中的ListProvider类中使用TwitterAdapter,其中我写了“PUT VALUE”。在那里我想访问这个值“imageAndTexts1.get(position).getTitle();”来自TwitterAdapter类。我怎么能这样做?

如果我在方法populateListItem()中尝试这样,我将得到以下异常:

private void populateListItem() {
        //for (int i = 0; i < 10; i++) {
            ListItem listItem = new ListItem();

            TwitterAdapter abc = new TwitterAdapter(null, imageAndTexts1); //TRIED TO ACCESS VALUE
            String a = abc.passtitletowidget; // TRIED TO ACCESS VALUE

            listItem.heading = a;
            listItem.content = "This is the content of the app widget listview.Nice content though";
            listItemList.add(listItem);
        //}
    }

例外细节:

02-28 13:42:22.271: E/AndroidRuntime(26600): FATAL EXCEPTION: main
02-28 13:42:22.271: E/AndroidRuntime(26600): java.lang.RuntimeException: Unable to bind to service com.wordpress.laaptu.WidgetService@42a2f118 with Intent { dat=intent: cmp=com.itcuties.multicategoryrssreader/com.wordpress.laaptu.WidgetService (has extras) }: java.lang.NullPointerException
02-28 13:42:22.271: E/AndroidRuntime(26600):    at android.app.ActivityThread.handleBindService(ActivityThread.java:2739)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at android.app.ActivityThread.access$1800(ActivityThread.java:168)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at android.os.Looper.loop(Looper.java:137)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at android.app.ActivityThread.main(ActivityThread.java:5493)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at java.lang.reflect.Method.invokeNative(Native Method)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at java.lang.reflect.Method.invoke(Method.java:525)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at dalvik.system.NativeStart.main(Native Method)
02-28 13:42:22.271: E/AndroidRuntime(26600): Caused by: java.lang.NullPointerException
02-28 13:42:22.271: E/AndroidRuntime(26600):    at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:153)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at com.rssfeed.adapter.TwitterAdapter.<init>(TwitterAdapter.java:47)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at com.wordpress.laaptu.ListProvider.populateListItem(ListProvider.java:42)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at com.wordpress.laaptu.ListProvider.<init>(ListProvider.java:34)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at com.wordpress.laaptu.WidgetService.onGetViewFactory(WidgetService.java:19)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at android.widget.RemoteViewsService.onBind(RemoteViewsService.java:241)
02-28 13:42:22.271: E/AndroidRuntime(26600):    at android.app.ActivityThread.handleBindService(ActivityThread.java:2726)

** PACKAGE ONE

TwitterAdapter.java

public class TwitterAdapter extends ArrayAdapter<RssFeedStructure> {
    List<RssFeedStructure> imageAndTexts1 = null;
    Context context;
    public static String passtitletowidget;         

    public TwitterAdapter(Activity activity,List<RssFeedStructure> imageAndTexts) {
        super(activity, 0, imageAndTexts);
        imageAndTexts1 = imageAndTexts;
    }

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

        context = getContext();
        Activity activity = (Activity) getContext();
        LayoutInflater inflater = activity.getLayoutInflater();

        View rowView = inflater.inflate(R.layout.twitteradapter, null);
        TextView textView = (TextView) rowView.findViewById(R.id.feed_text);
        TextView timeFeedText = (TextView) rowView.findViewById(R.id.feed_updatetime);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.feed_image);
        try {               
            passtitletowidget = imageAndTexts1.get(position).getTitle();  //PICK VALUE    
            Log.d("rssfeed", "imageAndTexts1.get(position).getImgLink() :: " + imageAndTexts1.get(position).getImgLink() + " :: " + imageAndTexts1.get(position).getTitle());

            //Underline HashTags -- To identify Mentioned user name; use this "@([A-Za-z0-9_-]+)"
            SpannableString hashtagintitle = new SpannableString(imageAndTexts1.get(position).getTitle());
            Matcher matcher = Pattern.compile("#([A-Za-z0-9_-]+)").matcher(hashtagintitle);
            while (matcher.find())
            {
                hashtagintitle.setSpan(new ForegroundColorSpan(Color.BLUE), matcher.start(), matcher.end(), 0);                 
            }
            textView.setText(hashtagintitle);

            timeFeedText.setText(imageAndTexts1.get(position).getPubDate());

            //Underline Date
            /*SpannableString content = new SpannableString(imageAndTexts1.get(position).getPubDate());
            content.setSpan(new UnderlineSpan(), 0, 13, 0);
            timeFeedText.setText(content);*/

            if (imageAndTexts1.get(position).getImgLink() != null) {

                URL feedImage = new URL(imageAndTexts1.get(position)
                        .getImgLink().toString());
                if (!feedImage.toString().equalsIgnoreCase("null")) {
                    HttpURLConnection conn = (HttpURLConnection) feedImage
                            .openConnection();
                    InputStream is = conn.getInputStream();
                    Bitmap img = BitmapFactory.decodeStream(is);
                    imageView.setImageBitmap(img);
                } else {
                    imageView.setBackgroundResource(R.drawable.rss_tab_tweets);
                }
            }

            //Share Button
            Button Button1= (Button)  rowView.findViewById(R.id.sharebutton);
            Button1.setOnClickListener(new OnClickListener() 
            { 
                   @Override
                   public void onClick(View v) 
                   {
                        //Share Data
                        String shareBody = imageAndTexts1.get(position).getDescription();
                        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
                        sharingIntent.setType("text/plain");
                        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
                        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
                        context.startActivity(Intent.createChooser(sharingIntent, shareBody));
                        //Share Data ends
                   }    
            });
            //Share Button ends

            //OpenWith Button
            Button Button2= (Button)  rowView.findViewById(R.id.openwith);
            Button2.setOnClickListener(new OnClickListener() 
            { 
                   @Override
                   public void onClick(View v) 
                   {
                        //OpenWith Data
                        Intent i = new Intent(Intent.ACTION_VIEW);
                        // We have to set data for our new Intent
                        i.setData(Uri.parse(imageAndTexts1.get(position).getLink()));
                        // And start activity with our Intent
                        context.startActivity(i);
                        //OpenWith Data ends
                   }    
            });
            //OpenWith Button ends

        } catch (MalformedURLException e) {

        } catch (IOException e) {

        }   
        return rowView;    
    }    
}

TwitterFeeds.java

public class TwitterFeeds extends Activity {

    /** Called when the activity is first created. */

    ListView _rssFeedListView;
    List<JSONObject> jobs;
    List<RssFeedStructure> rssStr;
    private TwitterAdapter _adapter;
    TextView textview;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);
        _rssFeedListView = (ListView) findViewById(R.id.rssfeed_listview);
        textview = (TextView) findViewById(R.id.loading);
        RssFeedTask rssTask = new RssFeedTask();
        rssTask.execute();
    }

    public class RssFeedTask extends AsyncTask<String, Void, String> {
        // private String Content;
        private ProgressDialog Dialog;
        String response = "";

        @Override
        public void onPreExecute() {

        }

        @Override
        public String doInBackground(String... urls) {
            try {
                String feed = "https://script.google.com/macros/s/AKfycbyRHtGY0TW5WRifXwMMRDQdtseKXxrYUbTcUlx1QxvUz-aap7Q/exec?action=timeline&q=SriSri";
                XmlHandler rh = new XmlHandler();
                rssStr = rh.getLatestArticles(feed);
            } catch (Exception e) {
            }
            return response;

        }

        @Override
        public void onPostExecute(String result) {

            if (rssStr != null) {
                _adapter = new TwitterAdapter(TwitterFeeds.this, rssStr);
                _rssFeedListView.setAdapter(_adapter);
                textview.setVisibility(View.INVISIBLE);

                _rssFeedListView.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        //Toast.makeText(getBaseContext(), "TwitterFeeds", Toast.LENGTH_LONG).show();
                        // TODO Auto-generated method stub

                    }
                });
            }


        }

    }

}

RssFeedStructure.java

public class RssFeedStructure {

    // private long articleId;
    // private long feedId;
    private String title;
    private String description;
    private String imgLink;
    private String pubDate;
    private String link;
    private String published;
    private String content;
    private URL url;
    private String encodedContent;

    /*
     * public long getArticleId() { return articleId; }
     * 
     * public void setArticleId(long articleId) { this.articleId = articleId; }
     * 
     * public long getFeedId() { return feedId; }
     * 
     * 
     * public void setFeedId(long feedId) { this.feedId = feedId; }
     */

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {

        String noHTMLStringtitle = title.replaceAll("\\<.*?>", "");
        String replaceampersandtitle = noHTMLStringtitle.replace("&amp;", "&");
        String yesHTMLStringtitle = Html.fromHtml(replaceampersandtitle)
                .toString();
        this.title = yesHTMLStringtitle;

    }

    public URL getUrl() {
        return url;
    }

    public void setUrl(URL url) {
        this.url = url;
    }

    public void setDescription(String description) {
        String noHTMLStringDes = description.replaceAll("\\<.*?>", "");
        String replaceampersand = noHTMLStringDes.replace("&amp;", "&");
        String yesHTMLStringDes = Html.fromHtml(replaceampersand).toString();
        this.description = yesHTMLStringDes;

        // Link to understand unicode characters -
        // http://bohemianalps.com/tools/characters/?faveAlph=frac14,frac12,frac34,copy,reg,trade,laquo,raquo&faveNum=171,187,40,41,8216,8217,8220,8221,169,174,64,8482,x2122,8211,8212,225,233,241

    }

    public String getDescription() {
        return description;
    }

    public void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }

    public String getPubDate() {
        return pubDate;
    }

    public void setEncodedContent(String encodedContent) {
        // this.encodedContent = encodedContent;
        // String noHTMLString = encodedContent.replaceAll("\\<.*?>","");
        // String replaceampersand = noHTMLString.replace("&amp;", "&");
        // String yesHTMLString= Html.fromHtml(replaceampersand).toString();
        // this.encodedContent = yesHTMLString;
        // Link to understand unicode characters -
        // http://bohemianalps.com/tools/characters/?faveAlph=frac14,frac12,frac34,copy,reg,trade,laquo,raquo&faveNum=171,187,40,41,8216,8217,8220,8221,169,174,64,8482,x2122,8211,8212,225,233,241

        /*if (encodedContent.contains("<img ")){
            String img = encodedContent.substring(encodedContent.indexOf("<img "));
            String cleanUp = img.substring(0, img.indexOf(">")+1);
            img = img.substring(img.indexOf("src=") + 5);
            int indexOf = img.indexOf("'");
            if (indexOf==-1){
            indexOf = img.indexOf("\"");
            }
            img = img.substring(0, indexOf);

            this.encodedContent = this.encodedContent.replace(cleanUp, "");

        }*/
        String removeimages = encodedContent.replaceAll("<img.+?>", "");
        this.encodedContent = removeimages;
    }

    public String getEncodedContent() {
        return encodedContent;
    }

    public void setImgLink(String imgLink) {
        this.imgLink = imgLink;
    }

    public String getImgLink() {
        return imgLink;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public String getLink() {
        return link;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }

    public void setPublished(String published) {
        this.published = published;
    }

    public String getPublished() {
        return published;
    }

}

** PACKAGE TWO

ListProvider.java

public class ListProvider implements RemoteViewsFactory {
    private ArrayList<ListItem> listItemList = new ArrayList<ListItem>();
    private Context context = null;
    private int appWidgetId;
    static String passtitletowidget;
    List<RssFeedStructure> imageAndTexts1 = null;

    public ListProvider(Context context, Intent intent) {
        this.context = context;
        appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);

        populateListItem();
    }

    private void populateListItem() {
        //for (int i = 0; i < 10; i++) {
            ListItem listItem = new ListItem();

            listItem.heading = "passtitletowidget";  //PUT VALUE
            listItem.content = "This is the content of the app widget listview.Nice content though";
            listItemList.add(listItem);
        //}
    }

    @Override
    public int getCount() {
        return listItemList.size();
    }

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

    /*
     *Similar to getView of Adapter where instead of View
     *we return RemoteViews 
     * 
     */
    @Override
    public RemoteViews getViewAt(int position) {
        final RemoteViews remoteView = new RemoteViews(
                context.getPackageName(), R.layout.list_row);
        ListItem listItem = listItemList.get(position);

        remoteView.setTextViewText(R.id.heading, listItem.heading);
        remoteView.setTextViewText(R.id.content, listItem.content);

        return remoteView;
    }

    @Override
    public RemoteViews getLoadingView() {
        return null;
    }

    @Override
    public int getViewTypeCount() {
        return 1;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public void onCreate() {
    }

    @Override
    public void onDataSetChanged() {
    }

    @Override
    public void onDestroy() {
    }   
}

ListItem.java

public class ListItem {
    public String heading, content;
}

WidgetProvider.java

public class WidgetProvider extends AppWidgetProvider {

    /* 
     * this method is called every 30 mins as specified on widgetinfo.xml
     * this method is also called on every phone reboot
     */
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        final int N = appWidgetIds.length;
        /*int[] appWidgetIds holds ids of multiple instance of your widget
         * meaning you are placing more than one widgets on your homescreen*/
        for (int i = 0; i < N; ++i) {
            RemoteViews remoteViews = updateWidgetListView(context,
                    appWidgetIds[i]);
            appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
        }
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    private RemoteViews updateWidgetListView(Context context, int appWidgetId) {

        //which layout to show on widget
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.widget_layout);

        //RemoteViews Service needed to provide adapter for ListView
        Intent svcIntent = new Intent(context, WidgetService.class);
        //passing app widget id to that RemoteViews Service
        svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        //setting a unique Uri to the intent
        //don't know its purpose to me right now
        svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
        //setting adapter to listview of the widget
        remoteViews.setRemoteAdapter(appWidgetId, R.id.listViewWidget,svcIntent);
        //setting an empty view in case of no data
        remoteViews.setEmptyView(R.id.listViewWidget, R.id.empty_view);
        return remoteViews;
    }

}

WidgetService.java

public class WidgetService extends RemoteViewsService {
    /*
     * So pretty simple just defining the Adapter of the listview
     * here Adapter is ListProvider
     * */

    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent) {
        int appWidgetId = intent.getIntExtra(
                AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);

        return (new ListProvider(this.getApplicationContext(), intent));
    }

}

1 个答案:

答案 0 :(得分:0)

您需要在ListProvider文件中安装TwitterAdapter实例。在初始化ListProvider时,您可以将TwitterAdapter实例作为参数发送到ListProvider构造函数。

可能你必须在主要活动中初始化TwitterAdapter&amp; ListProvider。