2016-03-28 57 views
0

我使用viewpager與2個滑動標籤佈局。在第一個tablayout中,我將數據發佈到服務器,當我切換選項卡時Listview未更新。只有當我點擊Listview項目並關閉它時,Listview纔會刷新,並且發佈的數據是可見的... 問題是:如何在數據發佈到服務器時自動刷新Listview,有人可以幫助。刷新其他片段的列表視圖

public class PagerAdapter extends FragmentStatePagerAdapter { 
int numOfTabs; 
public PagerAdapter(FragmentManager fm,int numOfTabs) { 
    super(fm); 
    this.numOfTabs=numOfTabs; 
} 

@Override 
public Fragment getItem(int position) { 
    switch (position){ 
     case 0: 
      RaiseComplaintFragment RFragment=new RaiseComplaintFragment(); 
      return RFragment; 
     case 1: 
      ComplaintListFragment CFragment=new ComplaintListFragment(); 
      return CFragment; 
     default: 
      return null; 
    } 
} 

@Override 
public int getCount() { 
    return numOfTabs; 
} 

}

這是數據發佈到服務器

public void postDataToServer(String complaintdata) throws JSONException { 
    String url = URLMap.getPostComplaintUrl(); 

    String roleId = LoggedInUserStore.getLoggedInRoleId(getContext()); 
    String branchId = LoggedInUserStore.getLoggedInBranchId(getContext()); 
    String compid = LoggedInUserStore.getLoggedInCompanyId(getContext()); 

    HashMap<String, String> params = new HashMap<>(); 
    params.put("CallRecordID", "0"); //pass 0 if we are inserting a new record always 
    params.put("CompanyID", compid); 
    params.put("BranchID", branchId); 
    params.put("ServiceID", sId); 
    params.put("CallLocationID", lId); 
    params.put("RaisedByID", roleId); 
    params.put("ComplaintDetails", complaintdata); 
    params.put("CallStatusID", "1"); 
    pDialog = new ProgressDialog(getContext()); 
    pDialog.setMessage("Please wait.."); 
    pDialog.setProgressStyle(pDialog.STYLE_SPINNER); 
    pDialog.setIndeterminate(false); 
    pDialog.setCancelable(false); 
    pDialog.show(); 
    JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject(params), new Response.Listener<JSONObject>() { 
     @Override 
     public void onResponse(JSONObject response) { 

      AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); 
      builder.setTitle("Complaint has been registered successfully"); 
      builder.setMessage("").setCancelable(true); 
      AlertDialog alertDialog = builder.create(); 
      alertDialog.show(); 
      _complaintText.setText(""); 
      serviceSpinner.setSelection(0); 
      locationSpinner.setSelection(0); 
      pDialog.dismiss(); 
      /*((HomeActivity)getActivity()).getViewPager().setCurrentItem(1); //onCLick of Submit it just switches the tab 
      String tagName="android:switcher:"+R.id.pager+":"+1; 
      ComplaintListFragment f2=(ComplaintListFragment)getActivity().getSupportFragmentManager().findFragmentByTag(tagName); 
      f2.fetchComplaintData();*/ 
     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); 
      builder.setTitle("Unable to register your request.\nPlease try later."); 
      builder.setCancelable(true); 
      AlertDialog alertDialog = builder.create(); 
      alertDialog.show(); 
      pDialog.dismiss(); 
     } 
    }); 
    req.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy()); 
    RequestQueue requestQueue = ((VolleyRequestQueue) getActivity().getApplication()).getRequestQueue(); 
    requestQueue.add(req); 
} 

我HomeActivity類處理兩個標籤佈局

方法
viewPager = (ViewPager) findViewById(R.id.view_Pager); 
    tabLayout = (TabLayout) findViewById(R.id.tab_Layout); 


    String roleID = LoggedInUserStore.getLoggedInRoleId(getApplicationContext()); 
    if (roleID.equals("4")) { 

     //RAISE COMPLAINT UI. IF ROLE ID == 4 MANAGER DASHBOARD 

     tabLayout.addTab(tabLayout.newTab().setText("Raise Complaint")); 
     tabLayout.addTab(tabLayout.newTab().setText("Complaint List")); 
     tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); 

     final PagerAdapter adapter = 
       new com.six30labs.cms.adapters.PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount()); 
     viewPager.setAdapter(adapter); 

     viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); 
     tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { 
      @Override 
      public void onTabSelected(TabLayout.Tab tab) { 
       viewPager.setCurrentItem(tab.getPosition()); 
      } 

      @Override 
      public void onTabUnselected(TabLayout.Tab tab) { 
       viewPager.setCurrentItem(tab.getPosition()); 
      } 

      @Override 
      public void onTabReselected(TabLayout.Tab tab) { 

      } 
     }); 

其中包含我的ListView二片段

public class ComplaintListFragment extends Fragment { 
private ListView complaintListView; 
EditText _inputSearch; 
ComplaintAdapter compadapter; 
private static Parcelable mListViewScrollPos = null; 
private RequestQueue mQueue; 
ProgressBar progressBar; 
String URL; 
private View v; 
String TAG="Second Fragment"; 


@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // Inflate the layout for this fragment 
    v = inflater.inflate(R.layout.fragment_complaint_list, container, false); 
    complaintListView = (ListView) v.findViewById(R.id.complaintListView); 
    _inputSearch = (EditText) v.findViewById(R.id.inputSearchforComplaintListFragment); 
    progressBar = (ProgressBar) v.findViewById(R.id.complaintListProgressBar); 

    fetchComplaintData(); 

    _inputSearch.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
     } 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 
      try { 
       compadapter.getFilter().filter(s.toString()); 
       compadapter.notifyDataSetChanged(); 
      }catch (NullPointerException e){ 
       e.printStackTrace(); 
      } 
     } 

     @Override 
     public void afterTextChanged(Editable s) { 
     } 
    }); 

    if (mListViewScrollPos != null) { 
     complaintListView.onRestoreInstanceState(mListViewScrollPos); 
    } 

    return v; 
} 

public void fetchComplaintData() { 

    progressBar.setVisibility(View.VISIBLE); 
    URL = URLMap.getComplaintUrl("complaint_url"); 
    URL = URL.replace("{id}", LoggedInUserStore.getLoggedInCompanyId(getContext())); 


    StringRequest request = new StringRequest(Request.Method.GET,URL, new Response.Listener<String>() { 
     @Override 
     public void onResponse(String response) { 
      getCompliantList(response); 
      progressBar.setVisibility(View.GONE); 

     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); 

     } 
    }); 
    request.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy()); 
    RequestQueue queue=((VolleyRequestQueue)getActivity().getApplication()).getRequestQueue(); 
    queue.add(request); 
    /* RequestQueue requestQueue 
    = Volley.newRequestQueue(getContext()); 
    requestQueue.add(request);*/ 
} 

public void getCompliantList(String response) { 

    try { 
     List complaint = new ArrayList<>(); 
     JSONArray jArray = new JSONArray(response); 
     for (int i = 0; i < jArray.length(); i++) { 

// complaint.add(Complaint.fromJson(jArray.getJSONObject(i)));

  complaint.add(0,Complaint.fromJson(jArray.getJSONObject(i))); //To push the data to the top of the listview. 
     } 
     compadapter = new ComplaintAdapter(getContext(), complaint); 
     complaintListView.setAdapter(compadapter); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
} 

//Method that will save the position the user when they scroll 
//return it when the user comes back to the listView instead of it refreshing the data. 
public void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    mListViewScrollPos = complaintListView.onSaveInstanceState(); 
} 

public void onPause() { 
    super.onPause(); 

} 

public void onResume() { 
    super.onResume(); 
    fetchComplaintData(); 
} 
+0

使該方法公共靜態或使用接口。也使用廣播接收器。 – Piyush

+0

使用界面進行刷新。 –

回答

3

BroadcastReceiver對於類你在哪裏列表視圖是

private BroadcastReceiver updateProfileBroadcast = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     //Fire your event 
    } 
}; 

註冊廣播onResume()

registerReceiver(updateProfileBroadcast, new IntentFilter("KEY")); 

現在火廣播神父agment

Intent intent = new Intent("KEY"); 
    getActivity().sendBroadcast(intent); 
+0

我的Listview是在另一個片段Sir ... ComplaintListFragment我有更新代碼... – Rakesh

+0

是的它會工作。做一件事。在另一個片段中創建並註冊具有listview和Fire廣播的片段Broasdcast。在onReceive裏面刷新listview。 –

+0

是的,你應該使用BroadcastReceivers。 –

0

作爲替代SID的答案,你可以使用EventBus。它通過事件驅動架構工作,並且能夠在組件之間輕鬆快速地傳輸信息。

這是你如何使用它:

1)中添加的gradle應用項目:compile 'org.greenrobot:eventbus:3.0.0'

2)註冊於片段的onCreate()EventBus,你需要更新ListVieweventBus.register(this);。而且不要忘記註銷它onDestryView()eventBus.unregister(this);

3)的方法添加到您的ListView片段將與列表更新處理事件:

@SupressWarning("unused") 
@Subscribe 
public void onEvent(List<YourListViewData> event) {/* update `ListView` */}; 

4)火從活動\片段時事件你需要更新ListView

EventBus bus = EventBus.getInstance(); 
eventBus.post(List<YourListViewData> yourData); 
+0

謝謝先生,請嘗試讓你知道... – Rakesh