Android:ListView项目单击无法正常工作

时间:2016-07-13 10:42:03

标签: java android listview gson sharedpreferences

我正在尝试实现“收藏夹”系统,因此当选择产品作为收藏夹(通过单击按钮)时,会将其传递给名为Favoris.java的类,该类将所有喜爱的产品显示为ListView,这些都是可点击的,以获取有关所点击产品的更多详细信息。到目前为止,listview工作得很好。

但这是我的主要问题:当我点击其中一个产品获取其详细信息时,会显示另一个不在收藏列表中的产品

我确实注意到了一些可能有用的东西:通过在我的列表中添加一些收藏夹,比如3,我注意到了一种模式:

  • 当我点击我作为收藏夹添加的第一个产品时,我会获得所有可用产品的第一个产品的详细信息(有一个包含所有可用产品的主ListView,这些产品都是从xml Feed中检索到的)
  • 当我点击我作为收藏夹添加的第二个产品时,我会获得所有可用产品的第二个产品的详细信息。
  • 当我点击我作为收藏夹添加的第三个产品时,我会获得所有可用产品的第三个产品的详细信息。

我目前将喜爱的产品作为类对象传递给收藏夹类,方法是使用Gson转换它并使用SharedPrefenreces传递它,而Favoris.java类将该产品返回并将其转换回类对象。

所以这是我所有我喜欢的产品的列表视图,你可以看到有4个产品被添加为收藏夹:

favorites' listview http://image.prntscr.com/image/d7a97e8edacb4970a4bd83bf4621ea6e.png

当点击第一个产品(PalaisHéracles)时,我得到另一个产品(默认产品列表中的第一个)名为“ChâteauPérigord”(你可以看到我没有将它添加为收藏夹,因为星形图标不是黑色而是白色):

wrong product detail http://image.prntscr.com/image/b9e89b52051a42d5bbaf520ddbcaaa1f.png

以下是产品详情的代码:

public class ProduitDetail extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

/**
 * fields
 */
private StackProduits produit;
private Button butStar;
/*images (main, thumbnails and gallery)*/
private ArrayList<String> imagesUrlListThumb, imagesUrlListFull = new ArrayList<String>();
private RecyclerAdapter recyclerAdapter;
private String urlRecyclerThumb = "";
/*view elements*/
private RecyclerView recyclerView;
private ImageView imgCurRecyclerView;
private Button btnMailCurProduct, btnMailAgency;


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

    /*get ids of the two star icons*/
    final int imgStarFull = R.drawable.ic_star;
    final int imgStarBorder = R.drawable.ic_star_border;

    /*get view references from content_produit_detail.xml*/
    butStar = (Button) findViewById(R.id.button_detail_heart);

    /*get produit class object from both Ventes.java and Location.java*/
    produit = new StackProduits();
    Intent intent = getIntent();
    produit = intent.getParcelableExtra("produit");


    /**handle favorites icon turned on or off when entering the product detail*/
    final SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    Set<String> jsonList = mPrefs.getStringSet("listJson2", new HashSet<String>());
    Set<String> jsonList2 = new HashSet<>();
    jsonList2.addAll(jsonList);
    produit.setIsAddedAsFav("1");
    Gson gson = new Gson();
    String myJson = gson.toJson(produit);

    if (jsonList2.contains(myJson)) {
        butStar.setCompoundDrawablesWithIntrinsicBounds(imgStarFull, 0, 0, 0);
    } else {
        produit.setIsAddedAsFav("0");
    }

    /**
     * Listener for the star button used to make the current product favorite by adding it to a
     * list of all the products currently set as favorite
     */
    butStar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*Change the icon and make a toast when the heart button is pressed*/
            if (produit.getIsAddedAsFav().equalsIgnoreCase("0")) {
                produit.setIsAddedAsFav("1");
                butStar.setCompoundDrawablesWithIntrinsicBounds(imgStarFull, 0, 0, 0);

                SharedPreferences.Editor prefsEditor = mPrefs.edit();
                Gson gson = new Gson();

                //convert product to string via gson
                String myJson = gson.toJson(produit);
                //prefsEditor.putString("MyObject", myJson);

                //get the Set<String> reference back to keep the entire list of favorites
                Set<String> jsonList = mPrefs.getStringSet("listJson2", new HashSet<String>());

                //make a copy of Set<String> pref to make it usable
                Set<String> jsonList2 = new HashSet<>();

                //add the list and the new product to the copy of Set<String>
                jsonList2.addAll(jsonList);
                jsonList2.add(myJson);

                //add list to editor
                prefsEditor.putStringSet("listJson2", jsonList2);
                prefsEditor.apply();
                Toast.makeText(ProduitDetail.this, getString(R.string.toast_favorite_added), Toast.LENGTH_SHORT).show();
            } else {
                produit.setIsAddedAsFav("1");
                butStar.setCompoundDrawablesWithIntrinsicBounds(imgStarBorder, 0, 0, 0);
                SharedPreferences.Editor prefsEditor = mPrefs.edit();

                Set<String> jsonList = mPrefs.getStringSet("listJson2", new HashSet<String>());

                Set<String> jsonList2 = new HashSet<>();
                jsonList2.addAll(jsonList);

                Gson gson = new Gson();
                String myJson = gson.toJson(produit);

                jsonList2.remove(myJson);

                prefsEditor.putStringSet("listJson2", jsonList2);
                prefsEditor.apply();
                produit.setIsAddedAsFav("0");
                Toast.makeText(ProduitDetail.this, getString(R.string.toast_favorite_removed), Toast.LENGTH_SHORT).show();
            }
        }
    });
}
}

以下是处理收藏夹的班级代码:

public class Favoris extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

/**fields*/
private ListView produitFavorisListView;
private List<StackProduits> listProduits = new ArrayList<>();
private ProduitsAdapter adapterFavoris;

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

    /*get ListView reference*/
    produitFavorisListView = (ListView) findViewById(R.id.favoritesList);

    /*getting back data from shared preferences*/
    final SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    final Gson gson = new Gson();

     //getting back favorites
    Set<String> myJson = mPrefs.getStringSet("listJson2", new HashSet<String>());

    if (myJson.isEmpty() && listProduits.isEmpty()) {
        produitFavorisListView.setAdapter(null);
    }
    else if (myJson.isEmpty() && listProduits != null) {
        adapterFavoris.notifyDataSetChanged();
        adapterFavoris = new ProduitsAdapter(getApplicationContext(), -1, listProduits);
        produitFavorisListView.setAdapter(adapterFavoris);
    }
    else{
        //for each where we get back values from sting set, then convert to product
        for (String id : myJson) {
            StackProduits savedProduct = gson.fromJson(id, StackProduits.class);
            listProduits.add(savedProduct);
        }
        adapterFavoris = new ProduitsAdapter(getApplicationContext(), -1, listProduits);
        produitFavorisListView.setAdapter(adapterFavoris);
    }

    //Set the click listener to launch the browser when a row is clicked.
    produitFavorisListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
            Intent intentProduitFavorisDetail = new Intent(Favoris.this, ProduitDetail.class);
            StackProduits ProduitFavoris = ProduitsXmlPullParser.getStackProduitFromFile(Favoris.this).get(pos);
            intentProduitFavorisDetail.putExtra("produit", ProduitFavoris);
            startActivity(intentProduitFavorisDetail);
        }
    });
}
}

这里是我最喜欢的ListView的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="13dp"
android:layout_marginTop="55dp">

<TextView
    android:id="@+id/content_favorite_emptylist"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:visibility="gone"
    android:textColor="#343232"
    android:textSize="18sp"
    android:textStyle="bold"/>

<ListView
    android:id="@+id/favoritesList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true" />

这是我的适配器类:

public class ProduitsAdapter extends ArrayAdapter<StackProduits> {

/**
 * fields
 */
ImageLoader imageLoader;
DisplayImageOptions options;
List<StackProduits> productList;
SparseBooleanArray mSelectedItemsIds;

public ProduitsAdapter(Context ctx, int textViewResourceId, List<StackProduits> sites) {
    super(ctx, textViewResourceId, sites);

    /**Setup the ImageLoader, we'll use this to display our images*/
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).build();
    imageLoader = ImageLoader.getInstance();
    imageLoader.init(config);

    mSelectedItemsIds = new SparseBooleanArray();

    /**Setup options for ImageLoader so it will handle caching for us.*/
    options = new DisplayImageOptions.Builder()
            .cacheInMemory()
            .cacheOnDisc()
            .build();
}

/**
 * This method is responsible for creating row views out of a StackProduits object that can be put
 * into our ListView.
 * <p/>
 * (non-Javadoc)
 *
 * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
 */
@Override
public View getView(int pos, View convertView, ViewGroup parent) {
    RelativeLayout row = (RelativeLayout) convertView;
    //Log.i("StackSites", "getView pos = " + pos);
    if (null == row) {   //No recycled View, we have to inflate one.
        LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = (RelativeLayout) inflater.inflate(R.layout.item_row, null);
    }

    //Get our View References from item_row.xml
    final ImageView iconImg = (ImageView) row.findViewById(R.id.iconImg);
    TextView txtDesignation = (TextView) row.findViewById(R.id.nameTxt);
    TextView txtAbout = (TextView) row.findViewById(R.id.aboutTxt);
    TextView txtPrice = (TextView) row.findViewById(R.id.priceTxt);
    TextView txtTotalArea = (TextView) row.findViewById(R.id.areaTxt);
    final ProgressBar indicator = (ProgressBar) row.findViewById(R.id.progress);

    //Initially we want the progress indicator visible, and the image invisible
    indicator.setVisibility(View.VISIBLE); //show progress indicator
    iconImg.setVisibility(View.INVISIBLE); //make image invisible

    //Setup a listener we can use to switch from the loading indicator to the Image once it's ready
    //changed ImageLoadingListener with SimpleImageLoadingListener
    SimpleImageLoadingListener listener = new SimpleImageLoadingListener() {
        @Override
        public void onLoadingStarted(String arg0, View arg1) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onLoadingCancelled(String arg0, View arg1) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
            indicator.setVisibility(View.INVISIBLE);
            iconImg.setVisibility(View.VISIBLE);
        }

        @Override
        public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
            // TODO Auto-generated method stub
        }
    };

    //Load the image and use our options so caching is handled.
    imageLoader.displayImage(getItem(pos).getImgUrl(), iconImg, options, listener);

    //Set the relevant text in our TextViews (ListView)
    txtDesignation.setText(getItem(pos).getDesignation());
    txtAbout.setText(getItem(pos).getAbout());
    txtPrice.setText(getItem(pos).getPrice());
    txtTotalArea.setText(getItem(pos).getArea());

    //return view that represents the full row
    return row;
}
}

LogI里面的onItemClick(Favoris.java)

Log.i("test", adapterFavoris.getItem(pos).toString());


07-13 13:27:27.907 1613-1613/com.example.adam_jaamour.cfimmobilier W/System: ClassLoader referenced unknown path: /data/app/com.example.adam_jaamour.cfimmobilier-2/lib/x86
07-13 13:27:30.020 1613-1613/com.example.adam_jaamour.cfimmobilier W/System: ClassLoader referenced unknown path: /data/app/com.example.adam_jaamour.cfimmobilier-2/lib/x86
07-13 13:27:30.169 1613-1613/com.example.adam_jaamour.cfimmobilier W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-13 13:27:30.380 1613-1701/com.example.adam_jaamour.cfimmobilier D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true

                                                                                 [ 07-13 13:27:30.388  1613: 1613 D/         ]
                                                                                 HostConnection::get() New Host Connection established 0xaa979e80, tid 1613


                                                                                 [ 07-13 13:27:30.414  1613: 1701 D/         ]
                                                                                 HostConnection::get() New Host Connection established 0xaa9796d0, tid 1701
07-13 13:27:30.418 1613-1701/com.example.adam_jaamour.cfimmobilier I/OpenGLRenderer: Initialized EGL, version 1.4
07-13 13:27:31.015 1613-1613/com.example.adam_jaamour.cfimmobilier I/Choreographer: Skipped 33 frames!  The application may be doing too much work on its main thread.
07-13 13:27:32.408 1613-1613/com.example.adam_jaamour.cfimmobilier E/libEGL: call to OpenGL ES API with no current context (logged once per thread)
07-13 13:27:32.649 1613-1701/com.example.adam_jaamour.cfimmobilier E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa2329ad0
07-13 13:27:36.071 1613-1613/com.example.adam_jaamour.cfimmobilier W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=161.13647, y[0]=1479.668, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=16698889, downTime=16695116, deviceId=0, source=0x1002 }
07-13 13:27:36.071 1613-1613/com.example.adam_jaamour.cfimmobilier W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=161.13647, y[0]=1479.668, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=16698889, downTime=16695116, deviceId=0, source=0x1002 }
07-13 13:27:36.072 1613-1613/com.example.adam_jaamour.cfimmobilier W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=161.13647, y[0]=1479.668, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=16698889, downTime=16695116, deviceId=0, source=0x1002 }
07-13 13:27:36.072 1613-1613/com.example.adam_jaamour.cfimmobilier W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=161.13647, y[0]=1479.668, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=16698889, downTime=16695116, deviceId=0, source=0x1002 }
                                                                               <p>&nbsp;</p>, reference=FFV0593, type=Apartment, numberOfRooms=Studio, livingArea=49sqm, terraceArea=-, building=Le Montaigne, district=Carré d'Or, parking=null, cellar=null, typeTransaction=Ԁt、��Fo, city=null, country=null, date created=2014-03-12 17:48:49, date last modified=2016-07-12 10:09:30]
07-13 13:27:36.366 1613-1613/com.example.adam_jaamour.cfimmobilier W/Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
07-13 13:27:36.836 1613-1623/com.example.adam_jaamour.cfimmobilier W/art: Suspending all threads took: 12.863ms
07-13 13:27:36.848 1613-1623/com.example.adam_jaamour.cfimmobilier I/art: Background sticky concurrent mark sweep GC freed 12227(1070KB) AllocSpace objects, 3(52KB) LOS objects, 2% free, 41MB/42MB, paused 13.974ms total 66.456ms
07-13 13:27:36.952 1613-1619/com.example.adam_jaamour.cfimmobilier W/art: Suspending all threads took: 19.437ms
07-13 13:27:37.062 1613-1623/com.example.adam_jaamour.cfimmobilier W/art: Suspending all threads took: 9.523ms
07-13 13:27:37.071 1613-1623/com.example.adam_jaamour.cfimmobilier I/art: Background sticky concurrent mark sweep GC freed 2527(286KB) AllocSpace objects, 17(812KB) LOS objects, 0% free, 43MB/43MB, paused 9.952ms total 80.879ms
07-13 13:27:37.125 1613-1701/com.example.adam_jaamour.cfimmobilier E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa2329c20
07-13 13:27:37.132 1613-1701/com.example.adam_jaamour.cfimmobilier D/OpenGLRenderer: endAllStagingAnimators on 0xa20b6880 (ListView) with handle 0xb3fec540

2 个答案:

答案 0 :(得分:1)

我认为您获取错误数据的问题在于,您根据从不同数据集中单击的项目获取数据,然后根据适配器基于其视图(两个数据集可能包含)相同的数据,但顺序不同)。

您正在从json构建数据集:

 //for each where we get back values from sting set, then convert to product 
    for (String id : myJson) {
        StackProduits savedProduct = gson.fromJson(id, StackProduits.class);
        listProduits.add(savedProduct);
    } 
    adapterFavoris = new ProduitsAdapter(getApplicationContext(), -1, listProduits);
    produitFavorisListView.setAdapter(adapterFavoris);

在OnItemClickListener内部,根据您的方法签名,您需要从文件中检索数据:

 //Set the click listener to launch the browser when a row is clicked. 
produitFavorisListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override 
    public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
        Intent intentProduitFavorisDetail = new Intent(Favoris.this, ProduitDetail.class);
        StackProduits ProduitFavoris = ProduitsXmlPullParser.getStackProduitFromFile(Favoris.this).get(pos);
        intentProduitFavorisDetail.putExtra("produit", ProduitFavoris);
        startActivity(intentProduitFavorisDetail);
    } 
});

数据可以以不同的顺序存储,这可以解释为什么当您选择某些项目时的其他项目信息。测试它的一种简单方法是在onItemClick中放置一个日志语句,以打印出列表项的字符串表示。

如果这确实是您的问题,可能的解决方案是在onItemClick内部对适配器的引用上调用ProduitsAdapter.getItem()以获取对应于&#39; pos&#39;的实际项目。

答案 1 :(得分:0)

通常会发生这种情况,因为ListView中的项目是焦点。尝试添加

android:descendantFocusability="blocksDescendants"

在您的自定义ListView

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="13dp"
android:layout_marginTop="55dp"
android:descendantFocusability="blocksDescendants">