I Want To Itemonclicklister in Fragment on Spinner - android-studio

This Is Main Fragment
Fragment:
private void getStock() {
dialog.show();
Retrofit retrofit = RetrofitClient.getRetrofitInstance();
apiInterface api = retrofit.create(apiInterface.class);
Call<List<Blocks>>call = api.getVaccineBlocks();
call.enqueue(new Callback<List<Blocks>>() {
#Override
public void onResponse(Call<List<Blocks>>call, Response<List<Blocks>> response) {
if (response.code() == 200) {
block = response.body();
spinnerada();
dialog.cancel();
}else{
dialog.cancel();
}
}
#Override
public void onFailure(Call<List<Blocks>> call, Throwable t) {
dialog.cancel();
}
});
}
private void spinnerada() {
String[] s = new String[block.size()];
for (int i = 0; i < block.size(); i++) {
s[i] = block.get(i).getBlockName();
final ArrayAdapter a = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_item, s);
a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spinner.setAdapter(a);
}
}
This Is Blocks Model
model:
package com.smmtn.book.models;
import java.io.Serializable;
public class Blocks implements Serializable {
public String id;
public String blockName;
public String blockSlug;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBlockName() {
return blockName;
}
public void setBlockName(String blockName) {
this.blockName = blockName;
}
public String getBlockSlug() {
return blockSlug;
}
public void setBlockSlug(String blockSlug) {
this.blockSlug = blockSlug;
}
}
here i need onitemclick with blockslug please any one can help, am new to android so i need some example.when on click i want take blockslug and load another method with that blockslug,like will get data from u "http://example.com/block/"+blockslug
i want to get blockslug from selected block
i hope guys i will get help
and sorry for my bad English,

First of all, you need to implement setOnItemSelectedListener. Refer to this https://stackoverflow.com/a/20151596/9346054
Once you selected the item, you can call them by making a new method. Example like below
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
final String itemSelected = parent.getItemAtPosition(pos).toString();
showBlockSlug(itemSelected);
}
And then, at the method showBlockSlug() , you can call Retrofit.
private void showBlockSlug(final String blockslug){
final String url = "http://example.com/block/"+ blockslug;
//Do your stuff...
}

Related

how to get all values added to recyclerview and send it to ion lib

so im trying to get recyclerview data list added and send it to ion lib when i use method below i only get one element as ill have to change string inside for() to String fav =null ouside of for() and log.d only shows the last result. i need get all so i can send to senddata() to ion lib
FavModelClass
private String fav;
private String user_id;
public FavModelClass(String fav, String user_id) {
this.fav = fav;
this.user_id = user_id;
}
public String getFav() {
return fav;
}
public void setFav(String fav) {
this.fav = fav;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
}
adapter
public class FavAdapter extends
RecyclerView.Adapter<FavAdapter .MyViewHolder> {
private List<FavModelClass> favModelClassList;
private Context beddingContext;
public FavAdapter (List<FavModelClass> favModelClassList, Context
beddingContext) {
this.favModelClassList= favModelClassList;
this.beddingContext = beddingContext;
}
#NonNull
#Override
public FavAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.amenitylayout,parent,false);
FavAdapter .MyViewHolder holder = new FavAdapter .MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull FavAdapter.MyViewHolder holder, int i) {
final FavModelClassdata = favModelClassList.get(i);
holder.ac_bedding_type.setText(data.getFav()+" "+"MAX:"+data.getUser_id());
holder.delete_entry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeAt(holder.getAdapterPosition());
}
});
}
public void removeAt(int position) {
favModelClassList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, favModelClassList.size());
}
#Override
public int getItemCount() {
return favModelClassList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView ac_bedding_type;
private ImageButton delete_entry;
public MyViewHolder(#NonNull View v) {
super(v);
ac_bedding_type = v.findViewById(R.id.ac_amenity_name);
delete_entry = v.findViewById(R.id.delete_amenity_entry);
}
}
}
Main activity
fav_recycler = findViewById(R.id.fave_recycler);
GridLayoutManager layoutManager1 = new GridLayoutManager(getApplicationContext(), 2,GridLayoutManager.VERTICAL, false);
fav_recycler.setHasFixedSize(true);
fav_recycler.setLayoutManager(layoutManager1);
favModelClassList= new ArrayList<>();
addfavamenity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
favModelClassList.add(new FavModelClass(
amenityET.getText().toString(),
user_idET.getText().toString()
));
amenityET.setText("");
user_idET.setText("");
FavAdapter adapter = new FavAdapter (favModelClassList, getApplicationContext());
adapter.notifyDataSetChanged();
fav_recycler.setAdapter(adapter);
for (int i = 0; i < favModelClassList.size(); i++) {
final FavModelClassList data = favModelClassList.get(i);
final String fav= data.getFav();
final String user_id = data.getUser_id();
Log.d(TAG, "onClick: "+ fav);
}
}
});
ArrayList d = new ArrayList();
for (int i = 0; i < favModelClassList.size(); i++) {
final FavModelClassList data = favModelClassList.get(i);
d.add(data.getFav());
}
Log.d(TAG, "onClick: " + d);

Trouble with logic flow for filtering search method on CS50 Pokedex

The app compiles fine but initially it shows nothing in the list. When I use the search bar, it doesn't display my filtered information and when I get rid of search, the entire list is finally display. Any help would be really appreciated, this is my first time ever coding in Java.
Here is my adapter code.
public class PokedexAdapter extends RecyclerView.Adapter<PokedexAdapter.PokedexViewHolder> implements Filterable {
public static class PokedexViewHolder extends RecyclerView.ViewHolder {
public LinearLayout containerView;
public TextView textView;
PokedexViewHolder(View view) {
super(view);
containerView = view.findViewById(R.id.pokedex_row);
textView = view.findViewById(R.id.pokedex_row_text_view);
containerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pokemon current = (Pokemon) containerView.getTag();
Intent intent = new Intent(v.getContext(), PokemonActivity.class);
intent.putExtra("name", current.getName());
intent.putExtra("url", current.getUrl());
v.getContext().startActivity(intent);
}
});
}
}
private List<Pokemon> pokemon = new ArrayList<>();
private RequestQueue requestQueue;
private List<Pokemon> filteredPokemon = new ArrayList<>();
PokedexAdapter(Context context) {
requestQueue = Volley.newRequestQueue(context);
loadPokemon();
}
public void loadPokemon() {
String url = "https://pokeapi.co/api/v2/pokemon?limit=365";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray results = response.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String name = result.getString("name");
pokemon.add(new Pokemon(
name.substring(0, 1).toUpperCase() + name.substring(1),
result.getString("url")
));
}
notifyDataSetChanged();
} catch (JSONException e) {
Log.e("cs50", "Json error", e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("cs50", "Pokemon list error");
}
});
requestQueue.add(request);
}
#NonNull
#Override
public PokedexViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.pokedex_row, parent, false);
return new PokedexViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PokedexViewHolder viewholder, int position){
Pokemon results = pokemon.get(position);
viewholder.textView.setText(results.getName());
viewholder.containerView.setTag(results);
}
#Override
public int getItemCount() {
return filteredPokemon.size();
}
#Override
public Filter getFilter() {
return new PokemonFilter();
}
private class PokemonFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// implement your search here
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
//No filter implemented return whole list
results.values = pokemon;
results.count = pokemon.size();
}
else {
List<Pokemon> filtered = new ArrayList<>();
for (Pokemon pokemon : filtered) {
if (pokemon.getName().toUpperCase().startsWith(constraint.toString())) {
filtered.add(pokemon);
}
}
results.values = filtered;
results.count = filtered.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredPokemon = (List<Pokemon>) results.values;
notifyDataSetChanged();
}
}
}
I really am not sure what is going on and given my knowledge of the subject, you could really help with understanding the logic better. Please let me know if there is any other information you would like from me about the code.
You might have already solved it and finished the Android tracks but this was the only thing I changed and it seemed to work after that.
for (Pokemon pokemon : pokemon) {
if (pokemon.getName().toUpperCase().startsWith(constraint.toString().toUpperCase()) {
filtered.add(pokemon);
}
}

issues with parcelable extension: getting unmarshalling unknown type code exception

long story short, I have one settlementItemeBase class as my father and two children. I want to make the father class parcelable so as extension happens, my two child classes be parcelable as well. I don't exactly know what I'm doing right or wrong. I searched little bit but nothing helped me.
here are my classes:
SettlementItemBase:
public class SettlementItemBase implements Parcelable{
public SettlementItemBase(){}
protected SettlementItemBase(Parcel in) {
}
public static final Creator<SettlementItemBase> CREATOR = new Creator<SettlementItemBase>() {
#Override
public SettlementItemBase createFromParcel(Parcel in) {
return new SettlementItemBase(in);
}
#Override
public SettlementItemBase[] newArray(int size) {
return new SettlementItemBase[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
}
first child class:
public class FirstClass extends SettlementItemBase {
private int id;
private int cardId;
private String cardNumber;
private String expDate;
private String currency;
private String url;
public FirstClass(){
id = 0;
cardId = 0;
cardNumber = "";
expDate = "";
currency = "";
url = "";
}
protected FirstClass(Parcel in) {
super(in);
id = in.readInt();
cardId = in.readInt();
cardNumber = in.readString();
expDate = in.readString();
currency = in.readString();
url = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(cardId);
dest.writeString(cardNumber);
dest.writeString(expDate);
dest.writeString(currency);
dest.writeString(url);
}
public int getId() {
return id;
}
public int getCardId() {
return cardId;
}
public String getCardNumber() {
return cardNumber;
}
public String getExpDate() {
return expDate;
}
public String getCurrency() {
return currency;
}
public String getUrl() {
return url;
}
}
second child class:
public class SecondClass extends SettlementItemBase{
private int id;
private String currency;
private String accountNumber;
private String ibanNumber;
public SecondClass(int id, String currency,
String accountNumber, String ibanNumber){
this.id = id;
this.currency = currency;
this.accountNumber = accountNumber;
this.ibanNumber = ibanNumber;
}
protected SecondClass(Parcel in){
super(in);
id = in.readInt();
currency = in.readString();
accountNumber = in.readString();
ibanNumber = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(currency);
dest.writeString(accountNumber);
dest.writeString(ibanNumber);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCurrency() {
return currency;
}
public String getAccountNumber() {
return accountNumber;
}
public String getIbanNumber() {
return ibanNumber;
}
}
I'm passing and getting an ArrayList of both child class' items with intent putParcelableArrayListExtra and getParcelableArrayListExtra methods and get the following error:
Parcel android.os.Parcel#2d0fde33: Unmarshalling unknown type code 3276849 at offset 172
any help would be appreciated 3>
well I'm posting this for those who may run into the same problem as me.
the problem was solved after adding the Creator statement to the child classes.
for one of the child classes it would be like:
public static final Creator<FirstClass> CREATOR = new Creator<FirstClass>() {
#Override
public FirstClass createFromParcel(Parcel in) {
return new FirstClass(in);
}
#Override
public FirstClass[] newArray(int size) {
return new FirstClass[size];
}
};
hope this helps. 3>

Google fused location service android

class name is Myclass and implement methods like -> LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener override methds
private static int UPDATE_INTERVAL = 10000; // 10 sec
private static int FATEST_INTERVAL = 5000; // 5 sec
private static int DISPLACEMENT = 10; // 10 meters
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
Context mContext;
#Override
public void onConnected(Bundle bundle) {
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
createLocationRequest();
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (LocationListener) mContext);
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
// mLocationRequest.setNumUpdates(2);
// mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Ov
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
stopLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
DateFormat.getTimeInstance().format(new Date());
updateUI();
}
public String updateUI() {
if (null != mCurrentLocation) {
Double lat = mCurrentLocation.getLatitude();
Double lng = mCurrentLocation.getLongitude();
Log.d("thhhhhhhhhhhhhhhhhhhh",lat.toString() +lng.toString());
getCurrentlocation(mCurrentLocation);
//setCurrentLocation(String.valueOf(lat + "," + lng));
tLocation(mCurrentLocation);
// arrayList.add(mCurrentLocation);
return lat.toString();
}
return null;
}
private void getCurrentlocation(Location mCurrentLocation) {
}
public void setmCurrentLocation(Location mCurrentLocation) {
this.mCurrentLocation = mCurrentLocation;
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this);
}
I want to develop mylocation class and getlocation method so its returns lat loan.
How to access that in any class and get lat lon ??
may you need to create servics, that implement google locationAPI , Location listner more..
In that override method onLocationChanged you get lat-long now you can send that direct to your server or other class
i hope My answer is help you.
if don't then ask me again.
thank you.

Passing content values form one activity to another in Android Studio

Activity1
private Cursor model = null;
private ClientAdapter adapter = null;
private ClientHelper helper = null;
private SharedPreferences prefs = null;
private ArrayAdapter<String> adapters;
private ArrayAdapter<String> adaptera;
private String[] available_locations;
private String[] selected_locations;
private ListView list1;
private ListView list2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locations);
list1 = (ListView) findViewById(R.id.available_locations);
list2 = (ListView) findViewById(R.id.selected_locations);
available_locations = getIntent().getStringExtra("List");
.....
Activity 2
....
public String getID(Cursor c) {
return (c.getString(0));
}
public String getclientName(Cursor c) {
return (c.getString(1));
}
public String getAddress(Cursor c) {
return (c.getString(2));
}
public String getTelephone(Cursor c) {
return (c.getString(3));
}
public String getCuisineType(Cursor c) {
return (c.getString(4));
}
public double getLatitude(Cursor c) {
return (c.getDouble(5));
}
public double getLongitude(Cursor c) {
return (c.getDouble(6));
}
public ArrayList<String> getclient;
getclient.add("clientName");
getclient.add("Address");
getclient.add("Telephone");
getclient.add("cuisineType");
getclient.add("lat");
getclient.add("lon");
public Intent intenti;
intenti = new Intent(ClientHelper.this, SetDestination.class);
intenti.putExtra("List", getclient);
startactivity(intenti);
How do I pass information from Activity2 to Activity1?
I want to do a Listview where I can select clients from the list that I have already added (hence two activity, list1 and list2, in activity1)
Use can use the Bundle to pass the data from one activity to other.
First make the object parcelable.You can do that using the plugin of Parcelable in android studio.
Example.
Intent intent=new Intent(getActivity(),targetclassname.class);
HomeScreenData homeScreenData=new HomeScreenData();//Pojo class
intent.putExtra("categorydesc",homeScreenData);
startActivity(intent);
{
//Pojo Class`enter code here`
public class HomeScreenData implements Parcelable {
private String imagePath;
private String imageTitle;
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getImageTitle() {
return imageTitle;
}
public void setImageTitle(String imageTitle) {
this.imageTitle = imageTitle;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.imagePath);
dest.writeString(this.imageTitle);
}
public HomeScreenData() {
}
protected HomeScreenData(Parcel in) {
this.imagePath = in.readString();
this.imageTitle = in.readString();
}
public static final Parcelable.Creator<HomeScreenData> CREATOR = new Parcelable.Creator<HomeScreenData>() {
public HomeScreenData createFromParcel(Parcel source) {
return new HomeScreenData(source);
}
public HomeScreenData[] newArray(int size) {
return new HomeScreenData[size];
}
};
}

Resources