如何将JSON数据解析为片段?

时间:2017-07-01 05:59:42

标签: android json android-fragments android-viewpager

你好朋友我在浏览器中用片段开发android应用程序,但现在我想将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;
    }

}

} 

FirstFragment

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;
}
}

2 个答案:

答案 0 :(得分:0)

你可以像这样解析:

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);
        }

并将constructure设置为每个片段,如下所示:

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);

并在第二个片段中设置1个位置:

RidesData data = 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);    
    }

答案 1 :(得分:-1)

您必须使用自定义适配器来提取json数据并查看持有者以打印数据。 请参阅此link