将数据从活动传递到片段,第一次不加载

时间:2018-09-03 12:52:25

标签: android fragment

我正在尝试将数据从活动传递到片段。我有四个标签。数据已传递但第一次未显示,当我滑动其他三个选项卡并返回到第一个选项卡时,将显示数据。我在活动的onCreate方法中调用JSON数据解析方法。在这里,我提供我的代码。 这是Main@Activity.java

    package com.example.iqbal.privateuniversityinfo;

import android.os.Bundle;
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.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

// https://api.myjson.com/bins/lb6b8

// new https://api.myjson.com/bins/1gzo6k
public class Main2Activity extends AppCompatActivity {
    String name, fac_and_sub, tution_fees, admission_info, contact;
    private String div;
    private int pos;

    private RequestQueue mqueue;
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    private Bundle bundle;

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

        div = getIntent().getStringExtra("div");
        pos = Integer.parseInt(getIntent().getStringExtra("pos"));

        bundle = new Bundle();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        jsonParse();
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main2, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    public static class PlaceholderFragment extends Fragment {

        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.university_details, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {


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

        @Override
        public Fragment getItem(int position) {

            switch (position) {

                case 0:
                    FacultyAndSubject facultyAndSubject = new FacultyAndSubject();
                    facultyAndSubject.setArguments(bundle);
                    return facultyAndSubject;
                case 1:
                    TutionFees tutionFees = new TutionFees();
                    return tutionFees;
                case 2:
                    Admission_info admission_info = new Admission_info();
                    return admission_info;
                case 3:
                    Contact contact = new Contact();
                    return contact;

                default:
                    return null;
            }


        }

        @Override
        public int getCount() {
            // Show 4 total pages.
            return 4;
        }
    }

    private void jsonParse() {
        String url = "https://api.myjson.com/bins/1gzo6k";
        mqueue = Volley.newRequestQueue(this);
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject jsonObject = response.getJSONObject(i);

                        switch (div) {
                            case "ctg":
                                if (i == pos) {
                                    name = jsonObject.getString("name");
                                    fac_and_sub = jsonObject.getString("faculty_and_sub");
                                    tution_fees = jsonObject.getString("tution_fees");
                                    admission_info = jsonObject.getString("admission_info");
                                    contact = jsonObject.getString("contact");

                                    bundle.putString("name", name);
                                    bundle.putString("fac", fac_and_sub);
                                    bundle.putString("fees", tution_fees);
                                    bundle.putString("info", admission_info);
                                    bundle.putString("contact", contact);
                                }
                                break;


                        }


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

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        mqueue.add(jsonArrayRequest);
    }
}

这是FacultyAndSubject类

   package com.example.iqbal.privateuniversityinfo;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.RequestQueue;

public class FacultyAndSubject extends Fragment {
    Context context;
    TextView tv;
    String name, fac, fees, info, contact;
    private Bundle bundle;
    private RequestQueue mqueue;
    String div;
    int pos;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.faculty_and_subject, container, false);
        tv = v.findViewById(R.id.tv);

        if (getArguments() != null) {
            name = getArguments().getString("name");
            fac = getArguments().getString("fac");
            fees = getArguments().getString("fees");
            info = getArguments().getString("info");
            contact = getArguments().getString("contact");
        }

        tv.setText(name + "\n" + " " + fac + "\n" + fees + "\n" + info + "\n" + contact);
        return v;
    }
}

2 个答案:

答案 0 :(得分:0)

尝试将代码添加到case 0的{​​{1}}内,与默认情况下一样。

也应@babich的建议,尝试在获得响应后设置适配器。

答案 1 :(得分:0)

获取数据后是否可能需要设置viewPager? 将完成的日志消息添加到您的onResponse末尾,并将其添加到onCreateView的{​​{1}}中

请先检查一下来电。 您知道如何添加日志消息以及如何使用FacultyAndSubject吗?

LogCat

第一个:

public class SectionsPagerAdapter extends FragmentPagerAdapter {
    FacultyAndSubject facultyAndSubject;
    TutionFees tutionFees;
    Admission_info admission_info;
    Contact contact;

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

    @Override
    public Fragment getItem(int position) {

        switch (position) {

            case 0:
                if(facultyAndSubject == null) {
                facultyAndSubject = new FacultyAndSubject();
                facultyAndSubject.setArguments(bundle);
                }
                return facultyAndSubject;
            case 1:
                if(tutionFees == null) tutionFees = new TutionFees();
                return tutionFees;
            case 2:
                if(admission_info == null) admission_info = new Admission_info();
                return admission_info;
            case 3:
                if(contact == null) contact = new Contact();
                return contact;

            default:
                return null;
        }


    }

    @Override
    public int getCount() {
        // Show 4 total pages.
        return 4;
    }
}

第二个:

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.faculty_and_subject, container, false);
        tv = v.findViewById(R.id.tv);

        if (getArguments() != null) {
            this.name = getArguments().getString("name");
            this.fac = getArguments().getString("fac");
            this.fees = getArguments().getString("fees");
            this.info = getArguments().getString("info");
            this.contact = getArguments().getString("contact");
            updateData();
        } else showLoading();

        tv.setText(name + "\n" + " " + fac + "\n" + fees + "\n" + info + "\n" + contact);

        return v;
    }

    public void updateData(String name, String fac, String fees, String info, String contact) {
    stopLoading();
    this.name = name;
    this.fac = fac;
    this.fees = fees;
    this.info = info;
    this.contact = contact;
    }