当前位置: 首页 > 知识库问答 >
问题:

actionbar上不确定progressbar的空指针异常

姬寂离
2023-03-14

所以我已经开始创建一个应用程序,它使用jsoup来取消股票数据。当我通过导航抽屉从home活动转移到'Stocks'活动时,我要求结果活动显示第一个片段(视图中的RecycerView),该片段刮擦并列出所有股票。但是,这总是导致以下错误。但是,如果将片段作为第三个片段放入,并按下图所示打开(编辑:还不能发布图片),它就像预期的那样工作了。

9200-9200/com.blueinklabs.InvestmentPortfolioPakistan e/androidRuntime:致命异常:main process:com.blueinklabs.InvestmentPortfolioPakistan,PID:9200 java.lang.nullpointerException:试图在com.blueinklabs.InvestmentPortfolioPakistan.stocksactivity.showProgressBar(stocksactivity.java:68)和在Android.os.asynctask.execute(asynctask.java:591)在com.blueinklabs.InvestmentPortfolioPakistan.stockData.(stockdata.java:539)在com.blueinklabs.InvestmentPortfolioPakistan.stockData.(stockdata.java:28)在com.blueinklabs.InvestmentPortfolioPakistan.stocksCompleteListfragment.getsymbols(n.stocksCompleteListFragment.oncreateView(stocksCompleteListFragment.java:48)在Android.support.v4.app.fragment.performCreateView(fragment.java:1789)在Android.support.v4.app.fragmentManagerimpl.moveTostate(fragmentManager.java:955)在Android.support.v4.app.fragmentManagerimpl.moveTostate(fragmentManager.java:1138)在:1501)在Android.support.v4.app.fragmentManagerImpl.ExecutePendingTransactions(FragentManager.java:490)在Android.support.v4.app.fragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)在Android.support.v4.view.viewPager.populate(ViewPager.java:1105)在Android.support.v4.view.viewPager.populate(ViewPager.java:1105)在andro的viewgroup.MeasureChildWithMargins(viewgroup.java:5535)id.support.design.widget.coordinatorlayout.onmeasurchild(coordinatorlayout.java:573),在Android.support.design.widget.coordinatorlayout.onmeasure(coordinatorlayout.java:640),在Android.support.design.widget.coordinatorlayout.java:640,在Android.support.v4.widget.drawerlayout.measure(view.java:17547),在.internal.widget.contentframelayout.onmeasure(contentframelayout.java:124)在Android.view.viewgroup.measure(view.java:17547)在Android.view.viewgroup.measure ChildWith Margins(viewgroup.java:5535)在Android.widget.linearlayout.measureChildBeRealayout(linearlayout.java:1436)在Android.widget.linearlayout.java:722)在在Android.widget.framelayout.onMeasure(framelayout.java:436)在Android.view.view.viewgroup.measure(view.java:17547)在Android.view.viewgroup.measure ChildWith Margins(viewgroup.java:5535)在Android.widget.linearlayout.measuryChildbeRelayout(linearlayout.java:1436)在Android.widget.linearlayout.java:722)在p.measureChildWith Margins(viewgroup.java:5535)在Android.widget.framelayout.onMeasure(framelayout.java:436)在com.android.internal.policy.impl.phoneWindow$decorview.onMeasure(framelayout.java:2615)在Android.view.view.view.view.measure(view.java:17547)在Android.view.viewrootimpl.performMeasure(viewrootimpl.java:1061)在Android.view.viewrootimpl$traversalrunnable.run(viewrootimpl.java:588

我认为问题在于异步任务(如下)发生在onPrepareOptionsMenu加载之前。在下面类的预执行时发生错误:

import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Iterator;

public class StockData {
    private ArrayList<String> symbolList;
    Context myContext;
    RecyclerView recyclerV;

    public StockData(Context getcontext, RecyclerView recyclerView){
        myContext = getcontext;
        symbolList = new ArrayList<String>();
        recyclerV = recyclerView;
        new Title().execute();
    }

    private class Title extends AsyncTask<Void, Void, Void> {
        String title;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ((StocksActivity) myContext).showProgressBar();
        }

        @Override
        protected Void doInBackground(Void... params) {
            Document doc = null;
            try {
                doc = Jsoup.connect("websiteurl").get();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Element table = doc.select("table.mGrid").get(1);
            Elements rows = table.select("tr");
            Iterator<Element> rowIterator = rows.iterator();
            rowIterator.next();

            while (rowIterator.hasNext()) {
                Element row = rowIterator.next();
                Elements cols = row.select("td");
                symbolList.add(cols.get(1).text());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            ((StocksCompleteListFragment.SimpleStringRecyclerViewAdapter) recyclerV.getAdapter()).changeList(symbolList);
            ((StocksActivity) myContext).hideProgressBar();
        }
    }

    public ArrayList<String> getSymbolList(){
        return symbolList;
    }


}

stocksactivity.java如下所示:

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 */
public class StocksActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;
    public MenuItem miActionProgressItem;

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // Store instance of the menu item containing progress
        miActionProgressItem = menu.findItem(R.id.mi_ActionProgress);
        // Extract the action-view from the menu item
        ProgressBar v = (ProgressBar) MenuItemCompat.getActionView(miActionProgressItem);
        // Return to finish
        Toast.makeText(this, "Hi", Toast.LENGTH_SHORT).show();
        return super.onPrepareOptionsMenu(menu);
    }

    public void showProgressBar() {
        // Show progress item
        miActionProgressItem.setVisible(true);
    }

    public void hideProgressBar() {
        // Hide progress item
        miActionProgressItem.setVisible(false);
    }

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        ab.setDisplayHomeAsUpEnabled(true);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        if (navigationView != null) {
            setupDrawerContent(navigationView);
            final Menu navMenu = navigationView.getMenu();
            ((MenuItem) navMenu.findItem(R.id.menuItem1)).setChecked(true);
            final ArrayList<View> mMenuItems = new ArrayList<>(navigationView.getChildCount());
            //for (int i = 0; i < navigationView.getChildCount(); i++){
            navigationView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    // Remember to remove the installed OnGlobalLayoutListener
                    navigationView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    // Loop through and find each MenuItem View
                    for (int i = 0; i < 6; i++) {
                        final String id = "menuItem" + (i);
                        final MenuItem item = navMenu.findItem(getResources().getIdentifier(id, "id", getPackageName()));
                        navigationView.findViewsWithText(mMenuItems, item.getTitle(), View.FIND_VIEWS_WITH_TEXT);
                    }
                    // Loop through each MenuItem View and apply your custom Typeface
                    for (final View menuItem : mMenuItems) {
                        ((TextView) menuItem).setTypeface(null, Typeface.BOLD);
                        ((TextView) menuItem).setTextSize(14);
                    }
                }
            });
            //}

        }

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        if (viewPager != null) {
            setupViewPager(viewPager);
        }

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.sample_actions, menu);
        miActionProgressItem = menu.findItem(R.id.mi_ActionProgress);
        // Extract the action-view from the menu item
        ProgressBar v = (ProgressBar) MenuItemCompat.getActionView(miActionProgressItem);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setupViewPager(ViewPager viewPager) {
        Adapter adapter = new Adapter(getSupportFragmentManager());
        adapter.addFragment(new StocksCompleteListFragment(), "Category 1");
        adapter.addFragment(new CheeseListFragment(), "Category 2");
        adapter.addFragment(new CheeseListFragment(), "All Stocks");
        viewPager.setAdapter(adapter);
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        mDrawerLayout.closeDrawers();
                        switch (menuItem.getItemId()) {
                            case R.id.menuItem0:
                                Intent mainIntent = new Intent(getApplicationContext(), MainActivity.class);
                                startActivity(mainIntent);
                                finish();
                                break;
                            case R.id.menuItem1:
                                Intent stocksIntent = new Intent(getApplicationContext(), StocksActivity.class);
                                startActivity(stocksIntent);
                                finish();
                                break;
                        }
                        return true;
                    }
                });
    }

    @Override
    public void onBackPressed() {
        Intent mainIntent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(mainIntent);
        finish();
    }

    static class Adapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

        public Adapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }
}

我已经花了8个小时试图解决这个问题,这是我第一次在这个论坛上发帖,所以如果我发错了,请原谅。我已经搜索和尝试了一些解决方案,我认为是相关的。

编辑:以下是片段StocksCompleteListFragment.java的类

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

public class StocksCompleteListFragment extends Fragment {

    ArrayList<String> list;
    RecyclerView rv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rv = (RecyclerView) inflater.inflate(
                R.layout.fragment_stocks_completelist, container, false);
        setupRecyclerView(rv);
        return rv;
    }

    private void setupRecyclerView(RecyclerView recyclerView) {
        recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
        recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(),
                getSymbols(recyclerView)));

    }


    private ArrayList<String> getSymbols(RecyclerView recyclerView) {

        list = new ArrayList<>();
        StockData stockDataClass = new StockData(getActivity(), recyclerView);
        list = stockDataClass.getSymbolList();
        return list;
    }

    public static class SimpleStringRecyclerViewAdapter
            extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {

        private final TypedValue mTypedValue = new TypedValue();
        private int mBackground;
        private List<String> mValues;

        public static class ViewHolder extends RecyclerView.ViewHolder {
            public String mBoundString;

            public final View mView;
            public final ImageView mImageView;
            public final TextView mTextView;

            public ViewHolder(View view) {
                super(view);
                mView = view;
                mImageView = (ImageView) view.findViewById(R.id.avatar);
                mTextView = (TextView) view.findViewById(android.R.id.text1);
            }

            @Override
            public String toString() {
                return super.toString() + " '" + mTextView.getText();
            }
        }

        public void changeList (ArrayList<String> tempStringList) {
            mValues = tempStringList;
            notifyDataSetChanged();
        }

        public String getValueAt(int position) {
            return mValues.get(position);
        }

        public SimpleStringRecyclerViewAdapter(Context context, List<String> items) {
            context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
            mBackground = mTypedValue.resourceId;
            mValues = items;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.completestocks_listitem, parent, false);
            view.setBackgroundResource(mBackground);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            holder.mBoundString = mValues.get(position);
            holder.mTextView.setText(mValues.get(position));

            holder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Context context = v.getContext();
                    Intent intent = new Intent(context, CheeseDetailActivity.class);
                    intent.putExtra(CheeseDetailActivity.EXTRA_NAME, holder.mBoundString);

                    context.startActivity(intent);
                }
            });

            Glide.with(holder.mImageView.getContext())
                    .load(Cheeses.getRandomCheeseDrawable())
                    .fitCenter()
                    .into(holder.mImageView);
        }

        @Override
        public int getItemCount() {
            return mValues.size();
        }
    }
}

共有1个答案

孟修竹
2023-03-14

很难在注释中解释它可能是什么,所以我将在这个答案中帮助您调试。

因此,StockActivity加载这些片段,StocksCompleteListFragment执行AsyncTask(最后一个访问StockActivity的菜单项)。AsyncTask(StockData的内部类)应该接收对MenuItem的引用。

正如前面所说,我会尝试将访问MenuItem的两个方法移动到AsyncTask

private class Title extends AsyncTask<Void, Void, Void> {
    // ...

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showProgressBar();
    }

    @Override
    protected void onPostExecute(Void result) {
        ((StocksCompleteListFragment.SimpleStringRecyclerViewAdapter) recyclerV.getAdapter()).changeList(symbolList);
        hideProgressBar();
    }


    // I don't need them to be public if I move them here
    //
    private void showProgressBar() {
    // Show progress item
        item.setVisible(true);
    }

    private void hideProgressBar() {
        // Hide progress item
        item.setVisible(false);
    }
}

添加一个接收它的构造函数

public class StocksCompleteListFragment extends Fragment {
    private MenuItem item;

    // Default constructor
    public StocksCompleteListFragment() {}

    public StocksCompleteListFragment(MenuItem item) {
        this.item = item;
    }

    // ...  

然后将其传递给片段类

// StocksActivity.java

adapter.addFragment(new StocksCompleteListFragment(miActionProgressItem ), "Category 1");

稍后,将项从StocksCompleteListFragment传递到StockData类,以便内部AsyncTask可以访问它

public class StockData {
    private ArrayList<String> symbolList;
    Context myContext;
    RecyclerView recyclerV;
    private MenuItem item;

    public StockData(Context getcontext, RecyclerView recyclerView){
        myContext = getcontext;
        symbolList = new ArrayList<String>();
        recyclerV = recyclerView;
        new Title().execute();
    }

    public StockData(Context getcontext, RecyclerView recyclerView, MenuItem item) {
        this(getcontext, recyclerView);
        this.item = item;
    }
private ArrayList<String> getSymbols(RecyclerView recyclerView) {

    list = new ArrayList<>();
    StockData stockDataClass = new StockData(getActivity(), recyclerView, item);
    list = stockDataClass.getSymbolList();
    return list;
}

StockActivity(完全加载、操作栏和所有内容)->传递菜单项->StocksCompleteListFragment(调用AsyncTask)->传递菜单项->AsyncTask隐藏/显示菜单项。

这就是我的看法,肯定有更容易的选择,但我想不出更容易的。

试试这个,我宁愿这是一个评论而不是一个答案,但我不能写这么多。

 类似资料:
  • 因此,我必须创建一个方法,将输入字符串分成名字/中间名/姓氏,计算创建的“学生”的数量,等等,然后我必须创建测试这些方法的类。 这是我测试代码的方式: } 当它为具有2个名称的学生测试toString时,我一直遇到空指针异常,我不知道为什么。

  • 问题内容: 我在登录模式提交按钮的单击侦听器中遇到问题。 这是错误。 我对什么是空指针异常有一个合理的了解,并且已经彻底搜索了一个类似于我的问题。我试图以几种方式重新格式化点击侦听器,确保我具有正确的视图ID等。 显然,还有更多但与我认为无关的话题。这是带有按钮的对话框的XML文件。 任何帮助将不胜感激。 问题答案: 是因为它不属于 当你调用内部的,它要寻找一个你的活动的布局中。 试试这个代替:

  • 问题内容: 我想在Honeycomb ActionBar中添加一个不确定的进度条,以便用户每次按下“刷新”时,刷新图标都会临时变为不确定的进度条,直到任务完成。电子邮件应用程序已经做到了,但是我不知道如何做到。 有什么建议吗? 问题答案: 很难确切说明电子邮件应用程序是如何完成的,但是您可能想保持简单,只需用XML文件的ID 调用setIcon,然后使用Timer更改状态即可。

  • 问题内容: 有可能这可能是一个双重问题。我将String变量初始化为null。我可能会或可能不会使用一个值更新它。现在我想检查此变量是否不等于null以及我尝试执行的操作是否会得到null指针异常。空指针异常,因为它代价高昂。是否有任何有效的解决方法.TIA 问题答案: 如果您使用 你 不会 得到。 我怀疑你在做什么: 这是因为null 而引发,而不是因为null。 如果仍然无法解释,请发布您用于

  • 我已经更新了我的项目中的一些依赖关系之后,我的Hibernate配置类显示Nullpointerx的。 我将SpringDataJPA存储库与hibernate一起使用,已经超过24小时了,仍然没有找到任何关于小问题的适当解决方案。 我已经尝试过的一些解决方案:- 使用@bean(name=“entityManagerFactory”)提供bean名称 我面临的问题 波姆。xml文件 配置类 db

  • 当我试图从DB查询结果时,我得到一个空指针异常。以下是错误: 这是错误产生的函数。 如果我启动应用程序信息服务(=new ApplicationInfoService()),我会得到一个指向我的服务类的空指针错误,在这里进行查询 错误转到createQuery行,如果我打印出EntityManager,它将返回“null”。为什么我的Entitymanager不能初始化。我在我的登录系统中使用了几