在Andriod

时间:2016-09-18 13:06:35

标签: java android json android-fragments arraylist

我正在创建一个具有Main活动的应用,而Main活动有两个片段:

  1. MapFragment (在每个有餐厅的地方都有别针)
  2. RestaurantsFragment (包含餐馆列表)
  3. 到目前为止,我可以在用户打开应用程序并单击选项卡后从服务器更新列表myRestaurantsFragment。 我想要做的是以下 - 我想在用户启动应用程序时从服务器更新两个片段。 我不想要的是将餐馆保存到我的本地sqlite数据库。我想在我的Main活动中获取列表并将它们传递给两个选项卡,将餐馆列表传递给myRestaurantFragment,我想 将此列表中的相同信息传递给我的MapsFragment 。我想把我的列表代码放到主要活动中并将其传递给主要活动中的三个片段,但我是初学者并通过简单的例子来处理这个应用程序,所以我有点迷失。

    MainActivity:

    public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    
    private SessionManager session;
    private SQLiteHandler db;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        returnMyRestaurants();
    
        // SqLite database handler
        db = new SQLiteHandler(getApplicationContext());
        // session manager
        session = new SessionManager(getApplicationContext());
    
        if (!session.isLoggedIn()) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        } else {
    
            TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
            tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_map)));
            tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_my_restaurants)));
    
            tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
            tabLayout.setTabMode(TabLayout.MODE_FIXED);
    
            final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
            final PagerAdapter adapter = new PagerAdapter
                    (getSupportFragmentManager(), tabLayout.getTabCount());
            viewPager.setAdapter(adapter);
            viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    
            MyRestaurantsFragment mapsFragment = new MyRestaurantsFragment();
            Bundle args = new Bundle();
            args.putParcelable("restaurantList", (Parcelable) restaurantList);
            mapsFragment.setArguments(args);
    
            tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    viewPager.setCurrentItem(tab.getPosition());
                }
    
                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
    
                }
    
                @Override
                public void onTabReselected(TabLayout.Tab tab) {
    
                }
            });
    ...
    public void returnMyRestuaurants() {
        SQLiteHandler db = new SQLiteHandler(getApplicationContext());
        HashMap<String, String> user = db.getUserDetails();
        final String userId = user.get("uid");
    
         StringRequest restuaurantReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_GET_RESTUAURANT, new Response.Listener<String>() {
    
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
    
                    if (!error) {
                        JSONArray restuaurants = jObj.getJSONArray("restuaurant");
    
                        // Parsing json
                        for (int i = 0; i < restuaurants.length(); i++) {
                            try {
    
                                JSONObject obj = restuaurants.getJSONObject(i);
                                RestuaurantParcelableModel restuaurant = new RestuaurantParcelableModel();
                                restuaurant.setUserName(obj.getString("name"));
                                if (obj.getString("image") != null && !obj.getString("image").isEmpty()) {
                                    restuaurant.setThumbnailUrl(obj.getString("image"));
                                }
                                restuaurant.setLat(obj.getString("latitude"));
                                restuaurant.setLon(obj.getString("longitude"));
                                restuaurant.setDate(obj.getString("event_date"));
                                restuaurant.setTime(obj.getString("event_time"));
    
                                // adding restuaurant to restuaurant array
                                restuaurantList.add(restuaurant);
    
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
    
                        // notifying list adapter about data changes so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    } else {
                        // Error. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                }
    
            }
        }, new Response.ErrorListener() {
    ...
    

    MapFragment:

    public class MapsFragment extends Fragment {
    
    private GoogleMap mMap;
    MapView mapView;
    Marker marker; // Marker
    private static final int MY_LOCATION_REQUEST_CODE = 1; 
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // inflate and return the layout
        View v = inflater.inflate(R.layout.fragment_maps, container,
                false);
        mapView = (MapView) v.findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);
    
        mapView.onResume();// needed to get the map to display immediately
    
        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        mMap = mapView.getMap();
        mMap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
    
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
            // Show rationale and request permission.
        }
    
        String provider = locationManager.getBestProvider(criteria, true);
        Location myLocation = locationManager.getLastKnownLocation(provider);
    
        double latitude = 51.4825766;
        double longitude = -0.0076589;
    
        if (myLocation != null) {
            latitude = myLocation.getLatitude();
            longitude = myLocation.getLongitude();
        }
    
        MarkerOptions markerOptions = new MarkerOptions().position(
                new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_me));
    
        mMap.addMarker(markerOptions);
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(latitude, longitude)).zoom(12).build();
        mMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));
    
        mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
    
            @Override
            public void onMapLongClick(final LatLng arg0) {
    
                RequestQueue queue = Volley.newRequestQueue(getActivity());
                String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + String.valueOf(arg0.latitude) + "," + String.valueOf(arg0.longitude) + "&key=myKey";
    
                // Request a string response from the provided URL.
                StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                try {
                                    JSONArray jObj = new JSONObject(response).getJSONArray("results").getJSONObject(0).getJSONArray("address_components");
    
                                    Intent intent = new Intent(getActivity(), SetRestaurantActivity.class);
    
                                    for (int i = 0; i < jObj.length(); i++) {
                                        String componentName = new JSONObject(jObj.getString(i)).getJSONArray("types").getString(0);
                                        if (componentName.equals("postal_code") || componentName.equals("locality") || componentName.equals("street_number") || componentName.equals("route")
                                                || componentName.equals("neighborhood") || componentName.equals("sublocality") || componentName.equals("administrative_area_level_2")
                                                || componentName.equals("administrative_area_level_1") || componentName.equals("country")) {
                                            intent.putExtra(componentName, new JSONObject(jObj.getString(i)).getString("short_name"));
                                        }
                                    }
    
                                    intent.putExtra("latitude", arg0.latitude);
                                    intent.putExtra("longitude", arg0.longitude);
    
                                    startActivity(intent);
    
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        int x = 1;
                    }
                });
                queue.add(stringRequest);
    
            }
        });
    
        return v;
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == MY_LOCATION_REQUEST_CODE) {
            if (permissions.length == 1 &&
                    permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mMap.setMyLocationEnabled(true);
            } else {
                // Permission was denied. Display an error message.
            }
        }
    }
    

    RestaurantsFragment:

    public class RestaurantsFragment extends Fragment {
    
    private static final String TAG = RestaurantsFragment.class.getSimpleName();
    
    // Restaurants json url
    private ProgressDialog pDialog;
    private List<Restaurant> restaurantList = new ArrayList<>();
    private ListView listView;
    private CustomListAdapter adapter;
    
    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_restaurants, container, false);
    
        listView = (ListView) view.findViewById(R.id.restaurants_list);
        adapter = new CustomListAdapter(getActivity(), restaurantList);
        listView.setAdapter(adapter);
    
        pDialog = new ProgressDialog(getActivity());
    
        pDialog.setMessage("Loading...");
        pDialog.show();
    
        Bundle bundle = this.getArguments();
        if (bundle != null) {
            restaurantList = bundle.getParcelable("restaurantList");
        }
        return view;
    }
    

    我已经制作了可模仿的模型:

    import android.os.Parcel;
    import android.os.Parcelable;
    
    public class RestaurantParcelableModel implements Parcelable {
    private String userName, thumbnailUrl, lat, lon, restname, description;
    ...
    

1 个答案:

答案 0 :(得分:2)

当您调用服务器并以列表形式获取响应时,请将其保存在活动中的arrayList中。让我们称之为 ArrayList<RestaurantParcelableModel> restaurantList = new ArrayList<>();
现在,无论何时切换片段,都要使用Bundle将此列表传递给新的片段。

Bundle args = new Bundle();
args.putParcelableArrayList("myList",restaurantList);   
MapFragment newFragment = new MapFragment ();
newFragment.setArguments(args);


在此之后进行片段交易。