How to swap spinner value while clicking image - java

Im very new for android, I want swap spinner value when user click the image. Please anyone help me.
Here my code:
public class SearchFragment extends Fragment {
ImageView swap;
Spinner source, destination;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.search, container,
false);
swap = (ImageView)getActivity().findViewById(R.id.imgSwap);
source = (Spinner)getActivity().findViewById(R.id.from);
destination = (Spinner)getActivity().findViewById(R.id.to);
swap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
-----> \\Here want to code
}
});
return view;
}
}

If you want to swap the contents of two Spinners you can use this
ArrayList<String> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>();
list1.add("A");
list1.add("B");
list1.add("C");
list2.add("1");
list2.add("2");
list2.add("3");
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,list1);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,list2);
spinner1.setAdapter(adapter1);
spinner2.setAdapter(adapter2);
yourImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayAdapter<String> a1 = (ArrayAdapter) spinner1.getAdapter();
ArrayAdapter<String> a2 = (ArrayAdapter) spinner2.getAdapter();
spinner1.setAdapter(a2);
spinner2.setAdapter(a1);
}
});
Or if you just want to swap the selected values across the spinner you can use this in your button click
yourImagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position1 = spinner1.getSelectedItemPosition();
int position2 = spinner2.getSelectedItemPosition();
String item1 = list1.get(position1);
String item2 = list2.get(position2);
list1.remove(position1);
list1.add(position1, item2);
list2.remove(position2);
list2.add(position2, item1);
adapter1.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
}
});

Related

How to sort recycler view SQLite content

I have a a view where a bunch of my Sqlite data is displayed. I recently added a column to my database called location_position. I have added a button to my relative layout so that when its clicked I want the data inside to be sorted in ascending format. I have tried following a few examples online but with the way my app is setup im struggling tom get it to work.
I have a routeView.java class and a routeAdapter
I would really apreciate if someone can show me how to have the content sorted when the button is clicked, or any resources with similar solutions
public class RouteView extends AppCompatActivity {
RecyclerView recyclerView;
routeAdapter routeAdapter;
ArrayList<String> location_id, location_name, location_county, location_description, location_route, location_position;
MyDatabaseHelper myDB;
Button createPDFButton, btnNorth, southBtn;
Context mContext = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_view);
Button southBtn = findViewById(R.id.button_south);
southBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Collections.sort(ArrayList);
}
});
// btnRemove = findViewById(R.id.btnRemove);
recyclerView = findViewById(R.id.recyclerView);
myDB = new MyDatabaseHelper(this);
createPDFButton = findViewById(R.id.createPDFButton);
location_id = new ArrayList<>();
location_name = new ArrayList<>();
location_county = new ArrayList<>();
location_description = new ArrayList<>();
location_route = new ArrayList<>();
location_position = new ArrayList<>();
Cursor cursor = myDB.readAllData();
createPDFButton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View v) {
if (UserActivity.checkAppPermission(RouteView.this, "android.permission.WRITE_EXTERNAL_STORAGE", 1)){
generatePDF(recyclerView);
}
}
});
while (cursor.moveToNext()){
if(cursor.getString(4).equals("1")) {
location_id.add(cursor.getString(0));
location_name.add(cursor.getString(1));
location_county.add(cursor.getString(2));
location_description.add(cursor.getString(3));
location_route.add(cursor.getString(4));
location_position.add(cursor.getString(8));
}
}
routeAdapter = new routeAdapter(this, this, location_id, location_name, location_county, location_description, location_route, location_position);
recyclerView.setAdapter(routeAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
and this is the route adapter class
public class routeAdapter extends RecyclerView.Adapter<routeAdapter.MyViewHolder> {
//private final ClickListener listener;
private Context context;
MyDatabaseHelper myDB;
Activity activity;
private ArrayList location_id, location_name, location_county, location_description, location_position, location_route, location_image_url;
Button btnRemove;
String id, name, county, description;
routeAdapter(Activity activity, Context context, ArrayList location_id, ArrayList location_name, ArrayList location_county,
ArrayList location_description, ArrayList location_route, ArrayList location_position){
this.activity = activity;
this.context = context;
this.location_id = location_id;
this.location_name = location_name;
this.location_county = location_county;
this.location_description = location_description;
this.location_position = location_position;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.route_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
holder.location_id_txt.setText(String.valueOf(location_id.get(position)));
holder.location_name_txt.setText(String.valueOf(location_name.get(position)));
holder.location_county_txt.setText(String.valueOf(location_county.get(position)));
holder.location_description_txt.setText(String.valueOf(location_description.get(position)));
holder.mainLayout2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, RouteView.class);
intent.putExtra("id", String.valueOf(location_id.get(position)));
intent.putExtra("name", String.valueOf(location_name.get(position)));
intent.putExtra("county", String.valueOf(location_county.get(position)));
intent.putExtra("description",String.valueOf(location_description.get(position)));
activity.startActivityForResult(intent, 2);
}
});
}
#Override
public int getItemCount() { return location_id.size(); }
class MyViewHolder extends RecyclerView.ViewHolder {
TextView location_id_txt, location_name_txt, location_county_txt, location_description_txt, added_to_route_txt, location_image_url;
LinearLayout mainLayout2;
Button btnRemove;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
location_id_txt = itemView.findViewById(R.id.location_id_txt);
location_name_txt = itemView.findViewById(R.id.location_name_txt);
location_county_txt = itemView.findViewById(R.id.location_county_txt);
location_description_txt = itemView.findViewById(R.id.location_description_txt);
mainLayout2 = itemView.findViewById(R.id.mainLayout2);
}
}
}
This is the basic concept:
On clicking a button or whatever to sort the things in a specific order, you sort the ArrayList that contains the values reflected in the RecyclerView. Then you update/ recreate the RecyclerView to register the changes.

How to save to online database from string results of custom dialog in android

I have a program that gets string from a custom dialog box to a listview in an activity and I want the strings I got to be saved to database the same time they are being passed to the textviews
Code:
public class orderlist extends AppCompatActivity {
List<String> qty = new ArrayList<>();
List<String> qtytype = new ArrayList<>();
List<String> products = new ArrayList<>();
List<String> store = new ArrayList<>();
ListView orderlist;
FloatingActionButton btnOrder;
MydAdapter adapter;
#Override
public void onBackPressed() {
Intent myIntent = new Intent(orderlist.this, Main2Activity.class);
orderlist.this.startActivity(myIntent);
}
String saveProduct, saveQty, saveStore, saveQtyType;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_orderpage);
orderlist = (ListView) findViewById(R.id.orderlistview);
btnOrder = (FloatingActionButton) findViewById(R.id.order);
String saveProduct, saveQty, saveStore, saveQtyType;
btnOrder.setOnClickListener(new View.OnClickListener() {
#SuppressLint("CutPasteId")
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(orderlist.this);
LayoutInflater inflater = (LayoutInflater) orderlist.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.prompts, null, false);
builder.setView(view);
builder.setCancelable(false);
RequestHandler rh = new RequestHandler();
final EditText txtproductname, txtstore, txtquantity;
final Spinner txtqtytype;
txtproductname = (EditText) view.findViewById(R.id.TxtProductName);
txtstore = (EditText) view.findViewById(R.id.TxtStoreName);
txtquantity = (EditText) view.findViewById(R.id.TxtQuantity);
List<String> arrayList = new ArrayList<String>();
arrayList.add("pieces");
arrayList.add("pesos");
arrayList.add("kilos");
arrayList.add("ml");
arrayList.add("grams");
arrayList.add("bundle");
ArrayAdapter<String> spinneradapter = new ArrayAdapter<String>(orderlist.this, android.R.layout.simple_spinner_item, arrayList);
spinneradapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
txtqtytype = (Spinner) view.findViewById(R.id.spinnerQuantityType);
txtqtytype.setAdapter(spinneradapter);
txtqtytype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String value = parent.getItemAtPosition(position).toString();
//Toast.makeText(parent.getContext(), "Selected: " + value, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView <?> parent) {
}
});
builder.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
qty.add(txtquantity.getText().toString());
qtytype.add(txtqtytype.getSelectedItem().toString());
products.add(txtproductname.getText().toString());
store.add(txtstore.getText().toString());
Toast.makeText(orderlist.this, txtproductname.getText().toString(), Toast.LENGTH_LONG).show();
adapter = new MydAdapter(orderlist.this, qty, qtytype, products, store);
orderlist.setAdapter(adapter);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
});
}
class MydAdapter extends ArrayAdapter{
List<String> adapter_products;
List<String> adapter_qty;
List<String> adapter_store;
List<String> adapter_qtytype;
public MydAdapter(Context context, List<String> qty, List<String> qtytype, List<String> products, List<String> store) {
super(context, R.layout.activity_orderlist, R.id.quantity, qty);
this.adapter_qty = qty;
this.adapter_qtytype = qtytype;
this.adapter_products = products;
this.adapter_store = store;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//Inflating layout
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#SuppressLint("ViewHolder") View row = inflater.inflate(R.layout.activity_orderlist, parent, false);
TextView txtProduct, txtQty, txtStore, txtQtyType;
Button btnCancel;
txtProduct = (TextView) row.findViewById(R.id.productname);
txtQty = (TextView) row.findViewById(R.id.quantity);
txtStore = (TextView) row.findViewById(R.id.storename);
txtQtyType = (TextView) row.findViewById(R.id.quantitytype);
btnCancel = (Button) row.findViewById(R.id.btnCancel);
txtQty.setText(adapter_qty.get(position));
txtQtyType.setText(adapter_qtytype.get(position));
txtProduct.setText(adapter_products.get(position));
txtStore.setText(adapter_store.get(position));
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
qty.remove(position);
qtytype.remove(position);
products.remove(position);
store.remove(position);
adapter= new MydAdapter(orderlist.this, qty, qtytype, products, store);
orderlist.setAdapter(adapter);
}
});
return row;
}
}
}
So this is where I need to get the data from. I've tried using Async but I cant seem to get it working
builder.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
qty.add(txtquantity.getText().toString());
qtytype.add(txtqtytype.getSelectedItem().toString());
products.add(txtproductname.getText().toString());
store.add(txtstore.getText().toString());
Toast.makeText(orderlist.this, txtproductname.getText().toString(), Toast.LENGTH_LONG).show();
adapter = new MydAdapter(orderlist.this, qty, qtytype, products, store);
orderlist.setAdapter(adapter);
Do you guys know a method how i can do this?

How update ListView from my Custom Adapter

I just wanna update my ListView, but I cant. I dont know what. What did I do Wrong? I guess that the Adapter that I created is missing something to return the real adapter that I can handle.
Home.java (MainActivity)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
MenuItem item = navigation.getMenu().findItem(R.id.navigation_home);
item.setCheckable(true);
item.setChecked(true);
BoxStore boxStore = AppMain.getBoxStore();
equipamentoBox = boxStore.boxFor(Equipamento.class);
lancamentoBox = boxStore.boxFor(Lancamento.class);
loadObjects();
////FOCUS HERE/////------------------------------
List<Equipamento> equipamentos = new ArrayList<>();
EquipamentoAdapter adapter;adapter = new EquipamentoAdapter(this, equipamentos);
listEquipamentos = (ListView) findViewById(R.id.listEquipamentos);
listEquipamentos.setAdapter(adapter);
registerForContextMenu(listEquipamentos);
}
EquipamentoAdapter.JAVA
public class EquipamentoAdapter extends ArrayAdapter<Equipamento> {
private final Activity context;
private final List<String> idArray = new ArrayList<String>();
private final List<String> qtdArray = new ArrayList<String>();
private final ArrayList<String> nomeArray = new ArrayList<String>();
private List<Equipamento> equipamentos = new ArrayList<>();
public EquipamentoAdapter(Activity context, List<Equipamento> equipamentos) {
super(context, R.layout.listview_row, equipamentos);
for (Iterator iterator = equipamentos.iterator(); iterator.hasNext(); ) {
Equipamento equipamento = (Equipamento) iterator.next();
this.idArray.add(Integer.toString((int)equipamento.getId()));
this.qtdArray.add(Integer.toString(equipamento.getQuantidade()));
this.nomeArray.add(equipamento.getNome());
}
this.context = context;
this.equipamentos = equipamentos;
}
public void callDialogTransaction(Equipamento equipamento) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View mView = inflater.inflate(R.layout.dialog_lancamento,null);
TextView title = (TextView) mView.findViewById(R.id.txtTitle);
final EditText quantidade = (EditText) mView.findViewById(R.id.edtQtd);
final EditText Observacao = (EditText) mView.findViewById(R.id.edtObs);
Button addTransaction = (Button) mView.findViewById(R.id.btnAddTranD);
title.setText(equipamento.getNome());
addTransaction.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(!quantidade.getText().toString().isEmpty()){
Toast.makeText(getContext(), "Success!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Erro. Fill everything.", Toast.LENGTH_SHORT).show();
}
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.listview_row,null,true);
//this code gets references to objects in the listview_row.xml file
TextView txtQtd,txtName;
txtQtd = (TextView) rowView.findViewById(R.id.txtQtd);
txtName = (TextView) rowView.findViewById(R.id.txtName);
final ImageButton btnAddTransaction = (ImageButton) rowView.findViewById(R.id.btnAddTransaction);
//this code sets the values of the objects to values from the arrays
txtQtd.setText(qtdArray.get(position));
txtName.setText(nomeArray.get(position));
btnAddTransaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Equipamento equipamento = equipamentos.get(position);
callDialogTransaction(equipamento);
Animation animation = new AlphaAnimation(1.0f,0.8f);
animation.setDuration(100);
btnAddTransaction.startAnimation(animation);
}
});
return rowView;
}
}
I read that I could try to use adapter.notifyDataSetChanged(); but its not working. Also I tryed to add this on EquipamentoAdapter.java and call from my MainActivity when I needed to refresh, but it didn work as well. I dont know why. Everything seems right.
public void refreshData(){
this.equipamentos.clear();
for(Equipamento equipamento : equipamentoBox.getAll()){
this.equipamentos.add(equipamento);
}
notifyDataSetChanged();
}
I'll suggest the following changes:
Reference the equipamento object directly from List inside the getView the so that the getView function becomes
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.listview_row,null,true);
//this code gets references to objects in the listview_row.xml file
TextView txtQtd,txtName;
txtQtd = (TextView) rowView.findViewById(R.id.txtQtd);
txtName = (TextView) rowView.findViewById(R.id.txtName);
final ImageButton btnAddTransaction = (ImageButton) rowView.findViewById(R.id.btnAddTransaction);
//this code sets the values of the objects to values from the arrays
Equipamento equipamento = equipamentos.get(position);
txtQtd.setText(String.valueOf(equipamento.getId()));
txtName.setText(String.valueOf(equipamento.getQuantidade()));
btnAddTransaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Equipamento equipamento = equipamentos.get(position);
callDialogTransaction(equipamento);
Animation animation = new AlphaAnimation(1.0f,0.8f);
animation.setDuration(100);
btnAddTransaction.startAnimation(animation);
}
});
return rowView;
}
Set the Items count with the getCount method
public int getCount(){
return equipamentos.size();
}
with these, calling notifyDataSetChanged(); should update the list without need to reinitialize the adapter.
One thing that you can do is reinflaiting the adapter, try this
public void refreshData(){
this.equipamentos.clear();
for(Equipamento equipamento : equipamentoBox.getAll()){
this.equipamentos.add(equipamento);
}
EquipamentoAdapter adapter;adapter = new EquipamentoAdapter(this, equipamentos);
listEquipamentos.setAdapter(adapter);
}
GUYS, I've noticed that if I use:
equipamentos.clear(); //Clear List
for(Equipamento equipamento : equipamentoBox.getAll()){
equipamentos.add(equipamento); //Populate List
}
adapter = null;
adapter = new EquipamentoAdapter((Activity) Home.this, equipamentos);
listEquipamentos.setAdapter(adapter);
adapter.notifyDataSetChanged();
Its gonna work. But this seems VERY wrong in terms of performance. My application is small but I dont want to make bad practices.
Create a method to replace the data and check the size of your adapter after you add new elements.
Add something like this to the adapter:
public void replaceData(List<Equipamento> equipamentos) {
this.equipamentos = equipamentos;
notifyDataSetChanged();
}
#Override
public int getCount() {
return equipamentos.size();
}
Then check the size from the Activity:
adapter.getCount();
As your following logic is in constructor of adapter-
enter code here
for (Iterator iterator = equipamentos.iterator(); iterator.hasNext(); ) {
Equipamento equipamento = (Equipamento) iterator.next();
this.idArray.add(Integer.toString((int)equipamento.getId()));
this.qtdArray.add(Integer.toString(equipamento.getQuantidade()));
this.nomeArray.add(equipamento.getNome());
}
after notifyDataSetChange, adapter is not called so you can do 2 things -
1) Initialize the Adapter as #Gastón Saillén answered.
2) Put that in some method and call it before you call notifydatasetchange.

Android Spinner value does not change in new Activity

I use a spinner in my App to open the same Activity but with different values to download Json files and show them. The first problem was, that the spinner don´t work, when i don´t add a spinner value at the 0 position and query it with if-statement (if(position >0)) in the onItemSelected method before open a new activity. Its a solution but not a very good.
The next problem is, that the value of the spinner shows every time the 0 position of the spinner list. Its same when i make a Array to fill the spinner or different Strings. Open the same Activity with different json files works fine but the spinner is all the time on position 0 value.
public class FragmentResult extends Fragment implements
GestureOverlayView.OnGesturePerformedListener, AdapterView.OnItemSelectedListener {
private ArrayList<ResultModel> arrayListResult = new ArrayList<>();
public static int dayOfMatch = 34;
private GestureLibrary gestureLibrary;
Spinner spinnerDay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//matchDayCheck();
ServerResult serverResult = new ServerResult(getActivity().getApplicationContext(),
"https://www.dein-weg-in-die-cloud.de/tomcat7/RestSoccer/fussball/spieltag/" + dayOfMatch);
serverResult.execute();
String downResult = null;
try {
downResult = serverResult.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
JsonParser jsonParser = new JsonParser();
arrayListResult = jsonParser.parseJSONResult(downResult);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
GestureOverlayView gestureOverlayView = new GestureOverlayView(getActivity());
View view = inflater.inflate(R.layout.layout_result, container, false);
ListView result_list = (ListView)view.findViewById(R.id.result_list);
AdapterResult adapterResult = new AdapterResult(getActivity().getApplicationContext(), arrayListResult);
result_list.setAdapter(adapterResult);
gestureOverlayView.addView(view);
gestureOverlayView.setFadeEnabled(false);
gestureOverlayView.addOnGesturePerformedListener(this);
gestureOverlayView.setGestureColor(Color.TRANSPARENT);
gestureOverlayView.setUncertainGestureColor(Color.TRANSPARENT);
gestureOverlayView.setFadeOffset(0);
gestureOverlayView.setHapticFeedbackEnabled(true);
gestureLibrary = GestureLibraries.fromRawResource(getActivity().getApplicationContext(), R.raw.gestures); //!!
if (!gestureLibrary.load()) {
getActivity().finish();
}
// Spinner element
Spinner spinnerYear = (Spinner)view.findViewById(R.id.spinnerResultYear);
spinnerDay = (Spinner)view.findViewById(R.id.spinnerResultDay);
// Spinner click listener
spinnerYear.setOnItemSelectedListener(this);
spinnerDay.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> spinnerListYear = new ArrayList<String>();
spinnerListYear.add("2013/2014");
List<String> spinnerListDay = new ArrayList<String>();
spinnerListDay.add("");
for(int i = 1; i<=34; i++){
spinnerListDay.add(i + ".Spieltag");
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerYearAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_item, spinnerListYear);
ArrayAdapter<String> spinnerDayAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_item, spinnerListDay);
// Drop down layout style - list view with radio button
spinnerYearAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerYear.setAdapter(spinnerYearAdapter);
spinnerDay.setAdapter(spinnerDayAdapter);
/*result_list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ResultModel resultModel = (ResultModel) parent.getItemAtPosition(position);
int matchId = resultModel.getMatchId();
Intent matchIntent = new Intent(getActivity(), MatchActivity.class);
matchIntent.putExtra("MatchId", matchId);
matchIntent.putExtra("Matchday", dayOfMatch);
startActivity(matchIntent);
}
});*/
return gestureOverlayView;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
if(position >0) {
final Intent intent;
intent = new Intent(getActivity().getApplicationContext(), ResultActivity.class);
dayOfMatch = position;
intent.putExtra("dayOfMatch", dayOfMatch);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
.
.
.
}

Passing RecyclerView CardView Clicked Item Data To Activity

I have a question about passing clicked cardview data to activity, and here the full story :
I have an Activity called "Details", which contains 2 TextViews in it's layout, Title & Description .
I have setup a fragment ( tab_1 ) which contain the recyclerview codes and the the items data, each item of those contain : title & description .
What i want :
When the user click the item, it will open the Details Activity, and change Details layout title, with clicked item title, and the same for description .
I've manged to create the other activity as an example, and made intent to start it, plus adding "addOnTouchlistener" thanks to Stackoverflow, i've found the way to make it .
So, how to make this alive? I've tried many ways of the available answers on Stackoverflow, but all of them not working, or not related to my request .
Here are my files :
itemsdata.java :
public class itemsdata {
int CatPic;
String title;
String Descr;
int Exapnd;
int expand_no;
tab_1.java ( fragment )
public class tab_1 extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerView mRecyclerView;
public RecyclingViewAdapter adapter;
private Activity context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.tab_1, container, false);
mRecyclerView = (RecyclerView)layout.findViewById(R.id.recycler_view);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener
(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent i = new Intent(view.getContext(), DetailsActivity.class);
view.getContext().startActivity(i);
}
}));
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new RecyclingViewAdapter(getActivity(),Listed());
mRecyclerView.setAdapter(adapter);
return layout;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String query) {
final List<itemsdata> filteredModelList = filter(Listed(), query);
adapter.animateTo(filteredModelList);
mRecyclerView.scrollToPosition(0);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
private List<itemsdata> filter(List<itemsdata> models, String query) {
query = query.toLowerCase();
final List<itemsdata> filteredModelList = new ArrayList<>();
for (itemsdata model : models) {
final String text = model.title.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
public List<itemsdata> Listed()
{
//Titles Strings
String sys_title1 = getString(R.string.system_item_title_1);
String sys_title2 = getString(R.string.system_item_title_2);
String sys_title3 = getString(R.string.system_item_title_3);
//Description Strings
String sys_descr1 = getString(R.string.system_item_desc_1);
String sys_descr2 = getString(R.string.system_item_desc_2);
String sys_descr3 = getString(R.string.system_item_desc_3);
//Adding New Cards
List<itemsdata> data = new ArrayList<>();
//Categories Icons New Items ** Make It The Same
int[] icons = {
R.drawable.facebook_icon ,
R.drawable.twitter_icon ,
R.drawable.twitter_icon
};
//Expand Button New Items
int[] expandbutton = {
R.drawable.expanded ,
R.drawable.expanded ,
R.drawable.expanded
};
//UnExpand Button New Items
int[] unexpandbutton = {
R.drawable.ca_expand ,
R.drawable.ca_expand ,
R.drawable.ca_expand
};
//Titles New Items
String[] titles = {
sys_title1 ,
sys_title2 ,
sys_title3
};
//Description New Items
String[] Description = {
sys_descr1 ,
sys_descr2 ,
sys_descr3
};
for(int i = 0;i<titles.length && i < icons.length && i < Description.length && i < unexpandbutton.length && i < expandbutton.length ; i++)
{
itemsdata current = new itemsdata();
current.CatPic = icons[i];
current.title = titles[i];
current.Descr = Description[i];
current.expand_no = unexpandbutton[i];
current.Exapnd = expandbutton[i];
data.add(current);
}
return data;
}
}
Details Activity :
public class DetailsActivity extends AppCompatActivity{
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
title = (TextView)findViewById(R.id.details_title);
}
EDIT : I've made it, i have added a button which open the fragment, and passed the data, in the Adapter, but i want it via tab_1.java, not the Adapter, i mean i want to click on the item to open the fragment, not on a button, here a snap from my Adapter code ( i've added it in OnBindViewHolder )
I've setup a OnClick and implemented the Vew.setOnClick ..etc, but when i click the item, nothing happen.
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(),DetailsActivity.class);
v.getContext().startActivity(i);
}
});
//Referencing Data
final itemsdata currentobject = mdata.get(position);
//Referencing Items
holder.ProbTitle.setText(currentobject.title);
holder.ProbDescr.setText(currentobject.Descr);
holder.CategoryPic.setImageResource(currentobject.CatPic);
holder.ExpandButton.setImageResource(currentobject.Exapnd);
holder.ExpandNoButton.setImageResource(currentobject.expand_no);
//What Happen When You Click Expand Button .
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",holder.ProbTitle.getText().toString());
v.getContext().startActivity(i);
}
}
);
public static class MyRecycleViewHolder extends RecyclerView.ViewHolder
{
SwipeLayout swipeLayout;
//Defining Items .
TextView ProbTitle;
ImageButton ExpandButton;
TextView ProbDescr;
ImageButton ExpandNoButton;
ImageView CategoryPic;
/*
TextView Card_Star;
TextView Card_UnStar;
*/
TextView Card_Share;
//Referencing Resources
public MyRecycleViewHolder(final View itemView) {
super(itemView);
ProbTitle = (TextView) itemView.findViewById(R.id.prob_title);
CategoryPic = (ImageView) itemView.findViewById(R.id.cat_pic);
ProbDescr = (TextView) itemView.findViewById(R.id.prob_descr);
ExpandButton = (ImageButton) itemView.findViewById(R.id.expand_button);
ExpandNoButton = (ImageButton) itemView.findViewById(R.id.expand_no_button);
/*
Card_Star = (TextView) itemView.findViewById(R.id.card_star);
Card_UnStar = (TextView) itemView.findViewById(R.id.card_unstar);
*/
Card_Share = (TextView) itemView.findViewById(R.id.card_share);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
}
create an Interface inside your adapter containing methods. And while implementing your Adapter, those methods will be implemented in your activity and you can perform whatever action you want.
public class Adapter extends RecyclerView.Adapter<MyRecycleViewHolder> {
public interface Callbacks {
public void onButtonClicked(String titleKey);
}
private Callbacks mCallbacks;
public Adapter() {
}
#Override
public MyRecycleViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_details, null);
return new MyRecycleViewHolder(v);
}
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, final int i) {
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallbacks != null) {
mCallbacks.onButtonClicked(holder.ProbTitle.getText().toString());
}
}
});
}
#Override
public int getItemCount() {
return;
}
public void setCallbacks(Callbacks callbacks) {
this.mCallbacks = callbacks;
}
}
you may try do this on your onItemClick()
Intent i = new Intent(view.getContext(), DetailsActivity.class);
i.putExtra("title", yourTitle);
i.putExtra("description", yourDescription);
view.getContext().startActivity(i);
and when oncreate in your DetailActivity,do this
String title = getIntent().getStringExtra("title");
String description = getIntent().getStringExtra("description");
so you can pass title and description to DetailActivity
IMO, you implement setOnClickListener inside Adapter of RecyclerView. You can refer to my following sample code, then apply its logic to your code. Hope it helps!
public class MyRVAdapter extends RecyclerView.Adapter<MyRVAdapter.ViewHolder> {
Context mContext;
List<String> mStringList;
public MyRVAdapter(Context mContext, List<String> mStringList) {
this.mContext = mContext;
this.mStringList = mStringList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView1 = (TextView) v.findViewById(R.id.textView1);
TextView textView2 = (TextView) v.findViewById(R.id.textView2);
Bundle bundle = new Bundle();
bundle.putString("key1", textView1.getText().toString());
bundle.putString("key2", textView2.getText().toString());
passToAnotherActivity(bundle);
}
});
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// do something...
}
#Override
public int getItemCount() {
if (mStringList != null) {
return mStringList.size();
}
return 0;
}
private void passToAnotherActivity(Bundle bundle) {
if (mContext == null)
return;
if (mContext instanceof MainActivity) {
MainActivity activity = (MainActivity) mContext;
activity.passToAnotherActivity(bundle); // this method must be implemented inside `MainActivity`
}
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ViewHolder(View itemView) {
super(itemView);
// do something...
}
#Override
public void onClick(View v) {
}
}
}
First of all make your "itemsdata" object to implement Parcelable. You can check it here . In your onItemClick method you pass the object to your Details activity using intent.putExtra("key",listOfDataItems.get(position));
In your DetailsActivity you can get your custom object with getParcelable("key")
All above methods worked, but kinda long, so this one worked for me :
Cardview cardview;
cardView = (CardView)itemView.findViewById(R.id.cv);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent (view.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",ProbTitle.getText().toString());
i.putExtra("DescrKey",ProbDescr.getText().toString());
view.getContext().startActivity(i);
}
});
And in Details.java :
TextView title;
TextView Descr;
title = (TextView)findViewById(R.id.details_title);
Descr = (TextView)findViewById(R.id.details_descr);
String titleresult = result.getExtras().getString("TitleKey");
String Descrresult = result.getExtras().getString("DescrKey");
title.setText(titleresult);
Descr.setText(Descrresult);

Categories

Resources