2016-09-18 7 views
0

のスタートに1つのアクティビティから複数のフラグメントを更新する私は、メイン活性を有するアプリを作っていて、主な活動は、2つの断片がありますのAndriod

  1. MapFragmentは(ここで、すべての場所のピンが含まれていますレストラン)がある
  2. RestaurantsFragment(レストランのリストが含まれています)

これまでユーザーがアプリを開いてタブをクリックすると、myRestaurantsFragmentをサーバーから更新することができました。 私がしたいことは次のとおりです - ユーザーがアプリケーションを起動したときにサーバーから両方のフラグメントを更新したいと思います。私がしたくないのは、ローカルのsqliteデータベースにレストランを保存することです。私はメインのアクティビティでリストを取得して両方のタブに渡し、レストランのリストをmyRestaurantFragmentに渡したいと思います。はこのリストから同じ情報を私のMapsFragmentに渡します。私は主な活動に私のリストコードを入れて、主な活動から3つの断片に渡すことを考えましたが、私は初心者であり、簡単な例を経てこのアプリケーションに取り組んでいるので、少し失われています。

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:

import android.os.Parcel; 
import android.os.Parcelable; 

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

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

私はすでにparcelableモデルを作りました

+1

Obsarvableデザインパターンは、トリックを行うだろう。 –

答えて

2

サーバーを呼び出してリストの形式で応答を取得するときは、アクティビティのarrayListにレスポンスを保存します。それを呼び出すことができます
ArrayList<RestaurantParcelableModel> restaurantList = new ArrayList<>();
フラグメントを切り替えるときはいつでも、このリストをBundleを使って新しいフラグメントに渡します。

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


この後、フラグメント取引を行います。

+0

だからあなたは答えを得た? –

+0

私はまだいくつかのエラーがある、私は週末前にそれをチェックアウトすることはできませんと私はあなたに知らせてください – Kemo

+0

確かに、あなたが欲しいときはいつでも、ここでコメントの質問を撃つ。 :) –

関連する問題