Dependant spinners in android studio - java

I am using Depandent Spinner in android studio. They are working well The child spinner is showing the correct data of against selected value of parent spinner but when I pass spinner text to Firebase Realtime database, it only pases the text of first index of childcat(child spinner), even when other item is selected. Text of main cat(parent spinner) is passing well in firebase database.
Here is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
emailtext = findViewById(R.id.emailtext);
// category = findViewById(R.id.cat);
fname = findViewById(R.id.fullnametext);
organization = findViewById(R.id.org);
maincat = findViewById(R.id.categories);
childcat = findViewById(R.id.categoryitem);
signup = findViewById(R.id.btn_signup);
ArrayAdapter adp1=ArrayAdapter.createFromResource(this, R.array.Categories,R.layout.support_simple_spinner_dropdown_item);
adp1.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
maincat.setAdapter(adp1);
maincat.setOnItemSelectedListener(this);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = emailtext.getText().toString();
// final String fcategory = category.getText().toString();
final String name = fname.getText().toString();
//final String con_pass = organization.getText().toString();
final String cat=category;
final String subcat=specific;
Map<String, Object> Users = new HashMap<>();
Users.put("Name", name);
Users.put("Email", email);
Users.put("Category", cat);
Users.put("SubCategory", subcat);
FirebaseDatabase.getInstance().getReference().child("Users").push().setValue(Users).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.i("vvv", "oncomplete");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("nnn", "OnFailure:" + e.toString());
}
});
}
});
;
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
category=maincat.getSelectedItem().toString();
if(i==0){
ArrayAdapter adp2 = ArrayAdapter.createFromResource(this, R.array.Natural_Disasters, R.layout.support_simple_spinner_dropdown_item);
childcat.setAdapter(adp2);
}
if(i==1){
ArrayAdapter adp2 = ArrayAdapter.createFromResource(this, R.array.Medical, R.layout.support_simple_spinner_dropdown_item);
childcat.setAdapter(adp2);
}
if(i==2){
ArrayAdapter adp2 = ArrayAdapter.createFromResource(this, R.array.Events, R.layout.support_simple_spinner_dropdown_item);
childcat.setAdapter(adp2);
}
if(i==3){
ArrayAdapter adp2 = ArrayAdapter.createFromResource(this, R.array.Career_supporting, R.layout.support_simple_spinner_dropdown_item);
childcat.setAdapter(adp2);
}
if(i==4){
ArrayAdapter adp2 = ArrayAdapter.createFromResource(this, R.array.SocialIssues, R.layout.support_simple_spinner_dropdown_item);
childcat.setAdapter(adp2);
}
specific=childcat.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}

add these 3 lines in on create
ProgressDialog mDialog = new ProgressDialog(getApplicationContext());
mDialog.setMessage("Please wait...");
mDialog.setCancelable(false);
add two lines in your signup function
mDialog.show(); //to show activity indicator
mDialog. dismiss(); //to hide activity indicator
here is example with your code
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = emailtext.getText().toString();
// final String fcategory = category.getText().toString();
final String name = fname.getText().toString();
//final String con_pass = organization.getText().toString();
final String cat=category;
final String subcat=specific;
Map<String, Object> Users = new HashMap<>();
Users.put("Name", name);
Users.put("Email", email);
Users.put("Category", cat);
Users.put("SubCategory", subcat);
mDialog.show();//to show activity indicator
FirebaseDatabase.getInstance().getReference().child("Users").push().setValue(Users).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
mDialog. dismiss();//to hide activity indicator
Log.i("vvv", "oncomplete");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("nnn", "OnFailure:" + e.toString());
}
});
}
});

Related

Data being added as new instead of updating firebase firestore

I'm trying to make the data get update in firestore with the method updatedata but for some reason instead of the data being updated, a new user gets created with the data I'm supposed to be updating, I don't get why, I've been stuck on it for hours now and any help will be appreciated, this is the class where I either save data or update it:
public class Admin_add extends AppCompatActivity {
public static final String TAG = "TAG";
EditText mFullName, mEmail, mPassword, mPhone;
Button mAddBtn,leaveAdd;
FirebaseAuth fAuth;
ProgressBar progressBar;
FirebaseFirestore fStore;/*db*/
String UserID;
Button showall;
private String uName,uEmail,uPhone,uPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_add);
mFullName = findViewById(R.id.fullName1);
mEmail = findViewById(R.id.Email1);
mPassword = findViewById(R.id.password1);
mPhone = findViewById(R.id.phone1);
mAddBtn = findViewById(R.id.adduserbtn);
leaveAdd=findViewById(R.id.leaveadd);
showall=findViewById(R.id.showallbtn);
fAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
fStore = FirebaseFirestore.getInstance();
Bundle bundle=getIntent().getExtras();
if(bundle!=null){
mAddBtn.setText("update");
uName=bundle.getString("uName");
uEmail=bundle.getString("uEmail");
uPhone=bundle.getString("uPhone");
uPassword=bundle.getString("uPassword");
mFullName.setText(uName);
mPhone.setText(uPhone);
mEmail.setText(uEmail);
mPassword.setText(uPassword);
}else{
mAddBtn.setText("save");
}
leaveAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),AdminAct.class));
finish();
}
});
showall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Crud_users.class));
}
});
mAddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString().trim();
final String password = mPassword.getText().toString().trim();
final String fullname = mFullName.getText().toString();
final String phone = mPhone.getText().toString();
if (TextUtils.isEmpty(email)) {
mEmail.setError("Email Is Required.");
return;
}
if (TextUtils.isEmpty(password)) {
mPassword.setError("Password Is Required.");
return;
}
if (password.length() < 8) {
mPassword.setError("Password must be>=8 characters");
}
progressBar.setVisibility(View.VISIBLE);
Bundle bundle1=getIntent().getExtras();
if(bundle1!=null){
String id=UserID;
updateToFireStore(fullname,email,password,phone);
}else{
fAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(Admin_add.this, "user created", Toast.LENGTH_SHORT).show();
UserID = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(UserID);
Map<String, Object> user = new HashMap<>();
user.put("fName", fullname);
user.put("email", email);
user.put("phone", phone);
user.put("Password", password);
//specify if user is admin
user.put("isUser", "1");
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "OnSuccess: user profile is created for" + UserID);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "Failure" + e.toString());
}
});
progressBar.setVisibility(View.INVISIBLE);
} else {
Toast.makeText(Admin_add.this, "ERROR" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
//register to firebase
}
});
}
private void updateToFireStore(String fullname, String email, String password, String phone) {
UserID = fAuth.getCurrentUser().getUid();
fStore.collection("users").document(UserID).update("email",email,"Password",password,"fName",fullname,"phone",phone)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(Admin_add.this, "data updated", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Admin_add.this, "Error"+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Admin_add.this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
i think there is a problem somewhere in updatetofirestore method, this is my adapater class:
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.MyViewHolder> {
private Crud_users activity;
private List<usersmodel> mList;
public UsersAdapter(Crud_users activity,List<usersmodel> mList){
this.activity=activity;
this.mList=mList;
}
public void updateData(int position){
usersmodel item=mList.get(position);
Bundle bundle=new Bundle();
bundle.putString("uName",item.getfName());
bundle.putString("uEmail",item.getEmail());
bundle.putString("uPhone",item.getPhone());
bundle.putString("uPassword",item.getPassword());
Intent intent=new Intent(activity,Admin_add.class);
intent.putExtras(bundle);
activity.startActivity(intent);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(activity).inflate(R.layout.list_item_single,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.name.setText(mList.get(position).getfName());
holder.email.setText(mList.get(position).getEmail());
holder.phone.setText(mList.get(position).getPhone());
holder.isuser.setText(mList.get(position).getIsUser());
}
#Override
public int getItemCount() {
return mList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView name,email,phone,isuser;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
name=itemView.findViewById(R.id.list_name);
email=itemView.findViewById(R.id.list_email);
phone=itemView.findViewById(R.id.list_phone);
isuser=itemView.findViewById(R.id.list_isuser);
}
}
}
I really have no clue i've tried everything i can.
I think you should change the way you pass values to update() method of firebase.
fStore.collection("users").document(UserID).update("email",email,"Password",password,"fName",fullname,"phone",phone)
The correct way is to pass a map<String, Object>. Below is the example:
Map<String, Object> data = new HashMap<String, Object>();
data.put("email", email);
data.put("Password", password);
data.put("fName", fullname);
data.put("phone", phone);
fStore.collection("users").document(UserID).update(data);
You can use set() method of Firebase with SetOptions.merge() as an alternative which is better than update() because update() will update a field only if it exists where set() with SetOptions.merge() will update the existing field and create if it doesn't exist.
Read more about it here.
Map<String, Object> data = new HashMap<String, Object>();
data.put("email", email);
data.put("Password", password);
data.put("fName", fullname);
data.put("phone", phone);
fStore.collection("users").document(UserID).set(data, SetOptions.merge());

How to create a pie chart using data from Firestore in Java

Right now my code is looking like this
public class MainActivity extends AppCompatActivity {
Spinner spinner;
TextView textView;
String item;
private EditText amount;
private Button save;
private Button report;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
amount = findViewById(R.id.Amount);
save = findViewById(R.id.Save);
String [] category = {"Food", "Gift", "Education", "Health", "Car"};
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
int txt_amount = Integer.parseInt(amount.getText().toString());
item = spinner.getSelectedItem().toString();
if (txt_amount == 0){
Toast.makeText(MainActivity.this, "Empty credentials!", Toast.LENGTH_SHORT).show();
}
else{
FirebaseFirestore db = FirebaseFirestore.getInstance();
Map<String, Object> users = new HashMap<>();
users.put("Category", item);
users.put("Amount", txt_amount);
db.collection("Expenses").add(users).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Values added", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
//SPINNER CODE
spinner = findViewById(R.id.spinnerCategory);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, category);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
report = (Button) findViewById(R.id.Report);
report.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivityReport();
}
});
FirebaseFirestore.getInstance().collection("Expenses").whereEqualTo("Category", "Expense");
}
public void openActivityReport(){
Intent intent = new Intent(this, ReportActivity.class);
startActivity(intent);
}
public class ReportActivity extends AppCompatActivity {
private PieChart pieChart;
FirebaseFirestore db = FirebaseFirestore.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report);
pieChart = findViewById(R.id.activity_report_piechart);
loadPieChartData();
setupPieChart();
}
public void setupPieChart(){
pieChart.setDrawHoleEnabled(true);
pieChart.setUsePercentValues(true); // to use the percentage values on the chart
pieChart.setEntryLabelColor(Color.BLACK);
pieChart.setEntryLabelTextSize(12);
pieChart.setCenterText("Spending by Category");
pieChart.setCenterTextSize(24);
pieChart.getDescription().setEnabled(false);
}
private void loadPieChartData(){
db.collection("Expenses").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
for(QueryDocumentSnapshot document : task.getResult()){
Log.d("", document.getLong("Amount") + document.getString("Category"));
ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
entries.add(new PieEntry(Float.valueOf(document.getLong("Amount")),document.getString("Category")));
entries.add(new PieEntry(Float.valueOf(document.getLong("Amount")),document.getString("Category")));
entries.add(new PieEntry(Float.valueOf(document.getLong("Amount")),document.getString("Category")));
entries.add(new PieEntry(Float.valueOf(document.getLong("Amount")),document.getString("Category")));
ArrayList<Integer> colors = new ArrayList<>();
for(int color: ColorTemplate.MATERIAL_COLORS){
colors.add(color);
}
for(int color: ColorTemplate.VORDIPLOM_COLORS){
colors.add(color);
}
PieDataSet dataSet = new PieDataSet(entries, "Expense Category");
dataSet.setColors(colors);
PieData data = new PieData(dataSet);
data.setDrawValues(true); //draws the values of the different percentages
data.setValueFormatter(new PercentFormatter(pieChart)); //Presents the percentage
data.setValueTextColor(Color.BLACK);
data.setValueTextSize(16f);
pieChart.setData(data);
pieChart.invalidate();
}
}
else{
Log.d("", "Error getting documents ", task.getException());
}
}
});
And my firestore database is looking like this
https://i.stack.imgur.com/vijfb.png
Is there anyway to arrange my code and to be able to create a pie chart from the data that is being stored in the firestore database. Hopefully this is enough code and the image is enough to be able to get some help

How to add a PLEASE SELECT error to a JSON Spinner

I have an app where you upload images to my company server
I have 2 spinners populated with json data and the selected item in the spinner is passed to an uri.builder for the upload url,
I have seen many questions on SO about setting a please select option on a spinner BUT the please select option of my spinners are coded into my JSON data as an item.
Now what I want is that the app will give an error if that please select item is selected to prompt the user to select a item in the spinner
so to summarize My spinners are populated with json data, the first item in the json data is "Please select" now I want an error message to appear if the please select option is chosen.
public class SecondActivity extends AppCompatActivity implements
View.OnClickListener {
private final int PICK_IMAGE=12345;
private final int REQUEST_CAMERA=6352;
private static final int REQUEST_CAMERA_ACCESS_PERMISSION=5674;
private Bitmap bitmap;
private ImageView imageView;
String myURL;
Spinner spinner;
Spinner spinner2;
String URL;
String URL2;
ArrayList<String> CategoryName;
ArrayList<String> ClientName;
String Item;
String Item2;
String email;
String clientId;
String pwd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
imageView=findViewById(R.id.imageView);
Button fromCamera=findViewById(R.id.fromCamera);
Button fromGallery=findViewById(R.id.fromGallery);
Button upload=findViewById(R.id.upload);
CategoryName=new ArrayList<>();
ClientName=new ArrayList<>();
spinner=findViewById(R.id.spinner);
spinner2=findViewById(R.id.spinner2);
email = getSharedPreferences("MyPrefs", MODE_PRIVATE).getString("name", "");
clientId= getSharedPreferences("MyPrefs", MODE_PRIVATE).getString("id", "");
pwd= getSharedPreferences("MyPrefs", MODE_PRIVATE).getString("password", "");
CheckBox chk =findViewById(R.id.chk1);
if (chk.isChecked()) {
Uri.Builder builder=new Uri.Builder();
builder.scheme("https")
.authority("www.smartpractice.co.za")
.appendPath("files-upload-phone-app.asp")
.appendQueryParameter("MyForm", "Yes")
.appendQueryParameter("ClientID", clientId)
.appendQueryParameter("Username", email)
.appendQueryParameter("Pwd", pwd)
.appendQueryParameter("Category", Item)
.appendQueryParameter("ClientName", Item2)
.appendQueryParameter("NoEmail", "Yes");
myURL=builder.build().toString();
} else {
Uri.Builder builder=new Uri.Builder();
builder.scheme("https")
.authority("www.smartpractice.co.za")
.appendPath("files-upload-phone-app.asp")
.appendQueryParameter("MyForm", "Yes")
.appendQueryParameter("ClientID", clientId)
.appendQueryParameter("Username", email)
.appendQueryParameter("Pwd", pwd)
.appendQueryParameter("Category", Item)
.appendQueryParameter("ClientName", Item2)
.appendQueryParameter("NoEmail", "Yes");
myURL=builder.build().toString();
}
upload.setOnClickListener(this);
fromCamera.setOnClickListener(this);
fromGallery.setOnClickListener(this);
Uri.Builder builder=new Uri.Builder();
builder.scheme("https")
.authority("www.smartpractice.co.za")
.appendPath("app-categories.asp")
.appendQueryParameter("MyForm", "Yes")
.appendQueryParameter("ClientID",clientId )
.appendQueryParameter("Username",email )
.appendQueryParameter("Pwd",pwd );
URL=builder.build().toString();
Uri.Builder builder2=new Uri.Builder();
builder2.scheme("https")
.authority("www.smartpractice.co.za")
.appendPath("app-clients.asp")
.appendQueryParameter("MyForm", "Yes")
.appendQueryParameter("ClientID",clientId )
.appendQueryParameter("Username",email )
.appendQueryParameter("Pwd",pwd );
URL2=builder2.build().toString();
loadSpinnerData(URL);
loadSpinnerData2(URL2);
spinner 1 on item selection code
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String country=spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(), country, Toast.LENGTH_LONG).show();
Item=spinner.getSelectedItem().toString();
spinner.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Spinner 2 on itme selection code
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String country=spinner2.getItemAtPosition(spinner2.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(), country, Toast.LENGTH_LONG).show();
Item2=spinner2.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
}
spinner 1 code for loading the JSON data from the server
private void loadSpinnerData(String url) {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
if (jsonObject.getInt("success") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String country=jsonObject1.getString("Category");
CategoryName.add(country);
}
}
spinner.setAdapter(new ArrayAdapter<>(SecondActivity.this, android.R.layout.simple_spinner_dropdown_item, CategoryName));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout=30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
Code for spinner 2 to load JSON data from the server
private void loadSpinnerData2(String url) {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
if (jsonObject.getInt("success") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String clientName=jsonObject1.getString("ClientName");
ClientName.add(clientName);
}
}
spinner2.setAdapter(new ArrayAdapter<>(SecondActivity.this, android.R.layout.simple_spinner_dropdown_item, ClientName));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout=30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
Add the following line to top of your onItemSelected Method of Spinner.
if(i==0){
///Here you need to show the error msg for the first item selected
Log.v("ERROR","Please select an item callded");
//return is used the break the flow of the app so the code below does not run in this case
return;
}
Add your item at first position. Add an Item Selected Check Listner on Spinner and add a check if selected value is first. If first then show a message
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
if(position==0)
Toast.makeText(getContext,"Please select a value",Toast.LENGTH_LONG).show()
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});

Multiple layout setVisibility wont show correct layout after getting pressed on certain layout

I have a layout in which there are several other layouts by including in XML, I add some textviews as buttons to change the view layouts from one layout to another.
I display each layout with the setVisibility method between layouts, with setOnClickListener in the textview.
The problem is just after finishing displaying the "profile" layout and trying to display the "about us" layout, the system displays a "profile" layout instead of the "about us" layout.
Here is myJava
public class SettingMenu extends AppCompatActivity {
View userProfile, settingLayout, userFavorite, UserEditProfile, aboutUS, contactUS, ProgressBar;
TextView user_username, user_password, user_email, user_ID, tvVisi, tvMisi, tvMitra, tvIsiVisi, tvIsiMisi, tvIsiMitra;
EditText ETUname, ETPass, ETEmail;
ImageView ivBack, ivEditUProfile;
Button bSetProfile, bSetFavorite, bLogout, BSave, BCancel, bSetAbout, bSetContact;
ArrayList<HashMap<String, String>> list_data;
SessionManager sessionManager;
int x = 0;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
settingLayout = findViewById(R.id.SettingLayout);
userProfile = findViewById(R.id.user_profile);
userProfile.setVisibility(View.GONE);
aboutUS = findViewById(R.id.AboutUs);
aboutUS.setVisibility(View.GONE);
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (x == 0){
Intent i = new Intent(SettingMenu.this, MainActivity.class);
startActivity(i);
finish();
}
else if (x == 1){
x = 0;
UserEditProfile.setVisibility(View.GONE);
settingLayout.setVisibility(View.VISIBLE);
}
else if (x == 2){
x = 0;
userFavorite.setVisibility(View.GONE);
settingLayout.setVisibility(View.VISIBLE);
}
else if (x == 3) {
x = 0;
aboutUS.setVisibility(View.GONE);
settingLayout.setVisibility(View.VISIBLE);
}
else if (x == 4){
x = 0;
settingLayout.setVisibility(View.VISIBLE);
contactUS.setVisibility(View.GONE);
}
}
});
bSetAbout = findViewById(R.id.bSettingAbout);
bSetAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aboutUS.setVisibility(View.VISIBLE);
settingLayout.setVisibility(View.GONE);
AboutUs();
x = x + 3;
}
});
bSetContact = findViewById(R.id.bSettingContact);
bSetContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bSetProfile = findViewById(R.id.bSettingProfile);
bSetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userProfile.setVisibility(View.VISIBLE);
settingLayout.setVisibility(View.GONE);
UserProfile();
x = x + 1;
}
});
bSetFavorite = findViewById(R.id.bSettingFav);
bSetFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bLogout = findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sessionManager.logout();
}
});
}
private void UserProfile() {
UserEditProfile = findViewById(R.id.EditParam);
UserEditProfile.setVisibility(View.GONE);
ETUname = findViewById(R.id.eTUsername);
ETUname.setVisibility(View.GONE);
ETPass = findViewById(R.id.eTPassword);
ETPass.setVisibility(View.GONE);
ETEmail = findViewById(R.id.eTEmail);
ETEmail.setVisibility(View.GONE);
user_username = findViewById(R.id.tVUsername);
user_email = findViewById(R.id.tVEmail);
user_password = findViewById(R.id.tVPassword);
user_ID = findViewById(R.id.tVUser_userID);
final HashMap<String , String> user = sessionManager.getUserDetail();
if (user.get(sessionManager.USERNAME).equals("")){
user_username.setText(R.string.empty_username);
}
else {
user_username.setText(user.get(sessionManager.USERNAME));
}
user_email.setText(user.get(sessionManager.EMAIL));
user_password.setText(user.get(sessionManager.PASSWORD));
user_ID.setText("USER ID #" + user.get(sessionManager.UserID));
ivEditUProfile = findViewById(R.id.iVEdit);
ivEditUProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user_username.setVisibility(View.GONE);
user_email.setVisibility(View.GONE);
user_password.setVisibility(View.GONE);
ETEmail.setVisibility(View.VISIBLE);
ETEmail.setText(user.get(sessionManager.EMAIL));
ETPass.setVisibility(View.VISIBLE);
ETPass.setText(user.get(sessionManager.PASSWORD));
ETUname.setVisibility(View.VISIBLE);
ETUname.setText(user.get(sessionManager.USERNAME));
UserEditProfile.setVisibility(View.VISIBLE);
}
});
BSave = findViewById(R.id.bSave);
BSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String editedUsername = ETUname.getText().toString();
String editedEmail = ETEmail.getText().toString();
String editedPass = ETPass.getText().toString();
if (editedUsername.equals(user_username.getText().toString()) &&
editedEmail.equals(user_email.getText().toString()) &&
editedPass.equals(user_password.getText().toString())){
Cancel();
}
else {
SaveChangedProfile(editedEmail, editedUsername, editedPass);
}
}
});
BCancel = findViewById(R.id.bCancel);
BCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cancel();
}
});
}
private void SaveChangedProfile(final String EditedEmail, final String EditedUsername, final String EditedPassword) {
//kirim langsung semua
}
private void AboutUs() {
list_data = new ArrayList<>();
ProgressBar = findViewById(R.id.progressLayout);
ProgressBar.setVisibility(View.VISIBLE);
tvVisi = findViewById(R.id.TvVisi);
tvMisi = findViewById(R.id.TvMisi);
tvMitra = findViewById(R.id.TvMitra);
tvVisi.setText("VISI");
tvMisi.setText("MISI");
tvMitra.setText("MITRA");
tvIsiVisi = findViewById(R.id.TvIsiVisi);
tvIsiMisi = findViewById(R.id.TvIsiMisi);
tvIsiMitra = findViewById(R.id.TvIsiMitra);
final String URL_about = "https://x";
final StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_about, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Take json Object
JSONObject jsonObject = new JSONObject(response);
//Take Parameter success from php
String success = jsonObject.getString("success");
//get Array tempat from php
JSONArray jsonArray = jsonObject.getJSONArray("about");
//traversing through all the object
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject detail = jsonArray.getJSONObject(i);
//adding the product to HashMap
HashMap<String, String> map = new HashMap<>();
map.put("visi", detail.getString("visi"));
map.put("misi", detail.getString("misi"));
map.put("mitra", detail.getString("mitra"));
list_data.add(0, map);
}
//Put Picture Location to Glide (function) and show it on layout item ("Imageview")
/*Glide.with(getApplicationContext())
.load(list_data.get(0).get("foto"))
.into(Imageview);*/
//Put each data in each Layout item
tvIsiVisi.setText(list_data.get(0).get("visi"));
tvIsiMisi.setText(list_data.get(0).get("misi"));
tvIsiMitra.setText(list_data.get(0).get("mitra"));
ProgressBar.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SettingMenu.this, "Error : " +e.toString(), Toast.LENGTH_SHORT).show();
AboutUs();
}
}
},
//Give something in these case toast to notice if server gone nuts. (it's only basic got no more time to detailed it)
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Something Wrong :/",Toast.LENGTH_LONG).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
private void Cancel() {
user_username.setVisibility(View.VISIBLE);
user_email.setVisibility(View.VISIBLE);
user_password.setVisibility(View.VISIBLE);
ETUname.setText("");
ETUname.setVisibility(View.GONE);
ETPass.setText("");
ETPass.setVisibility(View.GONE);
ETEmail.setText("");
ETEmail.setVisibility(View.GONE);
UserEditProfile.setVisibility(View.GONE);
}
}
UPDATE
I change my method from setVisibility to setContentView
here's the code. it works fine for me
public class SettingMenu extends AppCompatActivity {
View UserEditProfile, ProgressBar;
TextView user_username, user_password, user_email, user_ID, tvVisi, tvMisi, tvMitra, tvIsiVisi, tvIsiMisi, tvIsiMitra;
EditText ETUname, ETPass, ETEmail;
ImageView ivBack, ivEditUProfile;
Button bSetProfile, bSetFavorite, bLogout, BSave, BCancel, bSetAbout, bSetContact;
ArrayList<HashMap<String, String>> list_data;
SessionManager sessionManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
ControllerHome();
}
private void ControllerHome() {
setContentView(R.layout.activity_setting);
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SettingMenu.this, MainActivity.class);
startActivity(i);
finish();
}
});
bSetAbout = findViewById(R.id.bSettingAbout);
bSetAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AboutUs();
}
});
bSetContact = findViewById(R.id.bSettingContact);
bSetContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bSetProfile = findViewById(R.id.bSettingProfile);
bSetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UserProfile();
}
});
bSetFavorite = findViewById(R.id.bSettingFav);
bSetFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
bLogout = findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sessionManager.logout();
}
});
}
private void UserProfile() {
setContentView(R.layout.setting_user_profile);
UserEditProfile = findViewById(R.id.EditParam);
UserEditProfile.setVisibility(View.GONE);
ETUname = findViewById(R.id.eTUsername);
ETUname.setVisibility(View.GONE);
ETPass = findViewById(R.id.eTPassword);
ETPass.setVisibility(View.GONE);
ETEmail = findViewById(R.id.eTEmail);
ETEmail.setVisibility(View.GONE);
user_username = findViewById(R.id.tVUsername);
user_email = findViewById(R.id.tVEmail);
user_password = findViewById(R.id.tVPassword);
user_ID = findViewById(R.id.tVUser_userID);
final HashMap<String , String> user = sessionManager.getUserDetail();
if (user.get(sessionManager.USERNAME).equals("")){
user_username.setText(R.string.empty_username);
}
else {
user_username.setText(user.get(sessionManager.USERNAME));
}
user_email.setText(user.get(sessionManager.EMAIL));
user_password.setText(user.get(sessionManager.PASSWORD));
user_ID.setText("USER ID #" + user.get(sessionManager.UserID));
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ControllerHome();
}
});
ivEditUProfile = findViewById(R.id.iVEdit);
ivEditUProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user_username.setVisibility(View.GONE);
user_email.setVisibility(View.GONE);
user_password.setVisibility(View.GONE);
ETEmail.setVisibility(View.VISIBLE);
ETEmail.setText(user.get(sessionManager.EMAIL));
ETPass.setVisibility(View.VISIBLE);
ETPass.setText(user.get(sessionManager.PASSWORD));
ETUname.setVisibility(View.VISIBLE);
ETUname.setText(user.get(sessionManager.USERNAME));
UserEditProfile.setVisibility(View.VISIBLE);
}
});
BSave = findViewById(R.id.bSave);
BSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String editedUsername = ETUname.getText().toString();
String editedEmail = ETEmail.getText().toString();
String editedPass = ETPass.getText().toString();
if (editedUsername.equals(user_username.getText().toString()) &&
editedEmail.equals(user_email.getText().toString()) &&
editedPass.equals(user_password.getText().toString())){
Cancel();
}
else {
SaveChangedProfile(editedEmail, editedUsername, editedPass);
}
}
});
BCancel = findViewById(R.id.bCancel);
BCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cancel();
}
});
}
private void SaveChangedProfile(final String EditedEmail, final String EditedUsername, final String EditedPassword) {
//kirim langsung semua
}
private void AboutUs() {
setContentView(R.layout.about_us);
list_data = new ArrayList<>();
ProgressBar = findViewById(R.id.progressLayout);
ProgressBar.setVisibility(View.VISIBLE);
tvVisi = findViewById(R.id.TvVisi);
tvMisi = findViewById(R.id.TvMisi);
tvMitra = findViewById(R.id.TvMitra);
tvVisi.setText("VISI");
tvMisi.setText("MISI");
tvMitra.setText("MITRA");
tvIsiVisi = findViewById(R.id.TvIsiVisi);
tvIsiMisi = findViewById(R.id.TvIsiMisi);
tvIsiMitra = findViewById(R.id.TvIsiMitra);
ivBack = findViewById(R.id.IVSettingBack);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ControllerHome();
}
});
final String URL_about = "https://x";
final StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_about, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Take json Object
JSONObject jsonObject = new JSONObject(response);
//Take Parameter success from php
String success = jsonObject.getString("success");
//get Array tempat from php
JSONArray jsonArray = jsonObject.getJSONArray("about");
//traversing through all the object
for (int i = 0; i < jsonArray.length(); i++) {
//getting product object from json array
JSONObject detail = jsonArray.getJSONObject(i);
//adding the product to HashMap
HashMap<String, String> map = new HashMap<>();
map.put("visi", detail.getString("visi"));
map.put("misi", detail.getString("misi"));
map.put("mitra", detail.getString("mitra"));
list_data.add(0, map);
}
//Put Picture Location to Glide (function) and show it on layout item ("Imageview")
/*Glide.with(getApplicationContext())
.load(list_data.get(0).get("foto"))
.into(Imageview);*/
//Put each data in each Layout item
tvIsiVisi.setText(list_data.get(0).get("visi"));
tvIsiMisi.setText(list_data.get(0).get("misi"));
tvIsiMitra.setText(list_data.get(0).get("mitra"));
ProgressBar.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SettingMenu.this, "Error : " +e.toString(), Toast.LENGTH_SHORT).show();
AboutUs();
}
}
},
//Give something in these case toast to notice if server gone nuts. (it's only basic got no more time to detailed it)
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Something Wrong :/",Toast.LENGTH_LONG).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
private void Cancel() {
user_username.setVisibility(View.VISIBLE);
user_email.setVisibility(View.VISIBLE);
user_password.setVisibility(View.VISIBLE);
ETUname.setText("");
ETUname.setVisibility(View.GONE);
ETPass.setText("");
ETPass.setVisibility(View.GONE);
ETEmail.setText("");
ETEmail.setVisibility(View.GONE);
UserEditProfile.setVisibility(View.GONE);
}
}
solved by using setContentView rather than setVisibility.

Combining Spinner and Button onClick Listener is giving me a Null Pointer exception

I have an app where a person will be allowed to post an announcement. The person has to select on the spinner the category of their announcement and type their announcement on an EditText. After entering both these fields the Button will allow the person to make the Announcement but if the spinner value or the EditText Value is empty an Error should be generated. I tried making the button invisible for the person typing the Announcement because i was getting a Null Pointer Exception but after switching to, making the button invisible I still get the same Error. This is my Code:
public class MakeAnnouncements extends AppCompatActivity {
private EditText announcement;
private Button announce_button;
private ProgressDialog announcementDialog;
private DatabaseReference mRootRef;
private FirebaseAuth mAuth;
private String mCurrentUserId;
private String announcer;
private String []SPINNERCATEGORY ={"General","Cubs","Scouts","Seniors"};
private String category_text;
private MaterialBetterSpinner betterSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_announcements);
announcementDialog = new ProgressDialog(this);
mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();
announcement = (EditText)findViewById(R.id.announce_text);
announce_button = (Button)findViewById(R.id.announce_btn);
announce_button.setVisibility(View.VISIBLE);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,SPINNERCATEGORY);
betterSpinner = (MaterialBetterSpinner)findViewById(R.id.category_spinner);
betterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
String spinner_value= adapterView.getItemAtPosition(position).toString();
if(position==0){
// no item selected show Toast message
announce_button.setVisibility(View.INVISIBLE);
} else{
announce_button.setVisibility(View.VISIBLE);
// item selected
}
category_text = spinner_value;
return;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
announce_button.setVisibility(View.INVISIBLE);
}
});
betterSpinner.setAdapter(arrayAdapter);
mRootRef.child("Users").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
announcer = dataSnapshot.child("name").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
announce_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //<----- This is where i am getting a null point exception
String announced_text = announcement.getText().toString().trim();
String choosen_category = category_text.trim();
if (TextUtils.isEmpty(announced_text)){
announcement.setError("You did not type any announcement");
return;
}
announcementDialog.setTitle("Posting Announcement...");
announcementDialog.setMessage("Please wait...");
announcementDialog.setCanceledOnTouchOutside(false);
announcementDialog.show();
PostAnnouncement(announced_text,choosen_category);
}
});
}
private void PostAnnouncement(String announced_text, String choosen_category) {
DatabaseReference chat_push_key = mRootRef.child("Announcements").child(announcer).push();
String push_key = chat_push_key.getKey();
Map messageMap = new HashMap();
messageMap.put("announcement",announced_text);
messageMap.put("type","text");
messageMap.put("category",choosen_category);
messageMap.put("from",announcer);
messageMap.put("time", ServerValue.TIMESTAMP);
Map messageUserMap = new HashMap();
messageUserMap.put( "Announcements" + "/" + push_key, messageMap);
announcement.setText("");
announcementDialog.hide();
Toast.makeText(getApplicationContext(), "Your announcement was successfully posted",Toast.LENGTH_LONG).show();
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError != null){
Log.d("CHAT_LOG", databaseError.getMessage().toString());
}
}
});
}
}
What am i required to do to validate if the spinner Value is not empty?
According to your code you can check on the variable category_text.
if(TextUtils.isEmpty(category_text)){
//Show your error message
}
After checking for possible ways to solve this This Link assisted me.
I first changed the spinner_value to be a global variable. Then wrote this code:
String announced_text = announcement.getText().toString().trim();
String choosen_category = null;
if (TextUtils.isEmpty(announced_text)){
announcement.setError("You did not type any announcement");
return;
}
if(spinner_value != null){
choosen_category = spinner_value.trim();
return;
}
else if(spinner_value == null){
betterspinner.setError("This section must be selected before proceeding");
return;
}
After that i removed button Visibilities that are in my initial code.

Categories

Resources