1

Can I sort my listview for 2 conditions at once?I have 4 lines:title,description,url of image and pinned.I must show records where pinned==true at the top,then I must sort for alphabeticaly title line,at show after pinned==true lines.How can I do that?MainActivity and Adapter put below. MainActivity:

public class MainActivity extends ListActivity {
private Context context;
SqlHelper dbHelper;
    Intent intent;
    private static String url = "https://fierce-citadel-4259.herokuapp.com/hamsters";
    private static final String TITLE = "title";
    private static final String DESCRIPTION = "description";
    private static final String IMAGE = "image";
    private static final String PINNED = "pinned";

    ArrayList<HashMap<String,String>> jsonlist = new ArrayList<HashMap<String, String>>();
    ArrayList<HashMap<String,String>> bdList = new ArrayList<HashMap<String, String>>();
   ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actbar = getActionBar();
        actbar.setDisplayShowHomeEnabled(false);
        actbar.setDisplayShowTitleEnabled(false);
        actbar.setDisplayUseLogoEnabled(false);
        lv=(ListView) findViewById(android.R.id.list);
        LayoutInflater mInflater =LayoutInflater.from(MainActivity.this);
        View mcustomview = mInflater.inflate(R.layout.customactionbar, null);
        ImageButton imgbutt =(ImageButton)mcustomview.findViewById(R.id.actbarimagebutton);
        imgbutt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ProgressTask(MainActivity.this).execute();
            }

        });
        actbar.setCustomView(mcustomview);
        actbar.setDisplayShowCustomEnabled(true);
        if(isNetworkConnected()==true) {
            new ProgressTask(MainActivity.this).execute();
            ForItemClick();
        }
        else {
            try {
                dbHelper = new SqlHelper(MainActivity.this);
               WithoutInternetItemClick();
                imgbutt.setClickable(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            displaysavedlv();

        }



    }

    private class ProgressTask extends AsyncTask<String,Void,Boolean> {
        private ProgressDialog dialog;
        private ListActivity activity;
        private Context context;

        public ProgressTask(MainActivity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
            try {
                dbHelper = new SqlHelper(MainActivity.this);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        protected void onPreExecute(){
           this.dialog.setMessage("Progress start");
           this.dialog.show();
        }
        protected void onPostExecute(final Boolean success){
            try{
       if((this.dialog != null)&& this.dialog.isShowing()){
this.dialog.dismiss();
            }
if(isNetworkConnected()==true) {
    CustomListAdapter adapter = new CustomListAdapter(MainActivity.this, jsonlist, R.layout.list_item, new String[]{TITLE, DESCRIPTION}, new int[]{R.id.title, R.id.description});
    lv.setAdapter(adapter);
}else{
    displaysavedlv();
}


        }catch (final IllegalArgumentException e){e.printStackTrace();}
        }
        protected Boolean doInBackground(String... args) {

           JSONParser jParser = new JSONParser();
            JSONArray json = jParser.getJSONFromUrl(url);
            for(int i =0;i<json.length();i++) {
                try {
                    JSONObject c = json.getJSONObject(i);
                    String vtitle = c.getString(TITLE);
                    String vdescription = c.getString(DESCRIPTION);
                    String vimage = c.getString(IMAGE);
                    Boolean vpinned = c.getBoolean(PINNED);
                    dbHelper.open();
dbHelper.createEntry(vtitle, vimage, vdescription);

                    dbHelper.close();
                    HashMap<String, String> map = new HashMap<>();
                    map.put(TITLE, vtitle);
                    map.put(DESCRIPTION, vdescription);
map.put(IMAGE, vimage);
                    map.put(PINNED, String.valueOf(vpinned));
                    jsonlist.add(map);

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

            return null;
        }
    }

    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            // There are no active networks.
            return false;
        } else
            return true;
    }
    public void ForItemClick(){

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String title1 = jsonlist.get(position).get("title");
                String description1 = jsonlist.get(position).get("description");
                String url1 = jsonlist.get(position).get("image");

                intent = new Intent(MainActivity.this, DetailInfo.class);


                intent.putExtra("title", title1);
                intent.putExtra("description", description1);
                intent.putExtra("url", url1);
                startActivity(intent);


    }
});
    };
    private void displaysavedlv(){
        bdList = dbHelper.getAllData();
lv=(ListView) findViewById(android.R.id.list);
        CustomListAdapter adapter1 = new CustomListAdapter(MainActivity.this,bdList,R.id.list_item,new String[]{TITLE,DESCRIPTION},new int[]{R.id.title,R.id.description});
        lv.setAdapter(adapter1);


    }
    public void WithoutInternetItemClick(){
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String title1 = bdList.get(position).get("title");
                String description1 = bdList.get(position).get("description");
                String url1 = bdList.get(position).get("image");
                intent = new Intent(MainActivity.this, DetailInfo.class);


                intent.putExtra("title", title1);
                intent.putExtra("description", description1);
                intent.putExtra("url", url1);
                startActivity(intent);
            }
        });


    }
}

Adapter:

public class CustomListAdapter extends SimpleAdapter {
    private static final String IMAGE = null;
private final Activity context;
private ArrayList<HashMap<String, String>> result;
    public CustomListAdapter(Activity context, ArrayList<HashMap<String, String>> data, int resource, String[] from, int[] to) {
        super(context,data,resource,from,to);
        // TODO Auto-generated constructor stub

this.result = data;
        this.context = context;
    }

    public View getView(int position,View view,ViewGroup parent) {
        LayoutInflater inflater=context.getLayoutInflater();
        View rowView=inflater.inflate(R.layout.list_item, null, true);


        ImageView imageView = (ImageView) rowView.findViewById(R.id.image);
TextView title = (TextView) rowView.findViewById(R.id.title);
        title.setText(result.get(position).get("title"));
TextView description = (TextView) rowView.findViewById(R.id.description);
        description.setText(result.get(position).get("description"));
String url = result.get(position).get("image");
          Picasso.with(context)
                .load(url).into(imageView);


        return rowView;

    }


}
  • Set up a `Comparator` that implements your business rules, then `sort()` your model collection using that `Comparator`. – CommonsWare Sep 26 '15 at 11:27

2 Answers2

0

extend Comparable to your object over ride equals and compareto

@Override
public boolean equals(Object2 obj) {
    if (obj == null)
        return false;
    if (!(obj instanceof Messages))
        return false;
    Object1 u = (Object1) obj;

    return this.gettitle() == u.gettitle()
}

@Override
public int compareTo(Object2 obj) {
    return String.valueOf(this.title).compareTo(obj.title);
}
Ravi Gadipudi
  • 1,446
  • 1
  • 17
  • 30
0

If i follow your question than you can do something like this.

You can even define the Comparators in the bean itself so that you can reuse them instead of recreating them everytime:

public class Contact {

    private String name;
    private String phone;
    private Address address;

    // ...

    public static Comparator<Contact> COMPARE_BY_PHONE = new Comparator<Contact>() {
        public int compare(Contact one, Contact other) {
            return one.phone.compareTo(other.phone);
        }
    };

    public static Comparator<Contact> COMPARE_BY_ADDRESS = new Comparator<Contact>() {
        public int compare(Contact one, Contact other) {
            return one.address.compareTo(other.address);
        }
    };

}

which can be used as follows:

List<Contact> contacts = new ArrayList<Contact>();
// Fill it.

// Sort by address.
Collections.sort(contacts, Contact.COMPARE_BY_ADDRESS);

// Sort later by phone.
Collections.sort(contacts, Contact.COMPARE_BY_PHONE);

more details you can see here.

Community
  • 1
  • 1
SRB Bans
  • 3,096
  • 1
  • 10
  • 21