我不知道我应该给这个问题什么标题,因为我的代码没有给我错误。我不知道为什么它表现如此。问题是,当我第一次点击_findButton时,它打开它取出3个listview项目并显示在列表中,当我点击后我想要清除列表项目,以便我再次点击_findButton它给了我同样的3 listview项目,但它每个重复给我6个项目。我搜索了很多,但不知道问题出在哪里。如果可以,请你帮助我。我是新来的。谢谢。
package com.donateblood.blooddonation;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.facebook.FacebookSdk;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by YouCaf Iqbal on 4/6/2016.
*/
public class MainGUI extends AppCompatActivity {
public static ArrayList<DonorPerson> Donors = new ArrayList<DonorPerson>();
@InjectView(R.id.findppl) Button _findButton;
GPSTracker gps;
String bloodgroup=null;
private double latitude;
private double longitude;DB db;
DBCursor cursor;
DBCollection collection;
Database dataobj = new Database();
ArrayList allPPLlat = new ArrayList();
ArrayList allPPLlong = new ArrayList();
ArrayList allPPLNumbers = new ArrayList();
ArrayList allPPLNames = new ArrayList();
ArrayList allPPLImages = new ArrayList();
ArrayList allPPLEmails = new ArrayList();
public Spinner mySpinner;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maingui);
ButterKnife.inject(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//FacebookSdk.sdkInitialize(MainGUI.this);
Spinner spinner =(Spinner) findViewById(R.id.spinner);
String[] list = getResources().getStringArray(R.array.blood_type);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,list);
spinner.setAdapter(adapter);
_findButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getCurrentLatLong();
dbAsync thrd = new dbAsync();
thrd.execute();
}
//distance=Distance(lablat, lablong, curlat, curlong);
});
}
public void getCurrentLatLong(){
gps = new GPSTracker(MainGUI.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
public class dbAsync extends AsyncTask<Void,Void,Void>{
private ProgressDialog pDialog;
@Override
protected Void doInBackground(Void... voids) {
getOtherLatLong();
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainGUI.this);
pDialog.setMessage("Searching people nearby...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
Intent intent = new Intent(getApplicationContext(), PeopleList.class);
//intent.putExtra("DonorsList",Donors);
startActivity(intent);
// Toast.makeText(getBaseContext(), "Near by latitudes "+SelectedPPLlat, Toast.LENGTH_LONG).show();
// Toast.makeText(getBaseContext(), "Near by longitudes "+SelectedPPLlong, Toast.LENGTH_LONG).show();
}
}
public void getOtherLatLong() {
db = dataobj.getconnection();
collection = db.getCollection("UserDetails");
mySpinner=(Spinner) findViewById(R.id.spinner);
bloodgroup = mySpinner.getSelectedItem().toString();
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("bloodgroup",bloodgroup);
cursor = collection.find(whereQuery);
while (cursor.hasNext()) {
DBObject doc = cursor.next();
// Lats longs used in the next for Loop for calculation distances
allPPLlat.add(doc.get("lat"));
allPPLlong.add(doc.get("long"));
// All these other arraylists are used to store object of a donor person
allPPLNumbers.add(doc.get("number").toString());
allPPLNames.add(doc.get("Name").toString());
allPPLImages.add(doc.get("image").toString());
allPPLEmails.add(doc.get("email").toString());
}
// Clear DONOR objects before populating
//Donors.clear();
//Donors.removeAll(Donors);
for(int i =0;i<allPPLlat.size();i++){
double Dist= Distance(Double.parseDouble(allPPLlat.get(i).toString()),Double.parseDouble(allPPLlong.get(i).toString()),latitude,longitude);
Dist=Dist/1000;
if(Dist<20){
Donors.add(new DonorPerson(""+allPPLNames.get(i)+"", ""+allPPLEmails.get(i)+"" ,""+allPPLNumbers.get(i)+"" ,""+allPPLImages.get(i)+""));
}
}
}
public double Distance(double lat1, double lon1, double lat2, double lon2) {
double R = 6371.0; // km
double dLat = (lat2 - lat1) * Math.PI / 180.0;
double dLon = (lon2 - lon1) * Math.PI / 180.0;
lat1 = lat1 * Math.PI / 180.0;
lat2 = lat2 * Math.PI / 180.0;
double a = Math.sin(dLat / 2.0) * Math.sin(dLat / 2.0) +
Math.sin(dLon / 2.0) * Math.sin(dLon / 2.0) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = R * c;
return d * 1000; // return distance in m
}
/* public ArrayList<DonorPerson> getList() {
return this.Donors;
} */
}
package com.donateblood.blooddonation;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by YouCaf Iqbal on 4/30/2016.
*/
public class PeopleList extends AppCompatActivity {
public ArrayAdapter<DonorPerson> adapter;
int count=0;
// public MainGUI mainobj;
// ArrayList<DonorPerson> Donors;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.peoplelistview);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//mainobj= new MainGUI();
// Donors.addAll(mainobj.getList());
//Donors= (ArrayList<DonorPerson>)getIntent().getSerializableExtra("DonorsList");
adapter = new MyListAdapter();
populateListView();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
for(int i =0; i <MainGUI.Donors.size(); i++){
MainGUI.Donors.remove(i);
}
adapter.notifyDataSetChanged();
finish();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed()
{
for(int i =0; i <MainGUI.Donors.size(); i++){
MainGUI.Donors.remove(i);
}
adapter.notifyDataSetChanged();
finish();
super.onBackPressed();
}
public void populateListView() {
ListView list = (ListView) findViewById(R.id.DonorsListView);
list.setAdapter(adapter);
//count = list.getAdapter().getCount();
}
public class MyListAdapter extends ArrayAdapter<DonorPerson> {
ArrayList allPPLNumbers = new ArrayList();
public MyListAdapter() {
super(PeopleList.this, R.layout.singlelistitemview, MainGUI.Donors);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder MainViewHolder = null;
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.singlelistitemview, parent, false);
ViewHolder viewHolder = new ViewHolder();
// Find the Donor to work with.
DonorPerson currentPerson = MainGUI.Donors.get(position);
allPPLNumbers.add(currentPerson.getNumber());
//Set the Image of the Current Donor
viewHolder.DonorImage = (ImageView) itemView.findViewById(R.id.image);
//currentPerson.getImage();
byte[] decodedString = Base64.decode(currentPerson.getImage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Bitmap decodedFinalImage = getRoundedShape(decodedByte);
//Bitmap RoundedImage = getRoundedShape(ImageBitmap);
viewHolder.DonorImage.setImageBitmap(decodedFinalImage);
viewHolder.CallBtn = (Button) itemView.findViewById(R.id.buttonCall);
viewHolder.CallBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String number = (String) allPPLNumbers.get(position);
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + number));
if (ActivityCompat.checkSelfPermission(PeopleList.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startActivity(intent);
}
});
viewHolder.MsgBtn = (Button) itemView.findViewById(R.id.buttonMsg);
viewHolder.MsgBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String number = (String) allPPLNumbers.get(position);
Uri uri = Uri.parse("smsto:" + number);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body","");
startActivity(intent);
}
});
viewHolder.NotifyBtn = (Button) itemView.findViewById(R.id.buttonNotify);
viewHolder.NotifyBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "Notify Clicked", Toast.LENGTH_LONG).show();
}
});
itemView.setTag(viewHolder);
}
else{
MainViewHolder= (ViewHolder) itemView.getTag();
}
return itemView;
}
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 200;
int targetHeight = 200;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth),
((float) targetHeight)) / 2),
Path.Direction.CCW);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight), null);
return targetBitmap;
}
}
public class ViewHolder {
ImageView DonorImage;
Button CallBtn;
Button MsgBtn;
Button NotifyBtn;
}
}
答案 0 :(得分:0)
我认为问题在于您没有清除为ListView提供值的ArrayList。要清除ArrayList,只需使用arrayList.clear();
将此代码放入onCreate
类的MainGUI
方法中。如果清除Donors
ArrayList,则应用程序应该正常运行。