通过传递JSON在Android中生成/创建动态标签

时间:2017-12-07 14:54:53

标签: android json dynamic tabs

我正在尝试通过Volley从加载的JSON文件中动态创建标签(以及稍后在每个标签的片段中添加另一个动态创建的内容),但没有成功。

public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

String myData = "";

public static String test;

//Fragment List
private final List<Fragment> mFragmentList = new ArrayList<>();
//Title List
private final List<String> mFragmentTitleList = new ArrayList<>();
private ViewPagerAdapter adapter;

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

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    loaddata();
    //create multiple titles, but use OneFragment() for every new tab
    for(int i = 0; i < mFragmentTitleList.size(); i++) {
        mFragmentList.add(new OneFragment());
    }
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    // Tab ViewPager setting
    viewPager.setOffscreenPageLimit(mFragmentList.size());
    tabLayout.setupWithViewPager(viewPager);
}

//Loading the JSON data, which will be used to create dynamically content such as tabs and info for the Fragments
private void loaddata() {
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "https://ipfs.io/ipfs/QmQ69ScwoqSsFAdGV4oUKNaDMzSDuY9zcdRoFYkHPUZM7E";
    String line = "";

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            myData = response;
            //Log.d("response", myData);

            JSONObject object = null;
            try {
                object = new JSONObject(myData);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JSONObject menuitems = null;
            try {
                menuitems = object.getJSONObject("menuitems");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for(int i = 0; i<menuitems.length(); i++) {
                try {
                    mFragmentTitleList.add(menuitems.names().getString(i));
                    //mFragmentTitleList gives output [Alcohol Drinks, Soups, Salads]
                    Log.d("test", String.valueOf(mFragmentTitleList));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //Log.d(TAG, "Key = " + menuitems.names().getString(i) + " value = " + menuitems.get(menuitems.names().getString(i)));
            }
            /*try {
                Log.d("testagain", "\"" +categories.getString(2)+ "\"");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            */

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast.makeText(context, "That didn't work!", duration);
        }
    });
    queue.add(stringRequest);
}

private void setupViewPager(ViewPager viewPager) {
    adapter = new ViewPagerAdapter(getSupportFragmentManager(), mFragmentList, mFragmentTitleList);
    viewPager.setAdapter(adapter);
}


//ViewPagerAdapter settings
class ViewPagerAdapter extends FragmentPagerAdapter {
    private List<Fragment> mFragmentList = new ArrayList<>();
    private List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titleLists) {
        super(fm);
        this.mFragmentList = fragments;
        this.mFragmentTitleList = titleLists;
    }

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

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

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

}

}

最后我应该有3个标签,名为酒精饮料,汤,沙拉

目前应用程序刚启动时没有生成任何标签。谢谢你的帮助! :)

1 个答案:

答案 0 :(得分:1)

您必须在loaddata之后创建标签 - &gt; onResponse填写“mFragmentList”列表。

编辑粘贴此代码

public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

String myData = "";

public static String test;

//Fragment List
private final List<Fragment> mFragmentList = new ArrayList<>();
//Title List
private final List<String> mFragmentTitleList = new ArrayList<>();
private ViewPagerAdapter adapter;

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

toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

viewPager = (ViewPager) findViewById(R.id.viewpager);
loaddata();

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

//Loading the JSON data, which will be used to create dynamically content 
such as tabs and info for the Fragments
private void loaddata() {
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = 
    "https://ipfs.io/ipfs/QmQ69ScwoqSsFAdGV4oUKNaDMzSDuY9zcdRoFYkHPUZM7E";
    String line = "";

StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        myData = response;
        //Log.d("response", myData);

        JSONObject object = null;
        try {
            object = new JSONObject(myData);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JSONObject menuitems = null;
        try {
            menuitems = object.getJSONObject("menuitems");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        for(int i = 0; i<menuitems.length(); i++) {
            try {
                mFragmentTitleList.add(menuitems.names().getString(i));
                //mFragmentTitleList gives output [Alcohol Drinks, Soups, Salads]
                Log.d("test", String.valueOf(mFragmentTitleList));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Log.d(TAG, "Key = " + menuitems.names().getString(i) + " value = " + menuitems.get(menuitems.names().getString(i)));
        }
        //create multiple titles, but use OneFragment() for every new tab
        for(int i = 0; i < mFragmentTitleList.size(); i++) {
            mFragmentList.add(new OneFragment());
        }
        setupViewPager(viewPager);
        tabLayout.setupWithViewPager(viewPager);
        // Tab ViewPager setting
        viewPager.setOffscreenPageLimit(mFragmentList.size());
        tabLayout.setupWithViewPager(viewPager);
        /*try {
            Log.d("testagain", "\"" +categories.getString(2)+ "\"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        */

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        Toast.makeText(context, "That didn't work!", duration);
    }
});
queue.add(stringRequest);
}

private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager(), mFragmentList, mFragmentTitleList);
viewPager.setAdapter(adapter);
}


//ViewPagerAdapter settings
class ViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragmentList = new ArrayList<>();
private List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titleLists) {
    super(fm);
    this.mFragmentList = fragments;
    this.mFragmentTitleList = titleLists;
}

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

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

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

}
}