Handling image button click inside a RecycleView item - android

I have a button inside CardView which represents item of RecycleView. I've managed to handle the click event inside the ViewHolder class but I need to call function on MainActivity, How can I implement that with below code?
My code as below
ShopItemRecyclerViewAdapter.java
public class ShopItemRecyclerViewAdapter extends RecyclerView.Adapter<ShopItemRecyclerViewAdapter.ListItemViewHolder> {
static ArrayList<ShopListItemModel> list;
LayoutInflater inflater;
public ShopItemRecyclerViewAdapter(ArrayList<ShopListItemModel> list, Context context){
inflater = LayoutInflater.from(context);
this.list = list;
}
public ListItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_item, parent , false);
ListItemViewHolder vh = new ListItemViewHolder(view);
return vh;
}
public void onBindViewHolder(ListItemViewHolder holder, int position) {
ShopListItemModel current = list.get(position);
holder.name.setText(current.getName());
holder.price.setText(String.valueOf(current.getPrice()));
}
public int getItemCount() {
return list.size();
}
public static class ListItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView name;
TextView price;
ImageButton btnDelete;
ListItemViewHolder(final View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cvShopListItem);
name = (TextView)itemView.findViewById(R.id.name);
price = (TextView)itemView.findViewById(R.id.price);
btnDelete = (ImageButton)itemView.findViewById(R.id.btnDeleteItem);
itemView.setOnClickListener(this);
btnDelete.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//here i can handle the click but i think i need to use it in the main activity
}
}
}
MainActivity.java (skipped irrelevent code)
public class ShopCartScreen extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
RecyclerView cartItems; //recycler to hold the cart list
ArrayList<ShopListItemModel> list = new ArrayList<ShopListItemModel>();
ShopItemRecyclerViewAdapter adapter;
GetShopingCartList getShopingCartList; ////instance of network operation class to retrieve shop cart items list from server data base
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shop_carts_list);
cartItems = (RecyclerView) findViewById(R.id.newListItem);
cartItems.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
cartItems.setLayoutManager(llm)
}
public void bindData(int listNumber) {
getShopingCartList = new GetShopingCartList(this, list, adapter, cartItems, listNumber, totalPrice);
getShopingCartList.execute("link to query which returns json object");
}
}
GetShopingCartList.java for network operation
public class GetShopingCartList extends AsyncTask<String, String, ArrayList<ShopListItemModel>> {
private ArrayList<ShopListItemModel> shopCartItemList;
Context context;
RecyclerView items;
ShopItemRecyclerViewAdapter adapter;
int listNumber;
public GetShopingCartList(Context context, ArrayList<ShopListItemModel> shopCartItemList, ShopItemRecyclerViewAdapter adapter,
RecyclerView items ,int listNumber) {
this.context = context;
this.shopCartItemList = shopCartItemList;
this.adapter = adapter;
this.items = items;
this.listNumber = listNumber;
}
protected ArrayList<ShopListItemModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
shopCartItemList = new ArrayList<ShopListItemModel>();
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("result");
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);//get the cuttent json object which is representaion of shop cart model object
String name = finalObject.getString("name");
String price = finalObject.getString("price");
Double d = Double.parseDouble(price);
ShopListItemModel item = new ShopListItemModel(name, d);
shopCartItemList.add(item);//adds the shopcart to the list of shop carts model
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return shopCartItemList;
}
protected void onPostExecute(ArrayList<ShopListItemModel> s) {
super.onPostExecute(s);
adapter = new ShopItemRecyclerViewAdapter(shopCartItemList, context);
items.setAdapter(adapter);
}
public ArrayList<ShopListItemModel> getList() {
return shopCartItemList;
}
}

Implement a method inside ShopCartScreen.java, then you can use the context object inside the adapter.
((ShopCartScreen)context).methodImplemented(ShopListItemModel model)
//add this code inside onClick event of the button

ok this is my solution if anyone needs it (i combined 2 methods/ 1 in the main activity and 1 in the recycler adapter):
in my recycler adapter i added this delete method:
//delete the item from the recycler Immediately for user interaction
public void delete(int position){
list.remove(position);
notifyItemRemoved(position);
}
in my ViewHolder class:
ListItemViewHolder(final View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cvShopListItem);
name = (TextView)itemView.findViewById(R.id.name);
price = (TextView)itemView.findViewById(R.id.price);
btnDelete = (ImageButton)itemView.findViewById(R.id.btnDeleteItem);
itemView.setOnClickListener(this);
btnDelete.setOnClickListener(this);
}
#Override
public void onClick(View v) {
((ShopCartScreen)context).deleteItem(getPosition());//calls method in main activity
delete(getPosition());
}
and in the main activity:
public void deleteItem(int postion){
list = getShopingCartList.getList();
ShopListItemModel tmp = list.get(postion);
tmp.getName(); //gets the item name to remove
shopCartModel.getNumber(); //gets the cart number for deleting the item for the correct cart
new DeleteCartItem(this , shopCartModel , tmp).execute(); //remove the item from the data base
}

Related

user picks item from spinner, corresponding number in csv file shows intextview

I have it so, when the user presses the fab, a cardview is added to the recyclerview layout. Inside each cardview that the user adds, is a spinner, checkbox edittext and textview. The spinner is populated by the first column in a csv file. The first column has item names, the second column has specific numbers relating to that product some of which can be the same
i had a previous similar app where when the user selects an item from the spinner, the coressponding number from the csv file shows in the textview. However that was without the recyclerviews or cardviews so I am trying to implement it in my code now (with recyclerview and cardviews)
However as I've been trying to implmenent that code in my current ProductAdapter (recyclerviewadapter) Code I have got an error:
Compilation Errors:
error: cannot find symbol method getResources()
It comes from this chunk of code
InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
CSVFile csvFile = new CSVFile(inputStream);
final List<String> mSpinnerItems = csvFile.read();
Here is my full ProductAdapter.java code
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();
private Map<String, String> numberItemValues = new HashMap<>();
private SearchableSpinner spinner;
//we are storing all the products in a list
private List<Product> productList;
private Activity create;
//TODO CODE FOR CSV FILE
/*InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
CSVFile csvFile = new CSVFile(inputStream);
final List<String> mSpinnerItems = csvFile.read();*/
InputStream inputStream = null;
List<String> mSpinnerItems = null;
CSVFile csvFile = null;
//TODO END OF CODE FOR CSV FILE
public ProductAdapter(Activity activity) {
create = activity;
}
//getting the context and product list with constructor
public ProductAdapter(Activity activity, List<Product> productList) {
// this.mCtx = mCtx;
/* inputStream = create.getResources().openRawResource(R.raw.shopitems);
csvFile = new CSVFile(inputStream);
mSpinnerItems = csvFile.read();*/
create = activity;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(create);
View view = inflater.inflate(R.layout.layout_products, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(final ProductViewHolder holder, final int position) {
// //getting the product of the specified position
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(create, R.layout.item_spinner_layout,
Product.getSpinnerItemsList());
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinner.setAdapter(spinnerArrayAdapter);
holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int mPosition, long id) {
mSpinnerSelectedItem.put(position, mPosition);
TextView mTextView = view.findViewById(R.id.mSpinnerText);
//TODO CODE FOR GETTING AISLE NUMBER AND PUTTING IT IN THE TEXTVIEW
String currentItem = mSpinnerItems.get(position);
String aisleNumber = numberItemValues.get(currentItem);
holder.textView5.setText(aisleNumber);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//binding the data with the viewholder views
if (mSpinnerSelectedItem.containsKey(position)) {
holder.spinner.setSelection(mSpinnerSelectedItem.get(position));
}
holder.getView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create);
// set title
alertDialogBuilder.setTitle("Delete Item");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete this item?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
holder.checkBox.setChecked(false);
holder.spinner.setSelection(0);
productList.remove(holder.getAdapterPosition());
notifyItemRemoved(holder.getAdapterPosition());
Toast.makeText(create, "Item removed.", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
SearchableSpinner spinner;
EditText editText;
TextView textView5;
CheckBox checkBox;
LinearLayout linearLayout;
View rootView;
public ProductViewHolder(View itemView) {
super(itemView);
spinner = itemView.findViewById(R.id.spinner);
editText = itemView.findViewById(R.id.editText);
textView5 = itemView.findViewById(R.id.textView5);
checkBox = itemView.findViewById(R.id.checkBox);
rootView = itemView.findViewById(R.id.linearLayout);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// makes the set disappear when checkbox is ticked.
if(isChecked){
checkBox.setChecked(false);
spinner.setSelection(0);
productList.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
Toast.makeText(create, "Done!", Toast.LENGTH_LONG).show();
}
}
});
}
public View getView() {
return rootView;
}
}
//TODO CODE FOR CSV FILE
private class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream) {
this.inputStream = inputStream;
}
public List<String> read() {
List<String> resultList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",");
numberItemValues.put(row[1], row[0]);
resultList.add(row[1]);
}
} catch (IOException e) {
Log.e("Main", e.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException e) {
Log.e("Main", e.getMessage());
}
}
return resultList;
}
}
}
create.java code which is my mainactivity where the cards are added and the fab is etc
public class create extends AppCompatActivity {
//a list to store all the products
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
Product mProduct;
private Map<String, String> numberItemValues = new HashMap<>();
private Map<Integer, Integer> mSpinnerSelectedItem = new HashMap<Integer, Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
//opens csv
InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
CSVFile csvFile = new CSVFile(inputStream);
final List<String> mSpinnerItems = csvFile.read();
//getting the recyclerview from xml
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
productList.add(new Product(mSpinnerItems, "Test Edit Text",false, "Text String 2"));
final ProductAdapter adapter = new ProductAdapter(this, productList);
//TODO FAB BUTTON
FloatingActionButton floatingActionButton =
findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
productList.add(mProduct);
if(adapter != null)
adapter.notifyDataSetChanged();
//Handle the empty adapter here
}
});
//setting adapter to recyclerview
recyclerView.setAdapter(adapter);
}
private class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream) {
this.inputStream = inputStream;
}
public List<String> read() {
List<String> resultList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",");
//TODO I edited this part so that you'd add the values in our new hash map variable
numberItemValues.put(row[1], row[0]);
resultList.add(row[1]);
}
} catch (IOException e) {
Log.e("Main", e.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException e) {
Log.e("Main", e.getMessage());
}
}
return resultList;
}
}
}
The adapter has know idea about getResources(). This needs to come from an Activity or Context object. So do this:
InputStream inputStream = null;
List<String> mSpinnerItems = null;
CSVFile csvFile = null;
then in your public ProductAdapter() method initialize the InputStream properly.
public ProductAdapter(Activity activity, List<Product> productList) {
create = activity;
//INFO:: Now initialize the InputStream
inputStream = create.getResources().openRawResource(R.raw.shopitems);
csvFile = new CSVFile(inputStream);
mSpinnerItems = csvFile.read();
this.productList = productList;
}
Of course you could create a string-array resource and fill the spinner view with that.
<string-array name="my_values">
<item>Hello</item>
<item>World</item>
<item>Back</item>
<item>Again</item>
</string-array>
Then in the layout file:
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
android:entries="#array/my_values"
/>
.
EDIT
With the updated code you can remove:
InputStream inputStream = null;
List<String> mSpinnerItems = null;
CSVFile csvFile = null;
From the ProductAdapter.
The NullPointerException error occurring at line:
String currentItem = mSpinnerItems.get(position);
is caused because mSpinnerItems is no longer being used and is set to null. So, in order to get the value of the selection in the spinner do this:
holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int mPosition, long id) {
mSpinnerSelectedItem.put(position, mPosition);
TextView mTextView = view.findViewById(R.id.mSpinnerText);
//TODO CODE FOR GETTING AISLE NUMBER AND PUTTING IT IN THE TEXTVIEW
//SearchableSpinner spinner = (SearchableSpinner)view;
String currentItem = holder.spinner.getItemAtPosition(mPosition).toString();
// or try
// spinner.getAdapter.getItem(mPosition).toString();
String aisleNumber = numberItemValues.get(currentItem);
holder.textView5.setText(aisleNumber);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
.
NEW EDIT:
in the ProductAdapter use this:
public ProductAdapter(Activity activity, List<Product> productList, HashMap<String, String> numberList) {
numberItemValues = numberList;
create = activity;
this.productList = productList;
}
and change this line in the "create" Activity:
final ProductAdapter adapter = new ProductAdapter(this, productList, numberItemValues);

CardView in RecyclerView - spinners

I am following g this tutorial https://inducesmile.com/android/android-recyclerview-and-cardview-in-material-design-tutorial/
My previous app file had it so the spinners were populated by a csv file. Now I am just making another app file because I wanted to start again by using cardviews and recyclerview.
However I am having some trouble with trying to implement my previous spinner code into this new app file using recycler views and cardviews.
The Example linked above calls for a class called ItemObject.java. I assum ed this is where I put the code that reads the csv.
ItemObject class
public class ItemObject {
Spinner spinner;
public void setText(String spinner) {
private Map<String, String> numberItemValues = new HashMap<>();
private class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream) {
this.inputStream = inputStream;
}
public List<String> read() {
List<String> resultList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",");
//TODO I edited this part so that you'd add the values in our new hash map variable
numberItemValues.put(row[1], row[0]);
resultList.add(row[1]);
}
} catch (IOException e) {
Log.e("Main", e.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException e) {
Log.e("Main", e.getMessage());
}
}
return resultList;
}
}
}
}
Then the example calls for a RecyclerViewAdatper. I am confused what to put in the OnBindViewHolder part. What is suppose to go in there, to do with my spinner?
RecyclerViewAdapter class
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private List<ItemObject> itemList;
private Context context;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_products, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, int position) {
// **WHAT TO PUT HERE**
//holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
}
#Override
public int getItemCount() {
return this.itemList.size();
}
}
And here is the RecyclerViewHolders class just for anyones reference.
public class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView countryName;
public ImageView countryPhoto;
public Spinner spinner;
public TextView textView5;
public CheckBox checkBox;
public EditText editText;
public RecyclerViewHolders(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
/* countryName = (TextView)itemView.findViewById(R.id.country_name);
countryPhoto = (ImageView)itemView.findViewById(R.id.country_photo);*/
spinner = (Spinner)itemView.findViewById(R.id.spinner);
textView5 = (TextView)itemView.findViewById(R.id.textView5);
checkBox = (CheckBox)itemView.findViewById(R.id.checkBox);
editText = (EditText)itemView.findViewById(R.id.editText);
}
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked Country Position = " + getPosition(), Toast.LENGTH_SHORT).show();
}
}
You can pass CSV values in an String Array form to your recyleview adpater constructor. You can use these values to populate your spinner something like this
String [] spinnerValues;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList, String [] spinnerValues) {
this.itemList = itemList;
this.context = context;
this.spinnerValues = spinnerValues
}
Make View Holder class a inner class in your adapter and use below code.
spinner = (Spinner)itemView.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, YOUR_STRING_ARRAY);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

RecycleView not calling methods

I'm trying to fetch data from a JSON, but it doesn't seem to work. OnBindViewHolder is never called...
ADAPTER CODE:
public class AdapterRallye extends RecyclerView.Adapter<AdapterRallye.MyViewHolder> implements View.OnClickListener {
private Context context;
private View.OnClickListener listener;
private List<DataRallye> data;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView Rallye_Nom;
public ImageView Rallye_Foto;
public TextView Rallye_Provincia;
public TextView Rallye_DataI;
public TextView Rallye_Tipus;
// create constructor to get widget reference
public MyViewHolder(final View itemView) {
super(itemView);
Rallye_Nom = (TextView) itemView.findViewById(R.id.tv_nom);
Rallye_Foto = (ImageView) itemView.findViewById(R.id.iv_foto);
Rallye_Provincia = (TextView) itemView.findViewById(R.id.tv_provincia);
Rallye_DataI = (TextView) itemView.findViewById(R.id.tv_datai);
Rallye_Tipus = (TextView) itemView.findViewById(R.id.tv_tipus);
}
}
// create constructor to innitilize context and data sent from MainActivity
public AdapterRallye(List<DataRallye> dadesrally) {
this.data = dadesrally;
}
// Inflate the layout when viewholder created
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.container_rallye, parent, false);
view.setOnClickListener(this);
return new MyViewHolder(view);
}
// Bind data
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// Get current position of item in recyclerview to bind data and assign values from list
DataRallye current = data.get(position);
holder.Rallye_Nom.setText(current.getRallyeNom());
holder.Rallye_Tipus.setText(current.getRallyeTipus());
holder.Rallye_DataI.setText(current.getRallyeDataI());
holder.Rallye_Provincia.setText(current.getRallyeProvincia());
holder.Rallye_Provincia.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
// load image into imageview using glide
Glide.with(context).load("http://rallyecat.esy.es/fotos/" + current.getRallyeFoto())
.placeholder(R.drawable.rallyecatlogo)
.error(R.drawable.rallyecatlogo)
.into(holder.Rallye_Foto);
}
public void setOnClickListener(View.OnClickListener listener) {
this.listener = listener;
}
#Override
public void onClick(View view) {
if (listener != null)
listener.onClick(view);
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
}
FRAGMENT CODE:
public class FragmentRally extends Fragment {
public FragmentRally() {
// Required empty public constructor
}
private List<DataRallye> llistarallyes = new ArrayList<>();
private RecyclerView recyclerView;
private AdapterRallye mAdapter;
private Intent intent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment_rally, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.llistarallyes);
mAdapter = new AdapterRallye(llistarallyes);
recyclerView.setAdapter(mAdapter);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
new AsyncFetch().execute();
mAdapter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(getActivity(), ActivitatDetalls.class);
intent.putExtra("nombarra", llistarallyes.get(recyclerView.getChildAdapterPosition(view)).getRallyeNom());
startActivity(intent);
}
});
return rootView;
}
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tCarregant...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json llistarallyes
url = new URL("http://www.rallyecat.esy.es/Obtenir_events.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive llistarallyes from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve llistarallyes from json file
//conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read llistarallyes sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line + "\n");
}
// Pass llistarallyes to onPostExecute method
return (result.toString());
} else {
Toast.makeText(getActivity(), "No hi ha connexió a internet.",
Toast.LENGTH_LONG).show();
return ("No hi ha connexió a internet.");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract llistarallyes from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataRallye dadesrallye = new DataRallye();
dadesrallye.setRallyeNom(json_data.getString("nom"));
dadesrallye.setRallyeTipus(json_data.getString("tipus"));
dadesrallye.setRallyeDataI(json_data.getString("datai"));
dadesrallye.setRallyeProvincia(json_data.getString("provincia"));
dadesrallye.setRallyeFoto(json_data.getString("foto"));
llistarallyes.add(dadesrallye);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.fragment_fragment_rally, parent, false));
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(v.getContext(), ActivitatDetalls.class);
context.startActivity(intent);
}
});
}
}
}
I've seen other StackOverflow posts where the problem is already solved, but I've been trying alot of the solutions the user said, but none is working...
Thanks!
Try to call mAdapter.notifyDataSetChanged(); in onPostExecute() method.
You need to notify your adapter after you made changes.

How can I display specific CSV content to the clicked list item?

I'm trying to display specific CSV content to the clicked list item but with my current code, I can only display the entire CSV file. Here for example, when I click on level 2, all the CVS list is displayed, but what I'm trying to do here is to show only the level 2 elements of the CSV.
This is my first view :
This is the view I get when level 2 is clicked :
But here, the level 1 CSV elements are also display, how can I only display the level 2 elements ? And when the "Level 1" is clicked, how to display only the level 1 elements ? etc...
MainActivity.java
public class MainActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
// R.array.levels is in list_levels.xml
String[] levels = getResources().getStringArray(R.array.levels);
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label_level, levels));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String list = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("list", list);
startActivity(i);
}
});
}
}
Here is my file CSVFile.java
public class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream){
this.inputStream = inputStream;
}
public List<String[]> read(){
List<String[]> resultList = new ArrayList<String[]>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
My ItemArrayAdapter.java class
public class ItemArrayAdapter extends ArrayAdapter<String[]> {
private List<String[]> stimuliList = new ArrayList<String[]>();
static class ItemViewHolder {
TextView level_number;
TextView stimuli_name;
}
public ItemArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public void add(String[] object) {
stimuliList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.stimuliList.size();
}
#Override
public String[] getItem(int index) {
return this.stimuliList.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ItemViewHolder viewHolder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.single_list_item_view, parent, false);
viewHolder = new ItemViewHolder();
viewHolder.level_number = (TextView) row.findViewById(R.id.level_number);
viewHolder.stimuli_name = (TextView) row.findViewById(R.id.stimuli_name);
row.setTag(viewHolder);
} else {
viewHolder = (ItemViewHolder)row.getTag();
}
String[] stat = getItem(position);
viewHolder.level_number.setText(stat[0]);
viewHolder.stimuli_name.setText(stat[1]);
return row;
}
}
SingleListItem.java
public class SingleListItem extends Activity{
private ListView listView;
private ItemArrayAdapter itemArrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtList = (TextView) findViewById(R.id.list_label);
Intent i = getIntent();
// getting attached intent data
String list = i.getStringExtra("list");
// displaying selected list name
txtList.setText(list);
listView = (ListView) findViewById(R.id.stimuli_list);
itemArrayAdapter = new ItemArrayAdapter(getApplicationContext(), R.layout.single_list_item_view);
Parcelable state = listView.onSaveInstanceState();
listView.setAdapter(itemArrayAdapter);
listView.onRestoreInstanceState(state);
InputStream inputStream = getResources().openRawResource(R.raw.stimulis);
CSVFile csvFile = new CSVFile(inputStream);
List<String[]> stimuliList = csvFile.read();
for(String[] stimuliData:stimuliList ) {
itemArrayAdapter.add(stimuliData );
}
}
}
And finally, a quick view of my CSV file, stimulis.csv
level 1,feu
level 1,fête
level 2,blanc
level 2,blague
...
Is this possible ?
I am afraid it isn't possible.

OnItemClickListener getting data from model

I am fairly new to Android development and I am trying to build a ListView which get data from web service using gson. I have a model class, a list class, an adapter class and the activity class.
The list works fine and it got the data, and now I want to integrate the OnItemClickListener to it and pass the data to the 2nd activity. And I'd like to get the item id (DistrictId) and pass it to the next Activity(listView) instead of the row id. It would be great if someone could show me the light... as the documentation is not as clear to understand and because I am new.
Below is my code.
The model class
package com.sample.myapp;
public class DistrictModel {
private String id;
private String districtName;
public String getDistrictId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDistrictName(){
return districtName;
}
public void setDistrictEN(String districtName){
this.districtName = districtName;
}
}
The List class
public class DistrictList {
private List<DistrictModel> districts;
public List<DistrictModel> getDistricts(){
return districts;
}
public void setDistrictList(List<DistrictModel> districts){
this.districts = districts;
}
}
The Adapter class
public class DistrictAdapter extends ArrayAdapter<DistrictModel>{
int resource;
String response;
Context context;
private LayoutInflater dInflater;
public DistrictAdapter(Context context, int resource, List<DistrictModel> objects) {
super(context, resource, objects);
this.resource = resource;
dInflater = LayoutInflater.from(context);
}
static class ViewHolder {
TextView title;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
//Get the current location object
DistrictModel lm = (DistrictModel) getItem(position);
//Inflate the view
if(convertView==null)
{
convertView = dInflater.inflate(R.layout.item_district, null);
holder = new ViewHolder();
holder.title = (TextView) convertView
.findViewById(R.id.district_name);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(lm.getDistrictName());
return convertView;
}
}
The activity class
public class DistrictListActivity extends Activity{
LocationManager lm;
ArrayList<DistrictModel> districtArray = null;
DistrictAdapter districtAdapter;
DistrictList list;
ListView lv;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.districtlist_layout);
lv = (ListView) findViewById(R.id.list_district);
districtArray = new ArrayList<DistrictModel>();
districtAdapter = new DistrictAdapter(DistrictListActivity.this, R.layout.item_district, districtArray);
lv.setTextFilterEnabled(true);
lv.setAdapter(districtAdapter);
try {
new DistrictSync().execute("http://aws.something.com/service");
} catch(Exception e) {}
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(DistrictListActivity.this);
adb.setTitle("LVSelectedItemExample");
adb.setMessage("Selected Item is = "+(lv.getItemIdAtPosition(position)));
adb.setPositiveButton("Ok", null);
adb.show();
}
}); **//i'd like to get the DistrictId from the json data.**
}
private class DistrictSync extends AsyncTask<String, Integer, DistrictList> {
protected DistrictList doInBackground(String... urls) {
DistrictList list = null;
int count = urls.length;
for (int i = 0; i < count; i++) {
try {
// ntar diganti service
RestClient client = new RestClient(urls[i]);
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String json = client.getResponse();
list = new Gson().fromJson(json, DistrictList.class);
//
} catch(Exception e) {}
}
return list;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(DistrictList dislist) {
for(DistrictModel lm : dislist.getDistricts())
{
districtArray.add(lm);
}
districtAdapter.notifyDataSetChanged();
}
}
}
For testing purpose, now I click the row it will show me the row id, so I know the onclick listener works, but I just want it to grab me the DistrictId so I can use it to pass to the next activity.
Thank you so much.
(out of my head) Try this:
((DistrictModel)lv.getAdapter().getItem(position)).getDistrictId();
Generally when you want to pass data from one Activity to another, you just place it into the Intent that you use to create the new Activity.
For example (and here are some additional examples):
Intent i = new Intent(context, MyNewActivity.class);
i.putExtra("MyCurrentHealth", mCurrentHealth);
context.startActivity(i);
To retrieve the data do this:
Bundle extras = getIntent().getExtras();
if (extra != null) {
... // Do stuff with extras
}

Categories

Resources