删除重复的listView项目

时间:2014-07-29 11:05:59

标签: java android android-listview duplicate-removal

我的代码存在问题。 在我的活动中,它打印一个具有空值的重复listView!我怎样才能改变这种行为呢?

在java文件中,连接有效,但我不明白为什么它会显示重复。

public class OlivetoEventi extends Activity {

    // JSON Node names
    private static final String TAG_EVENTI = "eventi";
    private static final String TAG_TITOLO = "titolo";
    private static final String TAG_DESC = "descrizione";
    private static final String TAG_LUOGO = "luogo";
    private static final String TAG_DATA = "data";
    // private static final String TAG_LINK = "link";

    // message intent
    public final static String EXTRA_MESSAGE = "com.aljacket.appcomuneoc.MESSAGE";

    // products JSONArray
    JSONArray products = null;

    String[] titolo = new String[100];
    String[] data = new String[100];
    String[] luogo = new String[100];
    String[] descrizione = new String[200];
    String[] newDate = new String[100];
    int lunghezza;
    InputStream is = null;
    String result = null;
    StringBuilder sb = null;
    JSONArray jArray;

    TextView event;
    ImageButton ImBu[] = new ImageButton[100];

    ImageButton back,home;

    ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();

    ListView list;
    ArrayAdapter<String> listAdapter;
    getEventi mTask;
    ConnectivityManager cm;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview_eventi);
        list = (ListView) findViewById(R.id.eventiListView);
        if(isOnline()){
            mTask = new getEventi();
            mTask.execute();
        }
        else{
            Toast.makeText(getApplicationContext(), "Hai bisogno di una connessione dati o di una rete WI-FI " +
                    "per poter leggere le ultime News",
                       Toast.LENGTH_LONG).show();   
        }

        back = (ImageButton) findViewById(R.id.imageRetry);
        back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                retry(v);
            }
        });

        atHomeButton();

        new getEventi().execute();
    }

    class getEventi extends AsyncTask<Void, Void, Void> {
        private ProgressDialog pDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(OlivetoEventi.this);
            pDialog.setMessage("Caricamento ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
      }

        /**
         * Getting product details in background thread
         * */
        protected Void doInBackground(Void... params) {

            connect();
            return null;
        }

        protected void onPostExecute(Void result) {
            pDialog.dismiss();
            for (int i = 0; i < lunghezza; i++) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
                Date testDate = null;
                try {
                    testDate = sdf.parse(data[i]);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                SimpleDateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
                newDate[i] = formatter.format(testDate);

                // Adding value HashMap key => value
                HashMap<String, String> eventiHM = new HashMap<String, String>();
                eventiHM.put("titolo", titolo[i]);
                eventiHM.put("descrizione", descrizione[i]);
                eventiHM.put("data", newDate[i]);
                eventiHM.put("luogo", luogo[i]);

                //confrontare ed eliminare gli hashmap con valori uguali
//              for(Object key1:eventiHM.keySet()){  
//                    
//                  for(Object key2:eventiHM.keySet()){  
//                      if(!key1.toString().equals(key2.toString())){  
//                          String x=eventiHM.get(key1);  
//                          String y=eventiHM.get(key2);  
//                          if(x.equals(y)){  
//                              eventiHM.remove(key2);  
//                          }  
//                      }  
//                        
//                  }  
//              }
                oslist.add(eventiHM);               
                ListAdapter eventiAdapter = new SimpleAdapter(OlivetoEventi.this,
                        oslist, R.layout.row, new String[] { "titolo", "data" },
                        new int[] { R.id.rowTextView, R.id.rowEventiData });
                list.setAdapter(eventiAdapter);
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        // TODO Auto-generated method stub
                        // Toast.makeText(OlivetoEventi.this, "You Clicked at "+
                        // oslist.get(position).get("luogo"),
                        // Toast.LENGTH_SHORT).show();
                        //
                        Intent ev_intent = new Intent(OlivetoEventi.this,
                                ShowEventActivity.class);
                        String message = titolo[position] + "§"
                                + newDate[position] + "§"
                                + descrizione[position] + "§" + luogo[position];
                        ev_intent.putExtra(EXTRA_MESSAGE, message);
                        startActivity(ev_intent);

                    }

                });
            }
        }
    }

    private void connect() {
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(
                    "url");
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.d("HTTP", "collegamento effettuato");
            // convertire response a stringa
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "iso-8859-1"), 8);
                sb = new StringBuilder();
                sb.append(reader.readLine() + "\n");
                String line = "0";
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                // Log.d("CONVERTING", "conversione effettuata: " + result);
            } catch (Exception e) {
                Log.d("log_tag", "Error converting result: " + e.toString());
            }
            // recupero dati
            runOnUiThread(new Runnable() {
                public void run() {
                    Log.d("RUN", "entra");
                    try {
                        JSONObject jsonA = new JSONObject(result);
                        JSONArray jArray = jsonA.getJSONArray(TAG_EVENTI);
                        System.out
                                .println("*****JARRAY*****" + jArray.length());
                        lunghezza = jArray.length();
                        for (int i = 0; i < jArray.length(); i++) {
                            JSONObject json_data = jArray.getJSONObject(i);
                            titolo[i] = json_data.getString(TAG_TITOLO);
                            luogo[i] = json_data.getString(TAG_LUOGO);
                            data[i] = json_data.getString(TAG_DATA);
                            descrizione[i] = json_data.getString(TAG_DESC);
                        }

                    } catch (JSONException e1) {
                        Log.d("DATA", "no data found");
                    }
                }
            });
        } catch (ClientProtocolException e) {
            Log.d("HTTPCLIENT", e.getLocalizedMessage());
        } catch (IOException e) {
            Log.d("HTTPCLIENT", e.getLocalizedMessage());
        }

    }

    public void onBackPressed() {
        finish();
    }

    public void atHomeButton() {
        home = (ImageButton) findViewById(R.id.imageHome);
        home.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                 Intent intent = new Intent(OlivetoEventi.this, HomeActivity.class);
                    startActivity(intent);
            }
        });
    }

        public void retry(View v){
            onback();
        }
        public void onback(){
            finish();
        }

        public boolean isOnline() {
         cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

}

row.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="@android:color/darker_gray"
     >
    <TextView
        android:id="@+id/rowTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="20dp"
        android:textSize="25sp"
        />
    <TextView
        android:id="@+id/rowEventiData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"       
        android:textSize="15sp"
        />

    <ImageView 
        android:src="@drawable/list_item_arrow"     
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
         />

</RelativeLayout>

listview.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/rowTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/oliveto"
        android:gravity="center"
        android:paddingBottom="20dp"
        android:text="Eventi Olivetani"
        android:textSize="25sp" />

    <ListView
        android:id="@+id/eventiListView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/rowTextView" 
        android:layout_above="@+id/footer">
    </ListView>

    <RelativeLayout
        android:id="@+id/footer"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:background="#80C0C0C0" >

        <ImageButton
            android:id="@+id/imageRetry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="34dp"
            android:src="@drawable/reply" />

        <ImageButton
            android:id="@+id/imageHome"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@+id/imageRetry"
            android:layout_marginRight="38dp"
            android:src="@drawable/home" />
    </RelativeLayout>

</RelativeLayout>

0 个答案:

没有答案