Я хочу отсортировать список на основе счетчика, но я не могу это сделать, пожалуйста, любой орган поможет мне в этом.Сортировка в виде списка с использованием BaseAdapter
Здесь я делюсь своим кодом и снимком экрана.
Это адаптер, который связан с ListView
Custom_adapter_group.java
public class CustomAdapter_groups extends BaseAdapter {
String phone = "";
Button bttn_request;
ArrayList<DiscoverModel> discoverModel;
SharedPreference_Main sharedPreference;
String[] result;
String[] details;
private Context context;
private int[] prgmImages;
private LayoutInflater inflater = null;
public Database4 db4;
private ArrayList<DiscoverModel> listupdate;
protected int position;
public CustomAdapter_groups(Context context,
ArrayList<DiscoverModel> discoverModel) {
// TODO Auto-generated constructor stub
this.context = context;
this.discoverModel = discoverModel;
this.listupdate = listupdate;
this.inflater = (LayoutInflater) ((context))
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
db4 = new Database4(context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return discoverModel.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return discoverModel.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tv;
ImageView img;
TextView tv_pushcounter;
private Holder() {
}
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
sharedPreference = new SharedPreference_Main(context);
final Holder holder;
if (convertView == null) {
holder = new Holder();
convertView = this.inflater.inflate(
R.layout.fragment_others_list_view_elements, null);
holder.tv = (TextView) convertView.findViewById(R.id.tv_foodibdhe);
holder.img = (ImageView) convertView.findViewById(R.id.iv_foodie);
holder.tv_pushcounter = (TextView) convertView
.findViewById(R.id.tv_pushcounter);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
if (discoverModel.get(position) != null) {
holder.tv.setText(discoverModel.get(position).getGroupname());
// //Condition for counter
if (db4.getCounter(discoverModel.get(position).getGroupchatid()) == "0") {
holder.tv_pushcounter.setVisibility(View.GONE);
} else if (db4.getCounter(discoverModel.get(position)
.getGroupchatid()) == "101") {
holder.tv_pushcounter.setText("100+");
}
holder.tv_pushcounter.setText(db4.getCounter(discoverModel.get(
position).getGroupchatid()));
Picasso.with(context)
.load(discoverModel.get(position).getGroupimage())
.resize(200, 200).centerCrop()
.transform(new CircleTransform())
.into(holder.img, new Callback() {
@Override
public void onError() {
holder.img
.setBackgroundResource(R.drawable.group_friend_list_icon);
}
@Override
public void onSuccess() {
}
});
}
String update1 = sharedPreference.getlistupdate1();
// if (!update1.equalsIgnoreCase("")) {
// discoverModel.add(0, discoverModel.get(position));
// discoverModel.
// notifyDataSetChanged();
// }
notifyDataSetChanged();
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context,
Private_group_chat_activity.class);
sharedPreference = new SharedPreference_Main(context);
sharedPreference.is_slient(""
+ discoverModel.get(position).getIs_slient());
i.putExtra("public_group", "1");
i.putExtra("isMember", ""
+ discoverModel.get(position).getIsMember());
i.putExtra("groupidentify", ""
+ discoverModel.get(position).getGroup_identify());
i.putExtra("public_priavte_Identify",
"" + discoverModel.get(position).getPublic_private());
i.putExtra("groupchatid", ""
+ discoverModel.get(position).getGroupchatid());
i.putExtra("groupname", ""
+ discoverModel.get(position).getGroupname());
i.putExtra("groupId", ""
+ discoverModel.get(position).getGroupid());
i.putExtra("isAdmin", ""
+ discoverModel.get(position).getIsAdmin());
context.startActivity(i);
// discoverModel.add(0, discoverModel.get(position));
// notifyDataSetChanged();
}
});
return convertView;
Collections.sort(discoverModel, myComparator);
}
public Comparator<Database4> myComparator = new Comparator<Database4>() {
public int compare(Database4 obj1, Database4 obj2) {
return obj1
.getCounter(discoverModel.get(position).getGroupchatid())
.compareTo(
obj2.getCounter(discoverModel.get(position)
.getGroupchatid()));
}
};
}
Вот код, в котором используется элемент управления ListView
Fragment_groups.java
public class Fragment_groups extends Fragment implements ApiConstants,UpdateListener
{
private static int FLAG = 0;
private ListView lv_list_view;
private RelativeLayout rl_foodie;
private EditText et_type_groups;
private Database2 db2;
private Database4 db4;
private String newResponse;
private String counter;
private Button bttn_create_private_group;
private ArrayList<DiscoverModel> discoverModel;
private ArrayList<DiscoverModel> listupdate;
private CustomAdapter_groups CustomAdapter_groups;
SharedPreference_Main sharedPreference;
public ArrayList<DiscoverModel> discoverModelSearch;
public ArrayList<DiscoverModel> discoverModelStore;
Activity activity;
// Fragment_groups context;
public static int\[\] prgmImages = { R.drawable.group_chat_icon,
R.drawable.group_chat_icon, R.drawable.group_chat_icon };
public static String\[\] prgmNameList = { "Foodie", "Football" };
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
sharedPreference = new SharedPreference_Main(getActivity());
View v = inflater.inflate(R.layout.fragment_others, container, false);
// Inflate the layout for this fragment
// this.setUpdatedCounter();
activity = this.getActivity();
lv_list_view = (ListView) v.findViewById(R.id.lv_list_view);
et_type_groups = (EditText) v.findViewById(R.id.et_type_groups);
discoverModel = new ArrayList<DiscoverModel>();
listupdate = new ArrayList<DiscoverModel>();
discoverModelSearch = new ArrayList<DiscoverModel>();
discoverModelStore = new ArrayList<DiscoverModel>();
db2 = new Database2(getActivity());
db4 = new Database4(getActivity());
bttn_create_private_group = (Button) v
.findViewById(R.id.bttn_create_private_group);
bttn_create_private_group.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity(), Private_group.class);
startActivity(intent);
}
});
et_type_groups.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
searchText(s.toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
get_groups_api();
isOnline();
return v;
}
private void isOnline() {
// TODO Auto-generated method stub
ConnectivityManager conMgr = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
Toast.makeText(getActivity(), "No Internet connection!",
Toast.LENGTH_LONG).show();
newResponse = db2.getResponse(getActivity(), newResponse, 3);
jsonparsing(newResponse);
}
return;
}
public void get_groups_api() {
FLAG = 0;
// TODO Auto-generated method stub
final ProgressDialog pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
StringRequest sr = new StringRequest(Request.Method.POST,
"http://unichatapi.approutes.com:80/groups",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pDialog.hide();
discoverModel.clear();
// parsing method passing the response
Log.e("groups response", "" + response);
jsonparsing(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pDialog.hide();
VolleyLog.e("TAG", "Error: " + error.getMessage());
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("deviceId", sharedPreference.getRegisteration_id());
params.put("sessionId", "" + sharedPreference.getSession());
params.put("option", "getGroups");
params.put("userId", "" + sharedPreference.getUserId());
params.put("unixTime", "" + 0);
return params;
}
};
AppController.getInstance().addToRequestQueue(sr);
}
protected void jsonparsing(String response) {
// TODO Auto-generated method stub
db2.update(response, 2, "1");
try {
JSONObject jsonO = new JSONObject(response);
Log.e("message", "" + jsonO.getString("message"));
Log.e("serverTime", "" + jsonO.getString("serverTime"));
sharedPreference.server_time(jsonO.getString("serverTime"));
// code for public group
JSONArray publicgroupsA = jsonO.getJSONArray("publicGroups");
for (int i = 0; i < publicgroupsA.length(); i++) {
DiscoverModel cm = new DiscoverModel();
JSONObject public_groupO = publicgroupsA.getJSONObject(i);
// if(sharedPreference.getlistupdate1().equalsIgnoreCase(public_groupO.getString("groupChatId")))
// {
// listupdate.add(cm);
// }
DiscoverModel dm = new DiscoverModel();
dm.setGroup_identify("1");
dm.setPublic_private("0");
dm.setIs_slient(public_groupO.getString("is_silent"));
dm.setGroupid(public_groupO.getString("groupId"));
Log.e("groupId", "" + public_groupO.getString("groupId"));
dm.setGroupname(public_groupO.getString("groupName"));
Log.e("groupName", "" + public_groupO.getString("groupName"));
dm.setGroupimage("http://unichatapi.approutes.com/vchatfiles/"
+ public_groupO.getString("groupImage"));
dm.setGroupchatid(public_groupO.getString("groupChatId"));
// counter = db4.getCounter(dm.getGroupchatid());
Log.e("value from counter",""+counter);
// dm.setPushcounter(counter);
dm.setGroup_modified_on(public_groupO.getString("modifiedOn"));
dm.setGroup_created_on(public_groupO.getString("createdOn"));
discoverModel.add(dm);
db4.insertIncidentDetails(getActivity(), dm);
}
// code for private group
JSONArray fullDataA = jsonO.getJSONArray("fullData");
for (int j = 0; j < fullDataA.length(); j++) {
DiscoverModel fm = new DiscoverModel();
JSONObject jsongroup = fullDataA.getJSONObject(j);
fm.setGroup_identify("2");
fm.setPublic_private("1");
fm.setGroupid(jsongroup.getString("groupId"));
fm.setIsMember(jsongroup.getString("isMember"));
fm.setIsAdmin(jsongroup.getString("isAdmin"));
fm.setGroupname(jsongroup.getString("groupName"));
fm.setGroupimage("http://unichatapi.approutes.com/vchatfiles/"
+ jsongroup.getString("groupImage"));
fm.setGroupchatid(jsongroup.getString("groupChatId"));
fm.setGroup_modified_on(jsongroup.getString("modifiedOn"));
fm.setGroup_created_on(jsongroup.getString("createdOn"));
Log.e("groupid", "" + jsongroup.getString("groupId"));
Log.e("groupName", "" + jsongroup.getString("groupName"));
Log.e("groupImage", "" + jsongroup.getString("groupImage"));
Log.e("groupChatId", "" + jsongroup.getString("groupChatId"));
Log.e("modifiedOn", "" + jsongroup.getString("modifiedOn"));
Log.e("createdOn", "" + jsongroup.getString("createdOn"));
discoverModel.add(fm);
db4.insertIncidentDetails(getActivity(), fm);
// CustomAdapter_groups.notifyDataSetChanged();
}
CustomAdapter_groups = new CustomAdapter_groups(getActivity(),
discoverModel);
lv_list_view.setAdapter(CustomAdapter_groups);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "" + e, Toast.LENGTH_SHORT).show();
}
}
public LayoutInflater getSystemService(String layoutInflaterService) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadcastReceiver, new IntentFilter("com.example.vchat"));
}
@Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);
}
public void searchText(String chartext) {
// TODO Auto-generated method stub
chartext = chartext.toLowerCase(Locale.getDefault());
if (FLAG == 0) {
discoverModelStore.clear();
discoverModelStore.addAll(discoverModel);
FLAG = 1;
}
discoverModelSearch.clear();
discoverModelSearch.addAll(discoverModelStore);
discoverModel.clear();
if (chartext.length() == 0) {
// discoverModel.clear();
discoverModel.addAll(discoverModelStore);
CustomAdapter_groups.notifyDataSetChanged();
} else if (chartext.length() >= 0) {
// discoverModel.clear();
for (DiscoverModel dm : discoverModelSearch) {
if (dm.getGroupname().toLowerCase(Locale.getDefault())
.contains(chartext)) {
discoverModel.add(dm);
}
}
}
CustomAdapter_groups.notifyDataSetChanged();
}
@Override
public void setUpdatedCounter() {
// TODO Auto-generated method stub
}
BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
CustomAdapter_groups.notifyDataSetChanged();
}
};
}
список сортировкивот снимок экрана экрана
Фактически вы сортируете после оператора возврата. сначала сортировать, а затем передавать данные в адаптер, почему каждый раз, когда вы хотите сортировать данные? – androidnoobdev
@androidnoobdev Я не могу установить, потому что я устанавливаю счетчик непосредственно из базы данных в адаптере, и когда когда-либо нажимают уведомление, приходят значения изменения conter и в соответствии с этим видом списка также получают сортировку –
См., Что адаптер не будет получать событие напрямую, я имею в виду, когда push что вы собираетесь обновлять данные адаптера, так что я говорю, когда вы получаете данные из push или db, сортируете данные списка, а затем передаете их вашему адаптеру и вызываете метод notifydatasetchange. После утверждения возврата ваш код не будет запускаться, поэтому я думаю, что компилятор даже покажет вам ошибку. – androidnoobdev