-2

I have a ListView that is populated with values from the mySQL database, and not all values are pulled, but those that match the specified condition: if (getHarakterByid (currCount) .equals ("Sale of monitors")). At the moment, in the listview element, one line together displays the position, code and address values, and only one address needs to be displayed. How can I do it? Tried SimpleAdapter, but nothing comes out.

MainActivity.java code:

public class MainActivity extends Activity {

    private Button start;
    private Intent districts;
    private Intent detail;

    private static RequestQueue mQueue;
    private static ConnectivityManager connectivityManager;
    private static ProgressDialog progressDialog;
    private static ArrayAdapter<HashMap<String, Object>> adapter;
    private static ArrayAdapter<HashMap<String, Object>> sAdapter;

    private ArrayList<HashMap<String, Object>> d_Task;
    private static final String it_address = "Address"; // Верхний текст
    private static final String it_id = "Position"; // ниже главного
    private static final String it_kz = "Kod";

    private static Context context;

    private static Handler handler;

    public static ListView LISTVIEW;
    public static final Map<String, String> fields = new HashMap<String, String>(1);

    private static final int delay_min = 30 * 1000 * 60;

    private Integer verCode;
    private String verName;

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

        LISTVIEW = (ListView) findViewById(R.id.LIST_VIEW);
        LISTVIEW.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        String[] from = {};
        adapter = new ArrayAdapter<HashMap<String, Object>>(this, R.layout.main_item,
                R.id.main_textitem);
        LISTVIEW.setAdapter(adapter);
        start = (Button) findViewById(R.id.start);
        context = getApplicationContext();
        mQueue = Volley.newRequestQueue(context);
        detail = new Intent(context, DetailActivity.class);
        districts = new Intent(context, DistrictsActivity.class);
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        try {
            verCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
            verName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (Exception e) {
        }

        fields.put("ROOT", context.getString(R.string.DATA));
        fields.put("data_unp_err",
                context.getString(R.string.data_unpack_error));
        fields.put("ver_remind", context.getString(R.string.ver_remind_text));

        DataStruct.getStruct().setPrefObj(getPreferences(MODE_PRIVATE));
        DataStruct.getStruct().getPrefObj()
                .setCurrVersionInfo(verName, verCode);

        DataStruct.getStruct().setRequestQueue(mQueue);
        DataStruct.getStruct().setMAdapter(adapter);
        DataStruct.getStruct().setAdapter((new DBadapter(context, verCode)));

        if (!DataStruct.getStruct().getPrefObj().checkVersionInfo()
                || !DataStruct.getStruct().getPrefObj().checkAccDataExists()) {
            Intent accountActivity = new Intent(context,
                    CreateAccountActivity.class);
            startActivity(accountActivity);
        }

        DataStruct.getStruct().getSavedRecords();
        startActionOnTimer();

        start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkNetWorkState()) {
                    progressDialog = new ProgressDialog(v.getContext());
                    progressDialog.setIndeterminate(true);
                    progressDialog.setCancelable(false);

                    handler = new Handler() {
                        @Override
                        public void handleMessage(Message message) {
                            switch (message.what) {
                                case WaitResponce.statusNumKeys.RESPONSE_FAILED:
                                    stopMFDialog(String.valueOf(message.obj));
                                    DataStruct.getStruct().getRequestObject()
                                            .cancelQueue();
                                    break;
                                case WaitResponce.statusNumKeys.RESPONSE_WAITING:
                                    progressDialog.setMessage("Подождите...");
                                    progressDialog.show();
                                    break;
                                case WaitResponce.statusNumKeys.RESPONSE_OK:
                                    stopMFDialog(String.valueOf(message.obj));
                                    break;
                                default:
                                    break;
                            }
                        }
                    };

                    if (DataStruct.getStruct().getListener()
                            .setHandler(handler)) {
                        DataStruct.getStruct().getReqParams()
                                .prepareParamForSelectReq();
                        DataStruct.getStruct().getListener().getEvent()
                                .onResponceStartWait();
                    }
                }
            }
        });


        LISTVIEW.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                HashMap<String, Object> itemHashMap = (HashMap<String, Object>) parent.getItemAtPosition(position);
                String titleItem = itemHashMap.get(it_id).toString();
                int a = Integer.parseInt(titleItem);
                detail.putExtra("arg", a);
                startActivity(detail);
            }
        });
    }


    private void showMessageDialog() {
        String Doz = "";
        for (int i = 0; i < DataStruct.getStruct().getMainListSize(); i++) {
            String Kod1 = DataStruct.getStruct().getKodByid(i);
            String Sut1 = DataStruct.getStruct().getSutByid(i);
            for (int j = 0; j < OldDataStruct.getStruct().getMainListSize(); j++) {
                String Kod2 = OldDataStruct.getStruct().getKodByid(j);
                String Sut2 = OldDataStruct.getStruct().getSutByid(j);
                if (Kod1.equals(Kod2)) {
                    if (Sut1.equals(Sut2)) {
                    } else {
                        Doz = Sut1.replaceFirst(Sut2, "");
                        String Address = DataStruct.getStruct().getAddressByid(i);
                        Address = Address.replace("city", "");
                        Address = Address.replace("street", "st.");
                        AlertDialog.Builder quitDialog = new AlertDialog.Builder(this);
                        quitDialog.setTitle(Address);
                        quitDialog.setMessage("Addition: " + Doz);
                        quitDialog.setNegativeButton("ОК",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                });
                        quitDialog.show();
                    }
                }
            }


        }
    }

    private void startActionOnTimer() {
        Intent l_intent = new Intent(this, UpdateOnTimer.class);
        PendingIntent l_pendingIntent = PendingIntent.getBroadcast(context, 0,
                l_intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis(), delay_min, l_pendingIntent);
    }

    public static void stopMFDialog(String message) {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        ShowMessage.Show(message);
    }

    public static void setViewAdapter(ArrayAdapter<HashMap<String, Object>> mAdapter) {
        adapter = mAdapter;
        LISTVIEW.setAdapter(adapter);
    }
}

DataStruct.java code:

public class DataStruct extends Application {

    /**
     * здесь собраны все функции для операции с массивом данных (заявок)
     */

    private static DataStruct mStruct;

    private RequestParams params;
    private Map<Integer, Map<String, String>> mainDataList;
    private DistrictDataAdapterStruct districtsList;
    private Integer currCount;
    private Integer currIndex;
    private Pref pref;
    private AddRequest request;
    private String districtName;
    private DBadapter dbAdapter;
    private ArrayAdapter<HashMap<String, Object>> mAdapter;
    private TasksFieldsNames fieldsNames;
    private WaitResponce waitResponce;

    private void setMainDataList(Map<Integer, Map<String, String>> list) {
        mainDataList = list;
    }

    private ArrayAdapter<HashMap<String, Object>> getMainAdapter() {
        return mAdapter;
    }

    public void setMAdapter(ArrayAdapter<HashMap<String, Object>> _mAdapter) {
        mAdapter = _mAdapter;
    }

    public int getMainListSize() {
        return mainDataList.size();
    }

    public Map<Integer, Map<String, String>> getMainDataList() {
        return mainDataList;
    }
    public void setAdapter(DBadapter dbAdapter) {
        this.dbAdapter = dbAdapter;
    }

    public void setCurrIndex(Integer i) {
        currIndex = i;
    }

    public final DBadapter getAdapter() {
        return dbAdapter;
    }

    public DistrictDataAdapterStruct getDistricstsList() {
        return districtsList;
    }

    public WaitResponce getListener() {
        return waitResponce;
    }

    @SuppressLint("UseSparseArrays")
    public void getSavedRecords() {
        Map<Integer, Map<String, String>> LIST = new HashMap<Integer, Map<String, String>>();
        LIST = getAdapter().getSelectedRows();
        if (LIST != null) {
            setRecFromBase(LIST);
        }
    }

    public Map<String, String> getRecById(Integer i) {
        return mainDataList.get(i);
    }

    public String getAddressByid(Integer i) {
        return mainDataList.get(i).get("Address").trim();
    }

    public String getSutByid(Integer i) {
        return mainDataList.get(i).get("The essence of the application").trim();
    }

    public String getKodByid(Integer i) {
        return mainDataList.get(i).get("Claim code").trim();
    }

    public String getHarakterByid(Integer i) {
        return mainDataList.get(i).get("Nature of the application").trim();
    }

    public void setRequestQueue(RequestQueue queue) {
        request = new AddRequest(queue);
    }

    public AddRequest getRequestObject() {
        return request;
    }

    public void setPrefObj(SharedPreferences preferences) {
        pref = new Pref(preferences);
    }

    public Pref getPrefObj() {
        return pref;
    }

    public RequestParams getReqParams() {
        return params;
    }

    public ArrayList<String> getAllRec() {
        ArrayList<String> values = new ArrayList<String>(0);
        Iterator<Map<String, String>> iterator = mainDataList.values().iterator();
        while (iterator.hasNext()) {
            values.addAll(iterator.next().values());
        }
        return values;
    }


    public void createDistrictsList() {
        districtsList = new DistrictDataAdapterStruct();
    }

    public void setDistricts(ArrayList<Map<String, String>> items) {
        final String idRaion = "kodDistrict";
        final String valRaion = "District";
        final String KolvoZayavok = "QuantityApplications";
        createDistrictsList();
        Iterator<Map<String, String>> iterator = items.iterator();
        while (iterator.hasNext()) {
            Map<String, String> item = iterator.next();
            getDistricstsList().addItem(String.valueOf(item.get(valRaion)),
                    Integer.parseInt(item.get(KolvoZayavok)),
                    Integer.parseInt(item.get(idRaion)));
        }
    }

    public void setRecFromBase(Map<Integer, Map<String, String>> LIST) {
        if (LIST.size() > 0) {
            setMainDataList(LIST);
            currCount = mainDataList.size();
            addItemsToMainAdapter();
        }
    }
    //добавление значений в ListView
    private void addItemsToMainAdapter() {
        ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>(currCount);
        for (int i = 0; i < currCount; i++) {
            HashMap<String, Object> hm = new HashMap<String, Object>();
            hm.put("Address",getAddressByid(i));
            hm.put("Kod",getKodByid(i));
            hm.put("Position",""+i);
            items.add(hm);
        }
        mAdapter.addAll(items);
        mAdapter.notifyDataSetChanged();
        MainActivity.setViewAdapter(getMainAdapter());
    }
    //обновление значений в ListView
    private void addItemToMainAdapter() {
        if (getHarakterByid(currCount).equals("Sale of monitors")) {
            HashMap<String, Object> hm = new HashMap<String, Object>();
            hm.put("Address",getAddressByid(currCount));
            hm.put("Kod",getKodByid(currCount));
            hm.put("Position",""+currCount);
            mAdapter.add(hm);
        }
        mAdapter.notifyDataSetChanged();
        MainActivity.setViewAdapter(getMainAdapter());
    }

    public void setMainNode() {
        currCount = mainDataList.size();
        mainDataList.put(currCount, new LinkedHashMap<String, String>());
    }

    private void setChildNode(String key, String value) {
        mainDataList.get(currCount).put(key, value.trim());
    }

    public void setREC(JSONObject unParseRec) {
        setMainNode();
        Iterator<Names> iterator = getFieldsNamesList().getNamesList();
        while (iterator.hasNext()) {
            Names item = iterator.next();
            String val = unParseRec.optString(item.getUSName());

            setChildNode(item.getRUSName(),
                    (val.isEmpty()) ? getFieldsNamesList().emptyValue : val);
        }
        addItemToMainAdapter();

    }

    public TasksFieldsNames getFieldsNamesList() {
        return fieldsNames;
    }

    private DataStruct() {
        currCount = 0;
        districtName = null;
        params = new RequestParams();
        fieldsNames = new TasksFieldsNames();
        waitResponce = new WaitResponce();
        mainDataList = new LinkedHashMap<Integer, Map<String, String>>(currCount);
    }

    public static synchronized DataStruct getStruct() {
        if (mStruct == null) {
            mStruct = new DataStruct();
        }
        return mStruct;
    }

    private void replaceItems() {
        if (currCount > 0) {
            Map<Integer, Map<String, String>> map = new LinkedHashMap<Integer, Map<String, String>>(0);
            Integer index = 0;
            Iterator<Map<String, String>> items = mainDataList.values().iterator();
            do {
                Map<String, String> item = items.next();
                map.put(index, item);
                index++;
            } while (items.hasNext());
            mainDataList.clear();
            setMainDataList(map);
        }
    }

    public void deleteRec() {
        getMainAdapter().remove(getMainAdapter().getItem(currIndex));
        getMainAdapter().notifyDataSetChanged();
        String task_code = getFieldsNamesList().getRUNameByTag(TasksFieldsNames.fields_name.task_code);
        getAdapter().deleteRows(getRecById(currIndex).get(task_code));
        mainDataList.remove(currIndex);
        currCount = mainDataList.size();
        replaceItems();
    }

    public void deleteAllRec() {
        getMainAdapter().clear();
        getMainAdapter().notifyDataSetChanged();
        getAdapter().reCreateBase();
        mainDataList.clear();
        currCount = mainDataList.size();
    }

    public String getDistrictName() {
        return districtName;
    }

    public void setDistrictName(String districtName) {
        this.districtName = districtName;
    }
}
  • 1
    You need to use custom BaseAdapter and put your logic in getView(); method. Make your Basics clear first. – Nilay Dani Mar 23 '18 at 06:19

1 Answers1

0

Ok first , I recommend using RecyclerView instead of ListView. As to why , see this link.

See Google's documentation on how to create a proper list.

You will need write a custom adapter and put your logic in onBindViewHolder

  @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // your logic goes here
        holder.mTextView.setText("some filtered data");

    }
user456
  • 262
  • 2
  • 9