繁体   English   中英

在Android中启动时从一个活动更新多个片段

[英]Updating multiple fragments from one activity on start in Android

我正在制作一个具有Main活动的应用程序,并且Main活动有两个片段:

  1. MapFragment (在有餐厅的每个位置包含大头针)
  2. RestaurantsFragment (包含餐厅列表)

到目前为止,一旦用户打开应用程序并单击选项卡,我就可以从服务器更新列表myRestaurantsFragment。 我要做的是以下操作- 当用户启动应用程序时,我想从服务器更新两个片段。 我不希望将餐馆保存到我的本地sqlite数据库中。 我想在我的主要活动中获取列表,并将它们传递到两个选项卡,将餐馆列表传递到myRestaurantFragment,并且我想将相同的信息从该列表传递到MapsFragment 我曾考虑将清单代码放到主要活动中,然后将其传递给主要活动中的三个片段,但是我是一个初学者,通过简单的示例来开发此应用程序,所以我有点迷失了。

主要活动:

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

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

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


在此之后进行分段交易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM