我有这段代码:
ArretsFragment.java:
package activity;
public class ArretsFragment extends Fragment {
ConnectionDetector cd;
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "https://open.tan.fr/ewp/arrets.json";
private List<Arrets> arretsList = new ArrayList<Arrets>();
private ListView listView;
private CustomListAdapter adapter;
private SwipeRefreshLayout swipeLayout;
private Menu menu;
private MenuInflater inflater;
HashMap<String, String> lieumap = new HashMap<String, String>();
EditText search;
Spfav sharedPreference;
ArrayList listArrets;
public ArretsFragment() {
}
public void filtrer() {
// retourner la chaine saisie par l'utilisateur
String name = search.getText().toString();
// créer une nouvelle liste qui va contenir la résultat à afficher
ArrayList listFoodNew = new ArrayList();
for (Arrets food : arretsList) {
// si le nom du food commence par la chaine saisie , ajouter-le !
if (food.getArret().toLowerCase().toString().startsWith(name)) {
listFoodNew.add(food);
}
}
//vider la liste
listView.setAdapter(null);
// ajouter la nouvelle liste
listView.setAdapter(new CustomListAdapter(getActivity(), listFoodNew));
adapter.notifyDataSetChanged();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView = (ListView) getActivity().findViewById(R.id.list);
// movieList is an empty array at this point.
adapter = new CustomListAdapter(getActivity(), arretsList);
listView.setAdapter(adapter);
search = (EditText) getActivity().findViewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
filtrer();
adapter.notifyDataSetChanged();
}
});
// Showing progress dialog before making http request
swipeLayout = (SwipeRefreshLayout) getActivity().findViewById(R.id.container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
Toast.makeText(getActivity(), "Rechargement...", Toast.LENGTH_SHORT).show();
arretsList.clear();
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Arrets arret = new Arrets();
arret.setArret(obj.getString("libelle"));
String lieu = obj.getString("codeLieu");
arret.setLieu(lieu);
JSONArray genreArry = obj.getJSONArray("ligne");
ArrayList<String> genre = new ArrayList<String>();
int ligne = genreArry.length();
for (int v = 0; v < ligne; v++) {
JSONObject nl = genreArry.getJSONObject(v);
genre.add(nl.optString("numLigne").toString());
}
arret.setLigne(genre);
// adding movie to movies array
arretsList.add(arret);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getActivity(), "No internet connection !", Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
swipeLayout.setRefreshing(false);
}
});
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView textView = (TextView) view.findViewById(R.id.lieu);
String text = textView.getText().toString();
TextView textView2 = (TextView) view.findViewById(R.id.arret);
String libelle = textView2.getText().toString();
Intent i = new Intent(ArretsFragment.this.getActivity(), TempsActivity.class);
i.putExtra("text", text);
i.putExtra("libelle", libelle);
startActivity(i);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
sharedPreference = new Spfav();
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(getActivity(), arretsList.get(position));
Toast.makeText(getActivity(), "Ajouté au favoris !", Toast.LENGTH_LONG).show();
button.setTag("red");
button.setImageResource(R.drawable.ic_heart_red);
} else {
sharedPreference.removeFavorite(getActivity(), arretsList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_heart_white);
Toast.makeText(getActivity(), "Supprimé des favoris !", Toast.LENGTH_LONG).show();
}
return true;
}
});
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listArrets = new ArrayList();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Arrets arret = new Arrets();
arret.setArret(obj.getString("libelle"));
String lieu = obj.getString("codeLieu");
arret.setLieu(lieu);
JSONArray genreArry = obj.getJSONArray("ligne");
ArrayList<String> genre = new ArrayList<String>();
int ligne = genreArry.length();
for (int v = 0; v < ligne; v++) {
JSONObject nl = genreArry.getJSONObject(v);
genre.add(nl.optString("numLigne").toString());
}
arret.setLigne(genre);
arretsList.add(arret);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getActivity(), "No internet connection !", Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_arrets, container, false);
// Inflate the layout for this fragment
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_search) {
Toast.makeText(getActivity(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
和Spfav.java:
package util;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import model.Arrets;
public class Spfav {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public Spfav() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<Arrets> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, Arrets product) {
List<Arrets> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<Arrets>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, Arrets product) {
ArrayList<Arrets> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<Arrets> getFavorites(Context context) {
SharedPreferences settings;
List<Arrets> favorites;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
Arrets[] favoriteItems = gson.fromJson(jsonFavorites,
Arrets[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<Arrets>(favorites);
} else
return null;
return (ArrayList<Arrets>) favorites;
}
}
我想知道为什么,当我过滤时,当我长按一个项目时,它会在过滤器之前获取该项目!
获得一些帮助会非常好。
答案 0 :(得分:0)
在OnItemClickListener
替换此内容:
TextView textView = (TextView) view.findViewById(R.id.lieu); String text = textView.getText().toString(); TextView textView2 = (TextView) view.findViewById(R.id.arret); String libelle = textView2.getText().toString();
用这个:
Arrets item = (Arrets) adapter.getItemAtPosition(position);
这同样适用于您的OnItemLongClickListener
。
简而言之 - 从您的适配器获取项目,而不是形成ListView
或ArrayList
个对象。
答案 1 :(得分:0)
你正在做很多适配器应该为你处理的工作。 每次更改列表视图内容时,都会创建一个新的适配器。
每次创建一个新的适配器都是浪费,在我看来,最好让适配器处理数据。
尝试将适配器设置为全局变量,并在过滤时更新其内容。
伪代码:
CustomListAdapter mAdapter
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView = (ListView) getActivity().findViewById(R.id.list);
// movieList is an empty array at this point.
mAdapter = new CustomListAdapter(getActivity(), arretsList);
listView.setAdapter(mAdapter);
...
}
现在你的适配器可以存储arretsList并根据需要更新它。
然后在适配器中创建一个自定义方法来更新存储的arraylist并从filtrer中调用它,如下所示:
mAdapter.update(listFoodNew);
您遇到错误项目问题的原因是(如上所述)您有两个正在使用的适配器。
你在setOnItemLongClickListener中调用的全局函数如下:
arretsList.get(position)
与您在filtrer
中创建的新适配器不同listView.setAdapter(new CustomListAdapter(getActivity(), listFoodNew));
所以你已经用两个不同的数据集创建了两个差异适配器。一个过滤,一个没过。
试试这个:
@Override
public void setOnItemLongClickListener(AdapterView<?> parent, View view, int position, long id) {
//I think this is the data type your adapter uses.
Arrets food = mAdapter.getItem(position);
//Now check your color and fire your toast
}