使用ViewPager从Activity更改片段TextView - java

我有一个Activity,单击按钮后即可从Web API检索数据,并将其保存在自定义Stats对象中。在我看来,我有一个带有ViewPager的TabLayout。问题是,在Activity检索完所有数据后,我无法从Fragment更改TextViews,但我始终会收到NullPointerException。

我已经尝试了很多东西,但是似乎都没有用,我也不知道该怎么办。

这是我的活动:


public class StatsActivity extends AppCompatActivity {

    public TextView textStats, responseView;
    public EditText usuario;
    public ProgressBar progressBar;
    public ImageButton buscar;
    public TabLayout tabLayout;
    public TabItem tabSolo, tabDuo, tabSquad;
    public ViewPager viewPager;

    String idUsuario, user;
    Stats soloStats = new Stats();
    Stats duoStats = new Stats();
    Stats squadStats = new Stats();
    Typeface TF;
    PageAdapter pageAdapter;


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

        textStats = findViewById(R.id.textStats);
        progressBar = findViewById(R.id.progressBar);
        responseView = findViewById(R.id.responseView);
        usuario = findViewById(R.id.editText);
        buscar = findViewById(R.id.searchButton);
        tabLayout = findViewById(R.id.tabs);
        tabSolo = findViewById(R.id.tabsolo);
        tabDuo = findViewById(R.id.tabduo);
        tabSquad = findViewById(R.id.tabsquad);
        viewPager = findViewById(R.id.pager);

        TF = Typeface.createFromAsset(getAssets(), "font/BurbankBigCondensed-Bold.ttf");

        pageAdapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(pageAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        viewPager.setVisibility(View.INVISIBLE);
        setCustomFont();

        LinearLayout tabStrip = ((LinearLayout) tabLayout.getChildAt(0));
        for(int i = 0; i < tabStrip.getChildCount(); i++) {
            tabStrip.getChildAt(i).setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return true;
                }
            });
        }

        tabLayout.setVisibility(View.INVISIBLE);

        responseView.setText("");
        responseView.setMovementMethod(new ScrollingMovementMethod());

        textStats.setTypeface(TF);
        responseView.setTypeface(TF);

        buscar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                user = usuario.getText().toString().trim();
                new getPlayerId().execute();
            }
        });

    }

    class getPlayerId extends AsyncTask<Void, Void, String> {

        private Exception exception;

        protected void onPreExecute() {
            progressBar.setVisibility(View.VISIBLE);
            responseView.setText("");
        }

        protected String doInBackground(Void... urls) {

            user = user.trim();

            try {
                // getting data

                    return stringBuilder.toString();
                }
                finally{
                    urlConnection.disconnect();
                }
            }
            catch(Exception e) {
                Log.e("ERROR", e.getMessage(), e);
                return null;
            }
        }

        protected void onPostExecute(String response) {
            if(response == null) {
                response = "THERE WAS AN ERROR";
            }
            Log.i("INFO", response);

            try {
                JSONObject object = (JSONObject) new JSONTokener(response).nextValue();

                //Parsing JSON and setting soloStats

            } catch (JSONException e) {
                e.printStackTrace();
            }

            //HERE IS WHERE I WANT TO CHANGE MY FRAGMENT TEXTVIEW

            //SoloFragment solo = (SoloFragment) pageAdapter.getItem(0);
            //solo.getStats(soloStats);
        }
    }
}

我的片段代码:


public class SoloFragment extends Fragment {

    TextView textVictorias, textTop2, textTop3, textPartidas, textKills, textPuntos, textMinutos, textJugadores;

    public SoloFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View v = inflater.inflate(R.layout.fragment_solo, container, false);

        textVictorias = v.findViewById(R.id.textVictorias);
        textTop2 = v.findViewById(R.id.textTop2);
        textTop3 = v.findViewById(R.id.textTop3);
        textPartidas = v.findViewById(R.id.textPartidas);
        textKills = v.findViewById(R.id.textKills);
        textPuntos = v.findViewById(R.id.textPuntos);
        textMinutos = v.findViewById(R.id.textMinutos);
        textJugadores = v.findViewById(R.id.textJugadores);

        return v;
    }

    public void setStats(Stats stats){

        textVictorias.setText(stats.getTop1());
        textTop2.setText(stats.getTop2());
        textTop3.setText(stats.getTop3());
        textPartidas.setText(stats.getPartidas());
        textKills.setText(stats.getKills());
        textPuntos.setText(stats.getPuntos());
        textMinutos.setText(stats.getMinutos());
        textJugadores.setText(stats.getJugadores());

    }

}


我总是在setStats内的setText上获得NPE,但我不知道如何解决该问题,希望有人能帮助我!谢谢!

参考方案

在onPostExecute方法中使用它

      //HERE IS WHERE I WANT TO CHANGE MY FRAGMENT TEXTVIEW        
      if (pageAdapter.getFragment() != null) {
          pageAdapter.getFragment().getStats(soloStats);
      }

JAVA:字节码和二进制有什么区别? - java

java字节代码(已编译的语言,也称为目标代码)与机器代码(当前计算机的本机代码)之间有什么区别?我读过一些书,他们将字节码称为二进制指令,但我不知道为什么。 参考方案 字节码是独立于平台的,在Windows中运行的编译器编译的字节码仍将在linux / unix / mac中运行。机器代码是特定于平台的,如果在Windows x86中编译,则它将仅在Win…

java:继承 - java

有哪些替代继承的方法? java大神给出的解决方案 有效的Java:偏重于继承而不是继承。 (这实际上也来自“四人帮”)。他提出的理由是,如果扩展类未明确设计为继承,则继承会引起很多不正常的副作用。例如,对super.someMethod()的任何调用都可以引导您通过未知代码的意外路径。取而代之的是,持有对本来应该扩展的类的引用,然后委托给它。这是与Eric…

Java:BigInteger,如何通过OutputStream编写它 - java

我想将BigInteger写入文件。做这个的最好方式是什么。当然,我想从输入流中读取(使用程序,而不是人工)。我必须使用ObjectOutputStream还是有更好的方法?目的是使用尽可能少的字节。谢谢马丁 参考方案 Java序列化(ObjectOutputStream / ObjectInputStream)是将对象序列化为八位字节序列的一种通用方法。但…

Java DefaultSslContextFactory密钥库动态更新 - java

我有一个使用org.restlet.engine.ssl.DefaultSslContextFactory的现有应用程序和一个在服务器启动时加载的密钥库文件。我有另一个应用程序,该应用程序创建必须添加的证书服务器运行时动态地更新到密钥库文件。为此,我在代码中创建了证书和私钥,然后将其写入到目录。该目录由bash脚本监视,该脚本检查是否有新文件,如果出现,它将…

Java-如何将此字符串转换为日期? - java

我从服务器收到此消息,我不明白T和Z的含义,2012-08-24T09:59:59Z将此字符串转换为Date对象的正确SimpleDateFormat模式是什么? java大神给出的解决方案 这是ISO 8601标准。您可以使用SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM…