【问题标题】:How to parse JSON data into fragments?如何将 JSON 数据解析成片段?
【发布时间】:2017-07-01 05:59:41
【问题描述】:

你好朋友我正在开发带有片段的 Android 应用程序在 viewpager 但现在我想将 JSON 数据解析到片段中。我的问题是如何将片段数设置为 json 数据的大小并将 json 数据插入到所需的fragment.please 请帮助我,我已经在互联网上搜索了几个小时,但结果令人失望,所以请帮助我。提前致谢!

[{"c_id":13,"category_name":"PUBLICATIONS","imagename":"http://goringr.com/church_project/churchimagesnew/publications.jpg","ctype":"church"},{"c_id":14,"category_name":"YOUTH ASSOCIATION","imagename":"http://goringr.com/church_project/churchimagesnew/youthassociation.jpg","ctype":"church"}]

这是我的 json 数据,我只想在第一个片段中显示 c_id=13 的对象的内容,并在第二个片段中显示 c_id=14 的对象的内容。

MainActivity.java

package project1.test;

import android.content.Intent;
import android.support.design.widget.CollapsingToolbarLayout;
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.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
public static final String data = "hello";
FragmentPagerAdapter adapterViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

   //        Toolbar tool = (Toolbar)findViewById(R.id.tool);
   //        setSupportActionBar(tool);
    //        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
    adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
    vpPager.setAdapter(adapterViewPager);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.sample_actions, menu);
    return true;
}

public static class MyPagerAdapter extends FragmentPagerAdapter {
    private static int NUM_ITEMS = 3;

    public MyPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    // Returns total number of pages
    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    // Returns the fragment to display for that page
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return FirstFragment.newInstance(0, "Fragment1");
            case 1:
                return FirstFragment.newInstance(1, "Fragment2");
            case 2:
                return SecondFragment.newInstance(2, "Fragment3");
            default:
                return null;
        }
    }

    // Returns the page title for the top indicator
    @Override
    public CharSequence getPageTitle(int position) {
        return "Page " + position;
    }

}

} 

第一个片段

public class FirstFragment extends Fragment {
// Store instance variables
private String title;
private int page;

// newInstance constructor for creating fragment with arguments
public static FirstFragment newInstance(int page, String title) {
    FirstFragment fragmentFirst = new FirstFragment();
    Bundle args = new Bundle();
    args.putInt("someInt", page);
    args.putString("someTitle", title);
    fragmentFirst.setArguments(args);
    return fragmentFirst;
}

// Store instance variables based on arguments passed
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setHasOptionsMenu(true);
    page = getArguments().getInt("someInt", 0);
    title = getArguments().getString("someTitle");
}

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

;
    View view = inflater.inflate(R.layout.fragment_first, container, false);
 //        TextView tvLabel = (TextView) view.findViewById(R.id.tvLabel);
 ////        tvLabel.setText(page + " -- " + title);


    CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)view.findViewById(R.id.collapsing_toolbar1);
    collapsingToolbarLayout.setTitle("black panther");

    return view;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // TODO Add your menu entries here
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.sample_actions, menu);
}
}

SecondFragment

public class SecondFragment extends Fragment {
// Store instance variables
private String title;
private int page;
Button tryit;

// newInstance constructor for creating fragment with arguments
public static SecondFragment newInstance(int page, String title) {
    SecondFragment fragmentSecond = new SecondFragment();
    Bundle args = new Bundle();
    args.putInt("someInt", page);
    args.putString("someTitle", title);
    fragmentSecond.setArguments(args);
    return fragmentSecond;
}

// Store instance variables based on arguments passed
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    page = getArguments().getInt("someInt", 0);
    title = getArguments().getString("someTitle");
}

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

    View view = inflater.inflate(R.layout.fragment_second, container, 
   false);
    tryit = (Button) view.findViewById(R.id.tryit);
    tryit.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(),ManagingProfile.class);
            startActivity(intent);
        }
    });
//        TextView tvLabel = (TextView) view.findViewById(R.id.tvLabel);
//        tvLabel.setText(page + " -- " + title);
    return view;
}
}

【问题讨论】:

  • 它是片段的事实有何不同?
  • 请原谅我是初学者,我只有一个月的经验......我知道如何将 json 数据解析到自定义列表视图中,但是当涉及到片段时,我有点困惑。

标签: android json android-fragments android-viewpager


【解决方案1】:

你可以这样解析:

List<RidesData> ridesDatas;  /* this is should be parcelable */
private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); 
    adapter.addFragment(FragmentAbout.newInstance(ridesDatas), "ABOUT");
    adapter.addFragment(FragmentPointOfInterest.newInstance(ridesDatas),"POI");

    viewPager.setAdapter(adapter);
        }

并像这样为每个片段设置结构:

FragmentAbout.class

public static FragmentAbout newInstance(List<RidesData> ridesDatas) {
        FragmentAbout fragmentAbout = new FragmentAbout();
        Bundle arg = new Bundle();
        arg.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) ridesDatas);
        fragmentAbout.setArguments(arg);
        return fragmentAbout;
    }

FragmentPointOfInterest.class

public static FragmentPointOfInterest newInstance(List<RidesData> ridesDatas) {
        FragmentPointOfInterest fragmentPointOfInterest = new FragmentPointOfInterest();
        Bundle arg = new Bundle();
        arg.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) ridesDatas);
        fragmentPointOfInterest.setArguments(arg);
        return fragmentPointOfInterest;
    }

并在片段的onViewCreated()方法中获取json的每个数据,如下所示:

您在 json 中有 2 个数据位置。

[0] = c_id=13
[1] = c_id=14

所以在第一个片段集 0 位置:

RidesData data = ridesData.get(0);

在第二个 Fragment 中设置 1 个位置:

RidesData 数据 =ridesData.get(1);

@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ridesData = new ArrayList<>();
        ridesData = getArguments().getParcelableArrayList("data"); 
        RidesData data = ridesData.get(1);    
    }

【讨论】:

  • 感谢兄弟的回复,但这些片段是静态的,抱歉在我的问题中没有提到我需要动态片段。考虑用户添加一个 JSON 对象的场景(其中 c_id 可能为 15 或任何其他)在JSON数组中,我想在自动创建的片段中显示它而不使用addfragment()方法静态创建片段。假设JSON数组中有5个JSON对象,我想要的是自动创建5个片段在每个片段中显示每个 JSON 对象的内容。希望我的解释清楚。任何帮助将不胜感激。
  • 我已经在上面提到了.. 我的示例 ridesData 包含 json 数据。在我的 RideData 对象位置 0 = 第一个 json 对象数据。位置 1 = 第二个对象数据..不管你添加了多少个 json 对象..你可以通过位置获得。
  • 而且您不必为每个对象创建多个片段。您可以在一个片段中获取 json 对象的每个位置。每次它只会显示json对象数据的特定位置。
  • 但是您使用 **adapter.addFragment()** 方法创建了片段,例如adapter.addFragment(FragmentPointOfInterest.newInstance(ridesDatas),"POI");,但我希望根据 JSON 数组中 JSON 对象的数量自动创建片段...跨度>
  • 尝试理解本教程:: androidhive.info/2016/04/…
【解决方案2】:

您必须使用自定义适配器来提取 json 数据并使用视图持有者来打印数据。 参考这个link

【讨论】:

  • 这与片段问题无关。
猜你喜欢
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 2020-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多