Cannot get the secondSpinner to refresh itself - java

Can someone look at my code its really simple created just to practice my skills. But the language spinner works but the gender spinner is buggy. It will work once i change the language then change the gender and then go back to the gender i originally wanted. Code is shown. Thanks. Have tried putting onItemSelected() for spinnerGen, it does not solve the issue. Researching about this since last night cant find any solution
public class MainActivity extends AppCompatActivity {
private Button btnGo, btnAbout;
private Spinner spinner, spinnerGen;
private EditText addName;
private ArrayList<String> options;
private ArrayList<String> optionsGen;
private String allOption = "";
private String genOption = "";
private String genOptionSec = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initPage();
options = new ArrayList<>();
options.add("English");
options.add("Bengali");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, options);
spinner.setAdapter(adapter);
adapter.setNotifyOnChange(true);
adapter.notifyDataSetChanged();
optionsGen = new ArrayList<>();
optionsGen.add("Male");
optionsGen.add("Female");
ArrayAdapter<String> adapterGen = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, optionsGen);
spinnerGen.setAdapter(adapterGen);
adapterGen.setNotifyOnChange(true);
adapterGen.notifyDataSetChanged();
spinnerMethod();
}
private void initPage() {
btnGo = findViewById(R.id.btnGo);
btnAbout = findViewById(R.id.btnAbout);
spinner = findViewById(R.id.spinner);
spinnerGen = findViewById(R.id.spinnerGen);
addName = findViewById(R.id.addName);
}
public void spinnerMethod() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
allOption = spinner.getSelectedItem().toString();
switch (allOption) {
case "English" :
newMethodEnglish();
break;
case "Bengali" :
newMethodBengali();
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void newMethodEnglish() {
genOption = spinnerGen.getSelectedItem().toString();
switch (genOption) {
case "Male":
onClickEngMale(); //In these method Im just navigating to another activity
break;
case "Female":
OnClickEngFemale();
break;
default:
break;
}
}
public void OnClickEngFemale() {
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String femaleData = addName.getText().toString();
Intent intent = new Intent(MainActivity.this, EngFemale.class);
intent.putExtra("DataFemale", femaleData);
startActivity(intent);
}
});
}
public void onClickEngMale() {
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String maleData = addName.getText().toString();
Intent intent = new Intent(MainActivity.this, EngMale.class);
intent.putExtra("Data", maleData);
startActivity(intent);
}
});
}
public void newMethodBengali() {
genOptionSec = spinnerGen.getSelectedItem().toString();
switch (genOptionSec){
case "Male":
onClickBanMale();
break;
case "Female":
onClickBanFemale();
default:
break;
}
}
public void onClickBanMale() {
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String maleData = addName.getText().toString();
Intent intent = new Intent(MainActivity.this, BanMale.class);
intent.putExtra("DataBan", maleData);
startActivity(intent);
}
});
}
public void onClickBanFemale() {
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String femaleData = addName.getText().toString();
Intent intent = new Intent(MainActivity.this, BanFemale.class);
intent.putExtra("BanFemale", femaleData);
startActivity(intent);
}
});
}
}

Related

Cant get my API data to display on other pages

The code I've done was followed closely by a few YouTube tutorials. I'm designing an Age of Empires app that takes in the data from a public API. When the user progresses through the pages then different parts of the API data are shown. What I wanted it to do was get the data from the main activity (where the API is retrieved) and put some of its many data into the UniqueUnit page. It's using something called serializable which I can't quite understand how it works yet.
For the record, it works in getting the data from page 'DetailedCivilization' but just completely breaks on 'UniqueUnit'page.
MainActivity.java
package com.example.ageofempires2;
import ...
public class MainActivity extends AppCompatActivity {
public static final String TAG = "tag";
RecyclerView itemList;
Adapter adapter;
List<Civilizations> all_civilizations;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Civilizations menu");
all_civilizations = new ArrayList<>();
itemList = findViewById(R.id.itemList);
itemList.setLayoutManager(new LinearLayoutManager(this));
adapter = new Adapter(this, all_civilizations);
itemList.setAdapter(adapter);
getJsonData();
}
private void getJsonData() {
String URL = "https://age-of-empires-2-api.herokuapp.com/api/v1/civilizations";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray civilizations = response.getJSONArray("civilizations");
JSONObject civilizationsData = civilizations.getJSONObject(0);
Log.d(TAG, "onResponse "+ civilizationsData);
for (int i=0; i< civilizationsData.length();i++){
JSONObject civilization = civilizations.getJSONObject(i);
Civilizations v = new Civilizations();
v.setName(civilization.getString("name"));
v.setArmy_type(civilization.getString("army_type"));
v.setExpansion(civilization.getString("expansion"));
v.setCivilization_bonus(civilization.getString("civilization_bonus"));
v.setUnique_unit(civilization.getString("unique_unit"));
all_civilizations.add(v);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse" + error.getMessage());
}
});
requestQueue.add(objectRequest);
}
}
Adapter.java
package com.example.ageofempires2;
import ...
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<Civilizations> allCivilizations;
private Context context;
public Adapter(Context ctx, List<Civilizations> civilizationsData){
this.allCivilizations = civilizationsData;
this.context = ctx;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.civilization_view,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.titleName.setText(allCivilizations.get(position).getName());
holder.vv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putSerializable("civilizationsData", allCivilizations.get(position));
Intent i = new Intent(context, DetailedCivilization.class);
i.putExtras(b);
v.getContext().startActivity(i);
}
});
}
#Override
public int getItemCount() {
return allCivilizations.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView titleName;
TextView expansionName;
View vv;
public ViewHolder(#NonNull View itemView) {
super(itemView);
titleName = itemView.findViewById(R.id.civilizationUniqueUnits);
expansionName = itemView.findViewById(R.id.civilizationUnitDescription);
vv = itemView;
}
}
}
Civilizations.java
package com.example.ageofempires2;
import java.io.Serializable;
public class Civilizations implements Serializable {
private String name;
private String expansion;
private String army_type;
private String civilization_bonus;
private String unique_unit;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExpansion() {
return expansion;
}
public void setExpansion(String expansion) {
this.expansion = expansion;
}
public String getArmy_type() {
return army_type;
}
public void setArmy_type(String army_type) {
this.army_type = army_type;
}
public String getCivilization_bonus() {
return civilization_bonus;
}
public void setCivilization_bonus(String civilization_bonus) {this.civilization_bonus = civilization_bonus; }
public String getUnique_unit() {
return unique_unit;
}
public void setUnique_unit(String unique_unit) {this.unique_unit = unique_unit; }
}
UniqueUnits.java
package com.example.ageofempires2;
import ...
public class UniqueUnit extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unique_unit);
getSupportActionBar().setTitle("Unique Unit");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent incomingIntent = getIntent();
Bundle incomingName = incomingIntent.getExtras();
Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData");
Log.d(TAG, "onCreate: IDK MAN IT SHOULD WORK??" +incomingName);
TextView unit = findViewById(R.id.civilizationUnitDescription);
unit.setText(v.getUnique_unit());
}
}
DetailedCivilization.java
package com.example.ageofempires2;
import ...
public class DetailedCivilization extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations v = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit();
}
});
}
private void activityTech(){
Intent intent = new Intent(this, UniqueTech.class);
startActivity(intent);
}
private void activityUnit(){
Intent intent = new Intent(this, UniqueUnit.class);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
Solutions is
private void activityUnit(Civilizations civ){
Bundle b = new Bundle();
b.putSerializable("civilizationsData", civ)
Intent intent = new Intent(this, UniqueUnit.class);
intent.putExtras(b);
startActivity(intent);
}
In DetailedCivilization.java
Rename v from line Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData"); to civ or something more descriptive
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations civ = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit(civ);
}
});
}
And pass Civilizations when you call activityUnit function
Basically you forgot to pass Civilizations when you go from DetailedCivilization.java to UniqueUnits.java

How to different open activities without using position

This is a recipe app with categories and sub categories. I want to know is there any other command to open different activities besides position command. Because I have a problem when searching it becames alphabetical order, when i click the item it give me different result because the position is changing. I dont know what is the problem of my code is it the search function or the position command to open different new activities.
MainAdapter.class
public class MainAdapter extends FirebaseRecyclerAdapter<MainModel,MainAdapter.myViewHolder> {
private Context context;
/**
* Initialize a {#link RecyclerView.Adapter} that listens to a Firebase query. See
* {#link FirebaseRecyclerOptions} for configuration options.
*
* #param options
*/
public MainAdapter(#NonNull FirebaseRecyclerOptions<MainModel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull MainAdapter.myViewHolder holder, int position, #NonNull MainModel model) {
holder.categoryName.setText(model.getName());
holder.categoryDesc.setText(model.getDescription());
Glide.with(holder.categoryImage.getContext())
.load(model.getImage())
.placeholder(R.drawable.common_google_signin_btn_icon_dark)
.error(R.drawable.common_google_signin_btn_icon_dark_normal)
.into(holder.categoryImage);
context = holder.itemView.getContext();
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent;
switch (position){
case 0:
intent = new Intent(context, ChickenActivity.class);
break;
case 1:
intent = new Intent(context, PorkActivity.class);
break;
case 2:
intent = new Intent(context, BeefActivity.class);
break;
case 3:
intent = new Intent(context, SeafoodActivity.class);
break;
default:
intent = new Intent(context, VegetableActivity.class);
break;
}
context.startActivity(intent);
}
});
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_item,parent,false);
return new myViewHolder(view);
}
class myViewHolder extends RecyclerView.ViewHolder{
ImageView categoryImage;
TextView categoryName, categoryDesc;
public myViewHolder(#NonNull View itemView) {
super(itemView);
categoryImage = (ImageView)itemView.findViewById(R.id.categoryImage);
categoryName = (TextView)itemView.findViewById(R.id.categoryName);
categoryDesc = (TextView)itemView.findViewById(R.id.categoryDesc);
}
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
MainAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<MainModel> options =
new FirebaseRecyclerOptions.Builder<MainModel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("category"), MainModel.class)
.build();
mainAdapter = new MainAdapter(options);
recyclerView.setAdapter(mainAdapter);
}
#Override
protected void onStart() {
super.onStart();
mainAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mainAdapter.stopListening();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search,menu);
MenuItem item = menu.findItem(R.id.search);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
txtSearch(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
txtSearch(query);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
private void txtSearch(String str)
{
FirebaseRecyclerOptions<MainModel> options =
new FirebaseRecyclerOptions.Builder<MainModel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("category").orderByChild("name").startAt(str).endAt(str+"~"), MainModel.class)
.build();
mainAdapter = new MainAdapter(options);
mainAdapter.startListening();
recyclerView.setAdapter(mainAdapter);
}
}
Instead of tying the Activity to a number you should tie it to a tag or some identifier. For example, you have 3 items in the list Like:
[
{
name: "chickenwings"
},
{
name: "octopus"
},
{
name: "tomato"
}
]
Instead you can have additional information like the activity the item should correlate with, for example
[
{
name: "chickenwings",
category: "chicken"
},
{
name: "octopus",
category: "seafood"
},
{
name: "tomato",
category: "vegetable"
}
]
This will help you update your code like below
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent;
val category = model.getCategory()
switch (category){
case "chicken":
intent = new Intent(context, ChickenActivity.class);
break;
case "pork":
intent = new Intent(context, PorkActivity.class);
break;
case "beef":
intent = new Intent(context, BeefActivity.class);
break;
case "seafood":
intent = new Intent(context, SeafoodActivity.class);
break;
case "vegetable":
default:
intent = new Intent(context, VegetableActivity.class);
break;
}
context.startActivity(intent);
}
});
You can use "holder.getAdapterPosition" instead of "position" to solve this problem.

Filter Firestore database with two Spinner to RecyclerView

I am making a blood bank application with firestore database.
i want to get my data with two spinners for correct blood group and location of person who using my application. i used many method to dio this thing,but i failed everytime. this time you want fix it for the society.
and i made a index for that in my firestoew databse
my code is
public class ListActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public Dialog dialog;
Spinner bloodg,localbodyg;
Context context;
TextView sk;
private FirebaseFirestore db = FirebaseFirestore.getInstance ( );
private CollectionReference noteBokkRef = db.collection ("users");
RecyclerView recyclerView;
public NoteAdapter adapter;
public String name1,place1,number1,blood1,location1;
public String bld;
public String lclbdy;
public String group1;
public String munci;
Button load;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_list);
overridePendingTransition( R.anim.fui_slide_in_right, R.anim.fui_slide_out_left );
recyclerView=findViewById (R.id.recyclerview);
recyclerView.setVisibility (View.INVISIBLE);
load=findViewById (R.id.load);
bloodg=findViewById (R.id.bloodg);
localbodyg=findViewById (R.id.localbodyg);
final ArrayAdapter<CharSequence> adapter1=ArrayAdapter.createFromResource (this, R.array.blood_groups, R.layout.spinner_item);
adapter1.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item);
bloodg.setAdapter (adapter1);
bloodg.setOnItemSelectedListener (this);
ArrayAdapter<CharSequence>adapter2=ArrayAdapter.createFromResource (this, R.array.muncipality, R.layout.spinner_item);
adapter2.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item);
localbodyg.setAdapter (adapter2);
localbodyg.setOnItemSelectedListener (this);
load.setOnClickListener (new View.OnClickListener ( ) {
#Override
public void onClick(View v) {
recyclerView.setVisibility (View.VISIBLE);
Toast.makeText (ListActivity.this,bld +lclbdy,Toast.LENGTH_SHORT).show ();
}
});
setUpRecyclerView ( );
}
public void setUpRecyclerView() {
String blood = bloodg.getSelectedItem().toString();
String localbody = localbodyg.getSelectedItem().toString();
Query query=db.collection ("users")
.whereEqualTo ("bloodgroup",bloodg.getSelectedItem ().toString ())
.whereEqualTo ("muncipality",localbodyg.getSelectedItem ().toString ())
.orderBy ("name",Query.Direction.ASCENDING);
FirestoreRecyclerOptions<Note>options=new FirestoreRecyclerOptions.Builder<Note> ()
.setQuery (query,Note.class).build ();
FirebaseFirestoreSettings settings=new FirebaseFirestoreSettings .Builder ()
.setPersistenceEnabled (false)
.build ();
adapter=new NoteAdapter (options);
recyclerView.setHasFixedSize (true);
recyclerView.setLayoutManager (new LinearLayoutManager (this));
recyclerView.setAdapter (adapter);
adapter.setOnItemClickListener (new NoteAdapter.OnItemClickListener ( ) {
#Override
public void onItemClick(Note note, int position) {
String number=note.getNumber ();
String name=note.getName ();
String place=note.getPlace ();
String location=note.getMuncipality ();
String blood=note.getBloodgroup ();
name1=name;
place1=place;
location1=location;
blood1=blood;
number1=number;
startDialog();
}
});
}
#Override
protected void onStart() {
super.onStart ( );
adapter.startListening ();
}
#Override
protected void onStop() {
super.onStop ( );
adapter.stopListening ();
}
private void startDialog() {
dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custompopup);
dialog.show();
TextView tv_message = (TextView) dialog .findViewById(R.id.txtclose);
TextView name=dialog.findViewById (R.id.name2);
name.setText (name1);
TextView place=dialog.findViewById (R.id.place);
place.setText (place1);
TextView localbody=dialog.findViewById (R.id.location);
localbody.setText (location1);
TextView blood=dialog.findViewById (R.id.blood);
blood.setText (blood1);
TextView number=dialog.findViewById (R.id.number);
number.setText (number1);
Button call = (Button)dialog.findViewById(R.id.call);
call.setOnClickListener (new View.OnClickListener ( ) {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number1));
startActivity(intent);
}
});
Button share=dialog.findViewById (R.id.share);
share.setOnClickListener (new View.OnClickListener ( ) {
#Override
public void onClick(View v) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,name1+"\n"+blood1+"\n"+place1+"\n"+location1+"\n"+number1+"\n");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "The title");
startActivity(Intent.createChooser(shareIntent, "Share..."));
}
});
Button chat=dialog.findViewById (R.id.whatsapp);
chat.setOnClickListener (new View.OnClickListener ( ) {
#Override
public void onClick(View v) {
Uri uri=Uri.parse ("smsto:"+number1);
Intent intent=new Intent (Intent.ACTION_SENDTO, uri);
intent.setPackage ("com.whatsapp");
intent.putExtra(Intent.EXTRA_TEXT,"Your score and Some extra text");
intent.putExtra(Intent.EXTRA_SUBJECT, "The title");
startActivity (intent);
}
});
tv_message.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater ().inflate (R.menu.menu1,menu);
MenuItem item=menu.findItem (R.id.search);
return super.onCreateOptionsMenu (menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected (item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getId() == R.id.bloodg)
{
String group=parent.getItemAtPosition (position).toString ();
if (position!=0){
Toast.makeText (parent.getContext (),group,Toast.LENGTH_SHORT).show ();}
bld=group;
}
else if(parent.getId() == R.id.localbodyg)
{
String muncipality=parent.getItemAtPosition (position).toString ();
if (position!=0){
Toast.makeText (parent.getContext (),muncipality,Toast.LENGTH_SHORT).show ();}
lclbdy=muncipality; }
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void call(View view) {
}
}
Database structure:

How to create add and delete button for listview so next time user open the application added item stays there?

I need an answer on how to create an add button to add listview item, and a delete button to delete last added item. Look at my code. I made an add button but that item exists only for a few seconds and every time I close that page (go to other activity in usermode) it is deleted. Please let me know how can I fix this code and how can I write code for delete button. I need to know how to delete last made item. Thanks for your help in advance. I am looking forward to reply.
public class dodaj extends Activity {
ListView lv;
SearchView sv;
EditText txtinput;
ArrayList<String> arrayList;
String[] recepies={};
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dodaj);
registerClickCallback();
lv=(ListView) findViewById(R.id.listView);
sv=(SearchView) findViewById(R.id.searchView);
txtinput=(EditText)findViewById(R.id.txtinput);
Button addbutton=(Button)findViewById(R.id.addbutton);
Button buttondel=(Button) findViewById(R.id.buttondel);
arrayList= new ArrayList<>(Arrays.asList(recepies));
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v ) {
String newItem=txtinput.getText().toString();
arrayList.add(newItem);
adapter.notifyDataSetChanged();
}
});
buttondel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v ) {
int i = arrayList.size()-1;
arrayList.remove(arrayList.get(i));
}
});
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arrayList);
lv.setAdapter(adapter);
sv.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
private void registerClickCallback(){
lv=(ListView) findViewById(R.id.listView);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
TextView textView= (TextView) viewClicked;
if(position==0){
goToMojRecept1();
}else if(position==1){
goToMojRecept2();
}else if(position==2){
goToMojRecept3();
}else if(position==3){
goToMojRecept4();
}else if(position==4) {
goToMojRecept5();
}
}
});
}
private void goToMojRecept5() {
Intent intent = new Intent(this, MojRecept5.class);
startActivity(intent);
}
private void goToMojRecept4() {
Intent intent = new Intent(this, MojRecept4.class);
startActivity(intent);
}
private void goToMojRecept3() {
Intent intent = new Intent(this, MojRecept3.class);
startActivity(intent);
}
private void goToMojRecept2() {
Intent intent = new Intent(this, MojRecept2.class);
startActivity(intent);
}
private void goToMojRecept1() {
Intent intent = new Intent(this, MojRecept1.class);
startActivity(intent);
}

android.widget.Button cannot be cast to android.widget.CheckBox

I'm getting the error from the title in my Android project. I have searched for similar issues, which had me checkboxes casting, which seems ok, and also to clean and rebuild the project, which it did not work.
The app is crashing when I click the "Register" Button after a register form that contains EditTexts (for username, email and password) and Checkboxes for the user to pick multiple items. What should I do next?
public class RegisterActivity extends Activity {
ArrayList<Sport> sports = new ArrayList<>();
ArrayList<Sport> selectedSports = new ArrayList<>();
private void initializeSports(){
String[] sportsArray = getResources().getStringArray(array.sportsName);
for (int i = 0; i < sportsArray.length; i++){
sports.add(new Sport(i + 1, sportsArray[i]));
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_register);
initializeSports();
final EditText etEmail = (EditText) findViewById(id.etEmail);
final EditText etUsername = (EditText) findViewById(id.etUsername);
final EditText etPassword = (EditText) findViewById(id.etPassword);
final Button bRegister = (Button) findViewById(id.bRegister);
final CheckBox cbSoccer = (CheckBox) findViewById(id.cbSoccer);
cbSoccer.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbFootball = (CheckBox) findViewById(id.cbFootball);
cbFootball.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbBasket = (CheckBox) findViewById(id.cbBasket);
cbBasket.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbTennis = (CheckBox) findViewById(id.cbTennis);
cbTennis.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbSwimming = (CheckBox) findViewById(id.cbSwimming);
cbSwimming.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbGym = (CheckBox) findViewById(id.cbGym);
cbGym.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
final CheckBox cbOther = (CheckBox) findViewById(id.cbOther);
cbOther.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
selectItem(v);
}
});
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String email = etEmail.getText().toString();
final String passcode = etPassword.getText().toString();
selectItem(v);
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username, email, passcode, selectedSports, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
public void selectItem(View v){
boolean checked = ((CheckBox)v).isChecked();
switch(v.getId()){
case R.id.cbSoccer:
if(checked){
selectedSports.add(sports.get(0));
} else{
selectedSports.remove(sports.get(0));
} break;
case R.id.cbFootball:
if(checked){
selectedSports.add(sports.get(1));
} else{
selectedSports.remove(sports.get(1));
} break;
case R.id.cbTennis:
if(checked){
selectedSports.add(sports.get(2));
} else{
selectedSports.remove(sports.get(2));
} break;
case R.id.cbSwimming:
if(checked){
selectedSports.add(sports.get(3));
} else{
selectedSports.remove(sports.get(3));
} break;
case R.id.cbGym:
if(checked){
selectedSports.add(sports.get(4));
} else{
selectedSports.remove(sports.get(4));
} break;
case R.id.cbBasket:
if(checked){
selectedSports.add(sports.get(5));
} else{
selectedSports.remove(sports.get(5));
} break;
case R.id.cbOther:
if(checked){
selectedSports.add(sports.get(6));
} else{
selectedSports.remove(sports.get(6));
} break;
}
}
}
You are casting the view to CheckBox in your selectItem(v) method and in your listener
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectItem(v);
}
});
You are passing the View v, i.e, the clicked button, so the button can not be casted to CheckBox.
Remove this line from listener
selectItem(v);
and it will be alright.
In the selectItem(v) method the view passed to the method is an instance of Button since it is written in the onClickListener of button
If you want to do the same first make a check in selectItem(View v) method
if(v instanceof CheckBox) {
boolean checked = ((CheckBox)v).isChecked();
}
Then proceed with the rest of code

Categories