简体   繁体   中英

How can I rearrange the data from database in a ListView?

everyone. I have an ArrayList of the data and a ListView to showing up the list of the data. Now what I want to do is rearrange the data when I press the button and sort the data in which data has the highest result.

Here is my code:

public class MainActivity extends AppCompatActivity {

private TextView mTextMessage;

String[] dataDetail;
ArrayList<dataDetail> allDetail = new ArrayList<>();

ListView detailList;
final Context context = this;

final int min = 0;
final int max = 10;
final int random = new Random().nextInt((max - min) + 1) + min;

Button reorder = findViewById(R.id.arrangeId);

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_home:
                mTextMessage.setText(R.string.title_home);
                return true;
            case R.id.navigation_dashboard:
                mTextMessage.setText(R.string.title_dashboard);
                return true;
        }
        return false;
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    detailList = findViewById(R.id.dataView);

    mTextMessage = (TextView) findViewById(R.id.message);
    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

    new GetData().execute();

}

private class GetData extends AsyncTask<Void, Void, ArrayList<dataDetail>> {

    protected ArrayList<dataDetail> doInBackground(Void... voids) {

        HttpURLConnection urlConnection;
        InputStream in = null;
        try {
            URL url = new URL("http://10.0.2.2:8080/projectServer/DataDetailDB?getdata=true");
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String response = convertStreamToString(in);
        System.out.println("Server response = " + response);

        try {
            JSONArray jsonArray = new JSONArray(response);
            dataDetail = new String[jsonArray.length()];

            for (int i = 0; i < jsonArray.length(); i++) {

               final String customerName = jsonArray.getJSONObject(i).get("customerName").toString();
               final String carName = jsonArray.getJSONObject(i).get("carName").toString();
               final String appointmentDate = jsonArray.getJSONObject(i).get("appointmentDate").toString();
               final String email = jsonArray.getJSONObject(i).get("email").toString();
               final String issueDescribe = jsonArray.getJSONObject(i).get("issueDescribe").toString();
               final String timeForJob = jsonArray.getJSONObject(i).get("timeForJob").toString();
               final String costForJob = jsonArray.getJSONObject(i).get("costForJob").toString();
               final String reliableOnCar = jsonArray.getJSONObject(i).get("reliableOnCar").toString();
               final String distanceJob = jsonArray.getJSONObject(i).get("distance").toString();

                dataDetail tData = new dataDetail(customerName, carName, appointmentDate, email, issueDescribe, timeForJob, costForJob, reliableOnCar, distanceJob);
                allDetail.add(tData);

                System.out.println("customername = " + customerName + "carname = " + carName + "appointmentdate = " + appointmentDate +
                    "email = " + email + "describe = " + issueDescribe + "time = " + timeForJob + "cost = " + costForJob + "reliable = " + reliableOnCar
                + "dis = " + distanceJob);

                dataDetail [i] = "Name: " + customerName + "\n" + "Appointment Date: " + appointmentDate;


                reorder.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {


                        float finalResult = random * Float.parseFloat(timeForJob) + random * Float.parseFloat(reliableOnCar) +
                                random * Float.parseFloat(distanceJob) + random * Float.parseFloat(costForJob);

                        System.out.print("Test result " + finalResult + " ");

                        /* Trying to sort the data here which has the highest finalResult
                        *  will going to the top of the list */

                        allDetail = new ArrayList<String>(Arrays.asList(dataDetail));
                        Collections.sort(allDetail);

                        ArrayAdapter newList = new ArrayAdapter(context, android.R.layout.simple_list_item_1, dataDetail);
                        newList.setAdapter(theList);

                    }
                });


            }

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

        return null;
    }

    protected void onPostExecute(ArrayList<dataDetail> dataDetailArrayList) {
        super.onPostExecute(dataDetailArrayList);

        ArrayAdapter theList = new ArrayAdapter(context, android.R.layout.simple_list_item_1, dataDetail);
        detailList.setAdapter(theList);
    }
}

public String convertStreamToString(InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

}

But when I try to use sort I get the error says it's incompatible types.

allDetail = new ArrayList<String>(Arrays.asList(dataDetail));
Collections.sort(allDetail);

The finalResult will do the calculation and get the final result for every data it retrieves from the database. And now I just want to reorder it automatically, This is the logcat:

logcat 显示数据成功检索并进行计算

Please anyone can help how can I do the rearrange for the listview?

Collections.sort() will work. Its your problem related to how your are storing your data in list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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