Android refresh rating bar upon triggeration - java

I am having some problem when trying to refresh the rating bar after user submitted their rating. So basically I am passing the existing rating amount when certain button on my other Activity was triggered:
viewDtlEventBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Object[] obj = new Object[2];
obj[0] = String.valueOf(eventIDTV.getText());
obj[1] = eventReviewModel;
new GetEventDetailAsyncTask(new GetEventDetailAsyncTask.OnRoutineFinished() {
public void onFinish() {
// Passing whole object with value into another activity
Intent eventDtlIntent = new Intent(context, EventDetailMain.class);
// Pass in a list of rating star together with amount
eventDtlIntent.putExtra("eventPopulateStarObj", populateRatingStar);
context.startActivity(eventDtlIntent);
}
}).execute(obj);
}
});
And I am populating the rating bar when onCreate():
ratingStarList = (ArrayList<EventReview>) i
.getSerializableExtra("eventPopulateStarObj");
public void populateRatingProgressBar() {
int totalStar = 0;
// Get the total amount of rate records
for (int j = 0; j < ratingStarList.size(); j++) {
if (ratingStarList.get(j).getStarAmt() != null) {
totalStar += Integer.parseInt(ratingStarList.get(j)
.getStarAmt());
}
}
txtTotalRate.setText(totalStar + " Ratings for this event");
// Set progress bar based on the each rates
for (int i = 0; i < ratingStarList.size(); i++) {
if (ratingStarList.get(i).getStarAmt() != null) {
if (ratingStarList.get(i).getEventReviewRate().equals("5")) {
pb5Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("4")) {
pb4Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("3")) {
pb3Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("2")) {
pb2Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("1")) {
pb1Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
}
}
}
}
It did populated correctly. However, I not sure how to refresh the rating bar after user submitted their rating. Here is the code when user submit their rating:
public void promptSubmitStar() {
AlertDialog.Builder Dialog = new AlertDialog.Builder(getActivity());
Dialog.setTitle("Confirm Rating");
LayoutInflater li = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View dialogView = li.inflate(R.layout.option_submit_star, null);
txtPromptStarRate = (TextView) dialogView
.findViewById(R.id.txtPromptStarRate);
txtPromptStarRate.setText("Confirm to submit " + starRate
+ " stars for this event?");
Dialog.setView(dialogView);
Dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EventReview eventReviewModel = new EventReview();
eventReviewModel.setEventID(eventID);
eventReviewModel.setEventReviewBy(userID);
eventReviewModel.setEventReviewRate(String.valueOf(starRate));
new CreateEventReviewAsyncTask(context)
.execute(eventReviewModel);
dialog.dismiss();
// Disable the rating bar by setting a touch listener which
// always return true
ratingBar.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
return true;
}
});
}
});
Dialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
Dialog d = Dialog.show();
EventDialogueBox.customizeDialogueBox(context, d);
}
Any ideas? Thanks in advance.

Use setRating(starRate); to programmatically set the rating on the RatingBar.

Related

Trying to hide the menu item when there are no views

I'm trying to build an app that generates buttons dynamically per floatActionButton click. This aspect works fine. But if there are no views, there shouldn't be a delete menu item on the action bar. At the start of the app, since there are no items, there is no menu item but I need the menu item to show up once I start adding views. I tried to work it with if statements but it still did not work.
This is my code:
public class MainActivity extends AppCompatActivity {
int counter = 0;
FloatingActionButton addingSemester;
Button semesterButton;
LinearLayout semesterLayout;
GridLayout semesterGridLayout;
RelativeLayout relativeLayout;
LinearLayout.LayoutParams portraitLayoutParams = new LinearLayout.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT,
AppBarLayout.LayoutParams.WRAP_CONTENT);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addingSemester = (FloatingActionButton) findViewById(R.id.addActionButton);
semesterLayout = (LinearLayout) findViewById(R.id.main_layout);
semesterGridLayout = (GridLayout)findViewById(R.id.semester_grid_layout);
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
relativeLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
semesterButton = new Button(MainActivity.this);
if (savedInstanceState != null) {
counter = savedInstanceState.getInt("counter");
for(int i = 0; i < counter; i++) {
addSemesterButton(i);
}
}
}
public void addSemesterButton(int id) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
double width = (size.x)/3;
semesterButton = new Button(MainActivity.this);
semesterButton.setId(id + 1);
semesterButton.setText("Semester " + (id + 1));
semesterButton.setBackgroundColor(getColor(R.color.colorPrimary));
semesterButton.setTextColor(Color.WHITE);
portraitLayoutParams.setMargins(24, 24, 24, 24);
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.setMargins(24, 24, 24, 24);
params.width = (int) width;
params.height = GridLayout.LayoutParams.WRAP_CONTENT;
semesterButton.setLayoutParams(params);
semesterGridLayout.addView(semesterButton);
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.addView(semesterButton);
semesterButton.setLayoutParams(portraitLayoutParams);
}
setOnLongClickListenerForSemesterButton();
}
public void addTextView(int id){
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
double width = (size.x);
TextView instructionsPromptTextView = new TextView(MainActivity.this);
instructionsPromptTextView.setId(id);
instructionsPromptTextView.setText(R.string.click_the_button_to_add_semesters);
instructionsPromptTextView.setTextSize((float)width);
instructionsPromptTextView.setVisibility(View.VISIBLE);
instructionsPromptTextView.setBackgroundColor(Color.BLACK);
relativeLayout.addView(instructionsPromptTextView);
if(id == 0){
instructionsPromptTextView.setVisibility(View.INVISIBLE);
}
}
public void onFloatActionButtonClick(View view) {
if (counter < 8) {
addSemesterButton(counter);
counter++;
setOnLongClickListenerForSemesterButton();
} else if (counter == 8) {
Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", Toast.LENGTH_SHORT).show();
} else if (counter == 0){
addTextView(counter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.delete);
if(counter == 0){
item.setVisible(false);
}
if(counter > 0){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
item.setVisible(true);
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.delete) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete everything?")
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterGridLayout.removeAllViews();
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.removeAllViews();
}
counter = 0;
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("counter", counter);
super.onSaveInstanceState(savedInstanceState);
}
private void setOnLongClickListenerForSemesterButton() {
semesterButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final Button b = (Button) v;
b.setTag(b.getText().toString());
b.setBackgroundColor(Color.RED);
b.setText("Delete");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete entry");
builder.setMessage("Are you sure you want to delete this entry?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterGridLayout.removeView(b);
for (int i = 0; i < semesterGridLayout.getChildCount(); i++) {
((Button) semesterGridLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.removeView(b);
for (int i = 0; i < semesterLayout.getChildCount(); i++) {
((Button) semesterLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
}
counter--;
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
b.cancelLongPress();
b.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
b.setText(b.getTag().toString());
dialog.cancel();
}
});
builder.show();
return true;
}
});
}
}
EDIT
This is the stacktrace
FATAL EXCEPTION: main
Process: myapp.onur.journeygpacalculator, PID: 22605
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.view.View$DeclaredOnClickListener.onClick(View.java:4711)
at android.view.View.performClick(View.java:5623)
at android.view.View$PerformClick.run(View.java:22433)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6247)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4706)
at android.view.View.performClick(View.java:5623) 
at android.view.View$PerformClick.run(View.java:22433) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6247) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762) 
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.add(int, int, int, java.lang.CharSequence)' on a null object reference
at android.view.MenuInflater$MenuState.addItem(MenuInflater.java:493)
at android.view.MenuInflater.parseMenu(MenuInflater.java:190)
at android.view.MenuInflater.inflate(MenuInflater.java:111)
at android.support.v7.view.SupportMenuInflater.inflate(SupportMenuInflater.java:113)
at myapp.onur.journeygpacalculator.MainActivity.inflateMenu(MainActivity.java:182)
at myapp.onur.journeygpacalculator.MainActivity.onFloatActionButtonClick(MainActivity.java:168)
Instead of setting it invisible only in onCreateOptionsMenu set it in your action button click too like below
MenuItem item;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
item = menu.findItem(R.id.delete);
item.setVisible(false);
return super.onCreateOptionsMenu(menu);
}
public void onFloatActionButtonClick(View view) {
if (counter < 8) {
addSemesterButton(counter);
counter++;
setOnLongClickListenerForSemesterButton();
item.setVisible(true);
} else if (counter == 8) {
Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", Toast.LENGTH_SHORT).show();
item.setVisible(true);
} else if (counter == 0){
addTextView(counter);
item.setVisible(false);
}
}
1. Update onCreateOptionsMenu() as below, to hide delete option when app starts first:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
itemDelete = menu.findItem(R.id.delete);
// Required to hide delete option when app starts first
itemDelete.setVisible(false);
return true;
}
2. Add below method to update the state of delete option.
public void updateOptionMenu() {
if (counter > 0)
item.setVisible(true);
else
item.setVisible(false);
}
3. Call updateOptionMenu() method from all places where the counter value changes like: onFloatActionButtonClick() and AlertDialog's onClick() methods.
Here is the full code:
public class MainActivity extends AppCompatActivity {
MenuItem itemDelete;
int counter = 0;
FloatingActionButton addingSemester;
Button semesterButton;
LinearLayout semesterLayout;
GridLayout semesterGridLayout;
RelativeLayout relativeLayout;
LinearLayout.LayoutParams portraitLayoutParams = new LinearLayout.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT,
AppBarLayout.LayoutParams.WRAP_CONTENT);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addingSemester = (FloatingActionButton) findViewById(R.id.addActionButton);
semesterLayout = (LinearLayout) findViewById(R.id.main_layout);
semesterGridLayout = (GridLayout)findViewById(R.id.semester_grid_layout);
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
relativeLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
semesterButton = new Button(MainActivity.this);
if (savedInstanceState != null) {
counter = savedInstanceState.getInt("counter");
for(int i = 0; i < counter; i++) {
addSemesterButton(i);
}
}
addTextView(counter);
}
public void addSemesterButton(int id) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
double width = (size.x)/3;
semesterButton = new Button(MainActivity.this);
semesterButton.setId(id + 1);
semesterButton.setText("Semester " + (id + 1));
semesterButton.setBackgroundColor(getColor(R.color.colorPrimary));
semesterButton.setTextColor(Color.WHITE);
portraitLayoutParams.setMargins(24, 24, 24, 24);
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.setMargins(24, 24, 24, 24);
params.width = (int) width;
params.height = GridLayout.LayoutParams.WRAP_CONTENT;
semesterButton.setLayoutParams(params);
semesterGridLayout.addView(semesterButton);
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.addView(semesterButton);
semesterButton.setLayoutParams(portraitLayoutParams);
}
setOnLongClickListenerForSemesterButton();
}
public void addTextView(int id){
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
double width = (size.x);
TextView instructionsPromptTextView = new TextView(MainActivity.this);
instructionsPromptTextView.setId(id);
instructionsPromptTextView.setText(R.string.click_the_button_to_add_semesters);
instructionsPromptTextView.setTextSize((float)width);
instructionsPromptTextView.setVisibility(View.VISIBLE);
instructionsPromptTextView.setBackgroundColor(Color.BLACK);
relativeLayout.addView(instructionsPromptTextView);
/*
if(id == 0){
instructionsPromptTextView.setVisibility(View.INVISIBLE);
}*/
}
public void onFloatActionButtonClick(View view) {
if (counter < 8) {
addSemesterButton(counter);
counter++;
setOnLongClickListenerForSemesterButton();
// Required to show delete option
updateOptionMenu();
} else if (counter == 8) {
Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", Toast.LENGTH_SHORT).show();
}
// Will never be called because counter == 0 will be consumed by first if condition
/*
else if (counter == 0){
addTextView(counter); // Move it to onCreate()
}*/
}
public void updateOptionMenu() {
if (counter > 0)
item.setVisible(true);
else
item.setVisible(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
itemDelete = menu.findItem(R.id.delete);
// Required to hide delete option when app starts first
itemDelete.setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.delete) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete everything?")
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterGridLayout.removeAllViews();
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.removeAllViews();
}
counter = 0;
updateOptionMenu(); // Required to hide option item when all views are removed
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("counter", counter);
super.onSaveInstanceState(savedInstanceState);
}
private void setOnLongClickListenerForSemesterButton() {
semesterButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final Button b = (Button) v;
b.setTag(b.getText().toString());
b.setBackgroundColor(Color.RED);
b.setText("Delete");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete entry");
builder.setMessage("Are you sure you want to delete this entry?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterGridLayout.removeView(b);
for (int i = 0; i < semesterGridLayout.getChildCount(); i++) {
((Button) semesterGridLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.removeView(b);
for (int i = 0; i < semesterLayout.getChildCount(); i++) {
((Button) semesterLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
}
counter--;
updateOptionMenu(); // Required to hide delete item if this button is last button to be removed
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
b.cancelLongPress();
b.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
b.setText(b.getTag().toString());
dialog.cancel();
}
});
builder.show();
return true;
}
});
}
}
Hope this will help~

How to record dynamically generated buttons into the SQLite database

I'm building an app where a user dynamically generates semesters (buttons) through the Java code. Let's say that the user generates about 4 buttons (the user can generate up to 8), I want to store that into the SQLite database I've created. This is my first app ever and likely, my first time using an SQLite database. I went through the SQLite Android tutorials but my app is a bit different compared to the examples they were working with.
What I need help with, is to be able to store the dynamically generated buttons into my database so I have the exact same amount saved next time the app is launched again. I also need to wire the delete (menuItem and alertdialog) function with the onUpgrade.
This is my Mainactivity.java. This is where all my UI generation takes place. Its also my homepage.
public class MainActivity extends AppCompatActivity {
int counter = 0;
FloatingActionButton addingSemester;
Button semesterButton;
LinearLayout semesterLayout;
GridLayout semesterGridLayout;
LinearLayout.LayoutParams portraitLayoutParams = new LinearLayout.LayoutParams(
AppBarLayout.LayoutParams.MATCH_PARENT,
AppBarLayout.LayoutParams.WRAP_CONTENT);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addingSemester = (FloatingActionButton) findViewById(R.id.addActionButton);
semesterLayout = (LinearLayout) findViewById(R.id.main_layout);
semesterGridLayout = (GridLayout) findViewById(R.id.semester_grid_layout);
semesterButton = new Button(MainActivity.this);
if (savedInstanceState != null) {
counter = savedInstanceState.getInt("counter");
for (int i = 0; i < counter; i++) {
addSemesterButton(i);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.delete) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete everything?")
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
if (semesterGridLayout.getChildCount() > 0) {
semesterGridLayout.removeAllViews();
} else {
Toast.makeText(MainActivity.this, "There is nothing to delete", Toast.LENGTH_SHORT).show();
}
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
if (semesterLayout.getChildCount() > 0) {
semesterLayout.removeAllViews();
} else {
Toast.makeText(MainActivity.this, "There is nothing to delete", Toast.LENGTH_SHORT).show();
}
}
counter = 0;
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
public void addSemesterButton(int id) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
double width = (size.x) / 3;
semesterButton = new Button(MainActivity.this);
semesterButton.setId(id + 1);
semesterButton.setText("Semester " + (id + 1));
semesterButton.setBackgroundColor(getColor(R.color.colorPrimary));
semesterButton.setTextColor(Color.WHITE);
portraitLayoutParams.setMargins(24, 24, 24, 24);
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.setMargins(24, 24, 24, 24);
params.width = (int) width;
params.height = GridLayout.LayoutParams.WRAP_CONTENT;
semesterButton.setLayoutParams(params);
semesterGridLayout.addView(semesterButton);
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.addView(semesterButton);
semesterButton.setLayoutParams(portraitLayoutParams);
}
setOnLongClickListenerForSemesterButton();
setOnClickListenerForSemesterButton(counter);
}
public void onFloatActionButtonClick(View view) {
if (counter < 8) {
addSemesterButton(counter);
counter++;
setOnLongClickListenerForSemesterButton();
} else if (counter == 8) {
Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", Toast.LENGTH_SHORT).show();
} else if (counter == 0) {
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("counter", counter);
super.onSaveInstanceState(savedInstanceState);
}
private void setOnClickListenerForSemesterButton(int id){
semesterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SemesterBuilderActivity.class);
intent.putExtra("someKey", 1);
startActivity(intent);
}
});
}
private void setOnLongClickListenerForSemesterButton() {
semesterButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final Button b = (Button) v;
b.setTag(b.getText().toString());
b.setBackgroundColor(Color.RED);
b.setText("Delete");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete entry");
builder.setMessage("Are you sure you want to delete this entry?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterGridLayout.removeView(b);
for (int i = 0; i < semesterGridLayout.getChildCount(); i++) {
((Button) semesterGridLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
} else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
semesterLayout.removeView(b);
for (int i = 0; i < semesterLayout.getChildCount(); i++) {
((Button) semesterLayout.getChildAt(i)).setText("Semester " + (i + 1));
}
}
counter--;
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
b.cancelLongPress();
b.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
b.setText(b.getTag().toString());
dialog.cancel();
}
});
builder.show();
return true;
}
});
}
}
This is my Contract class:
public final class SemesterContract {
private SemesterContract(){}
public static final class SemesterEntry implements BaseColumns{
public static final String TABLE_NAME = "semesters";
public static final String _ID = BaseColumns._ID;
public static final String COLUMN_SEMESTER_NAME = "semester";
}
}
And finally this is my database helper:
public class SemesterDBHelper extends SQLiteOpenHelper{
public SemesterDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public static final String DATABASE_NAME = "semesters.db";
public static final int DATABASE_VERSION = 1;
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_SEMESTER_TABLE = "CREATE TABLE " + SemesterContract.SemesterEntry.TABLE_NAME + " ("
+ SemesterContract.SemesterEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ SemesterContract.SemesterEntry.COLUMN_SEMESTER_NAME + " TEXT NOT NULL";
db.execSQL(SQL_CREATE_SEMESTER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
I appreciate all of the help.

Dialog not dismiss in if condition

I am try to dismiss dialog in if condition true part but it is not worked.
In dialog entered in if condition but not dismiss.in If condition toast message display properly.
public void showIncomingCall() {
int getTotal = 0;
if(showincoming != null && showincoming.isShowing() )
{
//adapter1.notifyDataSetChanged();
//showincoming.dismiss();
return;
}
else {
showincoming = new Dialog(MainActivity.this);
showincoming.requestWindowFeature(Window.FEATURE_NO_TITLE);
showincoming.setContentView(R.layout.custome_dialog);
listdialog = (ListView) showincoming.findViewById(R.id.incoming_list);
//adapter1 = new CustomeListAdapter(MainActivity.this);
listdialog.setAdapter(adapter1);
//adapter1.notifyDataSetChanged();
close = (ImageButton) showincoming.findViewById(R.id.dialog_close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showincoming.dismiss();
adapter1.notifyDataSetChanged();
}
});
adapter1.notifyDataSetChanged();
for (int i = 0; i < listdialog.getCount(); i++) {
parentView = getViewByPosition(i, listdialog);
String getString = ((TextView) parentView.findViewById(R.id.tvLineStatus)).getText().toString();
if (getString.toString().equals("Idle") || getString.toString().equals("Disconnect") || getString.toString().equals("Dialing")) {
getTotal += 1;
}
}
if (getTotal >= 7) {
showincoming.dismiss();
Toast.makeText(getApplicationContext(),"getTotal" + getTotal,Toast.LENGTH_LONG).show();
adapter1.notifyDataSetChanged();
//adapter1.setNotifyOnChange(true);
}
//Toast.makeText(MainActivity.this,getTotal+"getTotal",Toast.LENGTH_LONG).show();
adapter1.notifyDataSetChanged();
listdialog.invalidateViews();
if(!showincoming.isShowing()) {
showincoming.show();
}
}
}
showincoming = new Dialog(MainActivity.this);
declare this below int getTotal = 0;
i.e outside else statement
then you can get referance of dialog object and can dissmiss dialog. try this and let me know

validation according to data types

want to validate edit text according to SQLite table data types
I have one table in my SQLite database which has three data types integer,integer,text respectively. edit texts are creates dynamically according to columns present in table. now I want to give validation on each text box like if I enter string value for integer datatype then one popup should display which shows message "can't insert text value for data type integer". so what can I do now?
here is my code
public class DisplayTable_Grid extends Activity
{
TableLayout table_layout;
SQL_crud sqlcon;
TableRow rw;
TextView gettxt_onLongclik;
ArrayList<String> storeColumnNames;
EditText enter_text;
TextView set_txt;
List<EditText> allEds = new ArrayList<EditText>();
ArrayList<String> storeallEds=new ArrayList<String>();
ArrayList<String> storeEditextText=new ArrayList<String>();
List<TextView> textViewlst = new ArrayList<TextView>();
ArrayList<String> getColumnNames=new ArrayList<String>();
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.displaytable);
sqlcon = new SQL_crud(this);
table_layout = (TableLayout) findViewById(R.id.diplay_table);
BuildTable();
}
private void BuildTable()
{
sqlcon.open();
storeColumnNames=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView.toString());
Cursor c = sqlcon.readEntryofTable(DisaplayTables_list.getTableNameFromListView.toString());
int rows = c.getCount();
int cols = c.getColumnCount();
String colN=c.getColumnNames().toString();
arraylist=sqlcon.readColumn_Datatypes(DisaplayTables_list.getTableNameFromListView.toString ());
ArrayList<String> colName=new ArrayList<String>();
colName=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView.toString());
//colName.add(colN);
c.moveToFirst();
System.out.println("size of hash map:"+arraylist.size());
for(int k=0;k<1;k++)
{
TableRow rowcolumnName = new TableRow(this);
rowcolumnName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
rowcolumnName.setBackgroundColor(Color.GRAY);
for(int a=0;a<cols/*arraylist.size()*/;a++)
{
TextView columnName = new TextView(this);
columnName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
columnName.setGravity(Gravity.CENTER);
columnName.setTextSize(18);
columnName.setPadding(0, 5, 0, 5);
columnName.setText(colName.get(a)+" "+arraylist.get(a).toString());
rowcolumnName.addView(columnName);}
table_layout.addView(rowcolumnName);
// c.moveToNext();
}
// outer for loop
if(rows==0)
{
Toast.makeText(getApplicationContext(), "rows not found..cant build table", Toast.LENGTH_LONG);
}
else{
for (int i = 0; i < rows; i++)
{
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 0; j < cols; j++)
{
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(0, 5, 0, 5);
tv.setText(c.getString(j));
row.addView(tv);
}
row.setClickable(true);
row.requestFocus();
row.setOnLongClickListener(new OnLongClickListener()
{
#Override
public boolean onLongClick(View viewlong)
{
rw=(TableRow) viewlong;
gettxt_onLongclik=(TextView)rw.getChildAt(0);
Toast.makeText(getApplicationContext(),gettxt_onLongclik.getText().toString(),Toast.LENGTH_SHORT).show();
final AlertDialog.Builder alertForSelectOperation=new AlertDialog.Builder(DisplayTable_Grid.this);
final LinearLayout linear=new LinearLayout(DisplayTable_Grid.this);
linear.setOrientation(LinearLayout.VERTICAL);
//TextView update=(TextView)new TextView(DisplayTable_Grid.this);
Button update=(Button)new Button(DisplayTable_Grid.this);
//update.setBackgroundColor(Color.rgb(3,12,90));
update.setText(Html.fromHtml("<font size=10>Update</font>"));
update.setOnClickListener(new OnClickListener()
{ #Override
public void onClick(View arg0)
{
final AlertDialog.Builder alertDialogOK_CANCEL=new AlertDialog.Builder(DisplayTable_Grid.this);
final LinearLayout linearlayout=new LinearLayout(DisplayTable_Grid.this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
sqlcon.open();
getColumnNames=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView.toString());
Cursor crs=sqlcon.readColumnCnt(DisaplayTables_list.getTableNameFromListView.toString());
int count=crs.getColumnCount();
Cursor cr=sqlcon.getSinlgeEntryof_table(DisaplayTables_list.getTableNameFromListView.toString(),getColumnNames.get(0), gettxt_onLongclik.getText().toString());
cr.moveToFirst();
for(int i=0;i<count;i++)
{ //add edittext to arralist
enter_text=new EditText(DisplayTable_Grid.this);
allEds.add(enter_text);
allEds.get(i).setText(cr.getString(cr.getColumnIndex(getColumnNames.get(i))));
linearlayout.addView(enter_text);
}
sqlcon.close();
//finish();
alertDialogOK_CANCEL.setPositiveButton("Update", new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface arg0, int arg1)
{
for(int i=0;i<allEds.size();i++)
{
//System.out.println(allEds.get(i).getText().toString());
storeallEds.add(allEds.get(i).getText().toString());
String getarraylist=arraylist.get(i).toString();
String datatype_text="{datatype=text}";
String datatype_integer="{datatype=integer}";
if(getarraylist.equals(datatype_text) || getarraylist.equals(datatype_integer))
{
if(getarraylist.equals(datatype_text))
{
Toast.makeText(getApplicationContext(), "text"+storeallEds.get(i),Toast.LENGTH_LONG).show();
//enter_text.setInputType(InputType.TYPE_CLASS_TEXT);
}
else if(getarraylist.equals(datatype_integer))
{
if(storeallEds.get(i).contains("a"))//allEds.get(i).getText().toString().contains("a")||allEds.get(i).getText().toString().contains("b"))
{
Toast.makeText(getApplicationContext(), "String in integer value",Toast.LENGTH_LONG).show();
//enter_text.setInputType(InputType.TYPE_CLASS_NUMBER);
}
else
{
//storeallEds.add(allEds.get(i).getText().toString());
Toast.makeText(getApplicationContext(), "integer"+storeallEds.get(i),Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "no datatype found",Toast.LENGTH_LONG).show();
}
}
}
//System.out.println(storeallEds);
sqlcon.open();
try
{
sqlcon.updateRecord(DisaplayTables_list.getTableNameFromListView.toString(), gettxt_onLongclik.getText().toString(), storeallEds);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"Can't Update column already exists ",Toast.LENGTH_LONG).show();
}
Intent i=new Intent(getApplicationContext(),DisplayTable_Grid.class);
startActivity(i);
sqlcon.close();
}
});
alertDialogOK_CANCEL.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface dialog, int arg1)
{
dialog.dismiss();
}
});
alertDialogOK_CANCEL.setView(linearlayout);
alertDialogOK_CANCEL.setTitle("insert values here");
alertDialogOK_CANCEL.create();
alertDialogOK_CANCEL.show();
}
});
//TextView delete=(TextView)new TextView(DisplayTable_Grid.this);
Button delete=(Button)new Button(DisplayTable_Grid.this);
delete.setText(Html.fromHtml("<font size=10> Delete</font>"));
//delete.setBackgroundColor(Color.rgb(3,12,90));
delete.setOnClickListener(new OnClickListener()
{ #Override
public void onClick(View arg0)
{
final AlertDialog.Builder alertDialogOK_CANCEL=new AlertDialog.Builder(DisplayTable_Grid.this);
alertDialogOK_CANCEL.setMessage("Press OK to Delete this Record");
alertDialogOK_CANCEL.setPositiveButton("OK", new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface arg0, int arg1)
{
sqlcon.open();
sqlcon.deleteEntry(DisaplayTables_list.getTableNameFromListView, storeColumnNames.get(0), gettxt_onLongclik.getText().toString());
sqlcon.close();
Intent i=new Intent(getApplicationContext(),DisplayTable_Grid.class);
startActivity(i);
}
});
alertDialogOK_CANCEL.setNegativeButton("CANCEL",new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface dialog, int arg1)
{
dialog.dismiss();
}
});
alertDialogOK_CANCEL.create();
alertDialogOK_CANCEL.show();
}
});
//TextView insert=(TextView)new TextView(DisplayTable_Grid.this);
Button insert=(Button)new Button(DisplayTable_Grid.this);
insert.setText(Html.fromHtml("<font size=10>Insert</font>"));
//insert.setBackgroundColor(Color.rgb(3,12,90));
insert.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
final AlertDialog.Builder alertDialog=new AlertDialog.Builder(DisplayTable_Grid.this);
final LinearLayout linearlayout=new LinearLayout(DisplayTable_Grid.this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
sqlcon.open();
getColumnNames=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView);
Cursor crs=sqlcon.readColumnCnt(DisaplayTables_list.getTableNameFromListView);
int count=crs.getColumnCount();
for(int i=0;i<count;i++)
{ //add edittext to arralist
enter_text=new EditText(DisplayTable_Grid.this);
allEds.add(enter_text);
String getarraylist=arraylist.get(i).toString();
String datatype_text="{datatype=text}";
String datatype_integer="{datatype=integer}";
if(getarraylist.equals(datatype_text))
{
Toast.makeText(getApplicationContext(), "text",Toast.LENGTH_LONG).show();
enter_text.setInputType(InputType.TYPE_CLASS_TEXT);
}
else if(getarraylist.equals(datatype_integer))
{
Toast.makeText(getApplicationContext(), "integer",Toast.LENGTH_LONG).show();
//enter_text.setInputType(InputType.TYPE_CLASS_NUMBER);
}
else
{
Toast.makeText(getApplicationContext(), "no datatype found",Toast.LENGTH_LONG).show();
}
//add textview to ayyalist
set_txt=new TextView(DisplayTable_Grid.this);
set_txt.setText(getColumnNames.get(i));
set_txt.setTextSize(15);
textViewlst.add(set_txt);
linearlayout.addView(set_txt);
linearlayout.addView(enter_text);
}
sqlcon.close();
alertDialog.setPositiveButton("Insert", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
if(allEds.size()==0)
{Toast.makeText(getApplicationContext(), "value not found",Toast.LENGTH_LONG).show();}
else
{
for(int i=0; i < allEds.size(); i++)
{ storeEditextText.add(allEds.get(i).getText().toString());
System.out.println("show gettext: "+storeEditextText.get(i).toString());
String getarraylist=arraylist.get(i).toString();
String datatype_text="{datatype=text}";
String datatype_integer="{datatype=integer}";
if(getarraylist.equals(datatype_text))
{
Toast.makeText(getApplicationContext(), "text",Toast.LENGTH_LONG).show();
}
else if(getarraylist.equals(datatype_integer))
{
Toast.makeText(getApplicationContext(), "integer",Toast.LENGTH_LONG).show();
if(storeEditextText.contains("a")||storeEditextText.contains("b"))
{
try
{
int edittxtint=Integer.parseInt(allEds.get(i).getText().toString());//enter_text.setInputType(InputType.TYPE_CLASS_NUMBER);
}
catch(Exception e)
{
System.out.println("exception....."+e);
Toast.makeText(getApplicationContext(),"value must be an integer",Toast.LENGTH_LONG).show();
}
}
}
else
{
Toast.makeText(getApplicationContext(), "no datatype found",Toast.LENGTH_LONG).show();
}
}
if(storeEditextText.size()==0)
{Toast.makeText(getApplicationContext(), "Text is empty",Toast.LENGTH_LONG).show();}
else
{
sqlcon.open();
try
{sqlcon.insert(DisaplayTables_list.getTableNameFromListView,storeEditextText);}
catch(Exception e)
{Toast.makeText(getApplicationContext(),"emp_id is Primary key", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),"column value already exists",Toast.LENGTH_LONG).show();}
System.out.println("size of storeEdittext="+storeEditextText.size());
System.out.println("size of Edit Texts: "+allEds.size());
}
Intent i=new Intent(getApplicationContext(),DisplayTable_Grid.class);
startActivity(i);
sqlcon.close();
}
}
});
alertDialog.setView(linearlayout);
alertDialog.setTitle("insert values here");
alertDialog.create();
alertDialog.show();
}
});
linear.addView(insert);
linear.addView(update);
linear.addView(delete);
alertForSelectOperation.setView(linear);
alertForSelectOperation.setTitle("perform operations here");
alertForSelectOperation.create();
alertForSelectOperation.show();
alertForSelectOperation.setCancelable(true);
return false;
}
});
row.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
TableRow rw=(TableRow) v;
TextView gettxt=(TextView)rw.getChildAt(0);
Toast.makeText(getApplicationContext(), gettxt.getText().toString(),Toast.LENGTH_SHORT).show();
}
});
c.moveToNext();
table_layout.addView(row);
}
}//end of else for null rows
sqlcon.close();
}
}
You can modify your table definition and add "CHECK" constraint, like this:
CREATE TABLE tab (
column1 INTEGER CHECK(typeof(column1) == "integer"),
column2 INTEGER CHECK(typeof(column2) == "integer"),
column3 TEXT CHECK(typeof(column3) == "text")
);
This will enable your database to enforce datatype checking for this table. This will slow down the insertions/updates on this table just a bit.

how to set button invisible depending on another activity

In my activity I add to it some stuff by checking checkbox and if
list.size()>0 (this condition is in my adapter) shows up button which is redirecting me to second activity. In second activity I display listview filled with items from static list , when I click on it i delete object from list, also Ive made button in second activity which make this list.clear(); finish(); When I return to first activity i've still visible button even if static list was cleared. How to solve it ? I need the simplest ideas becouse i'm a beginner in android. All answers, suggestions, clues are wellcome. If you don't know how to do it, pop up thread. Thank you for your time.
public class TowarAdapter extends ArrayAdapter<Towar> {
private List<Towar> items;
private Activity context;
private int i = 0;
ImageButton b_zatwierdz;
int counter = 0;
boolean user_checked = false;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public TowarAdapter(Activity context, int resource, List<Towar> items,
ImageButton b_zatwierdz) {
super(context, resource);
this.b_zatwierdz = b_zatwierdz;
this.items = items;
this.context = context;
}
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Towar getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
static class ViewHolder {
TextView tvNazwaT;
TextView tvCenaT;
ImageView ivTowar;
CheckBox chb_czy_zamowic;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder view;
// LayoutInflater inflator = activity.getLayoutInflater();
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
view = new ViewHolder();
convertView = inflator.inflate(R.layout.element, null);
view.tvNazwaT = (TextView) convertView.findViewById(R.id.tvNazwaT);
view.tvCenaT = (TextView) convertView.findViewById(R.id.tvCenaT);
view.chb_czy_zamowic = (CheckBox) convertView
.findViewById(R.id.chb_czy_zamowic);
view.ivTowar = (ImageView) convertView.findViewById(R.id.ivTowar);
convertView.setTag(view);
} else {
view = (ViewHolder) convertView.getTag();
}
view.tvNazwaT.setText(items.get(position).getTow_nazwa());
view.tvNazwaT.setTextColor(Color.BLACK);
view.tvCenaT.setText(items.get(position).getTow_cena() + "zł");
for (int i = 0; i < items.size(); i++) {
String s = Integer.valueOf(items.get(position).Kat_id).toString();
int resourceId = context.getResources().getIdentifier("a" + s + i,
"drawable", context.getPackageName());
view.ivTowar.setImageResource(resourceId);
}
view.chb_czy_zamowic
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
final CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()) {
user_checked = true;
if (user_checked == true) {
final Dialog d1 = new Dialog(context);
d1.setContentView(R.layout.ilosc);
d1.getWindow()
.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
d1.setTitle("Wybierz ilość");
final EditText et_Ilosc;
Button b_Ok;
Button b_Odejmij;
Button b_Dodaj;
et_Ilosc = (EditText) d1
.findViewById(R.id.et_Ilosc);
et_Ilosc.setText(String.valueOf(i));
view.chb_czy_zamowic.setClickable(false);
b_Dodaj = (Button) d1
.findViewById(R.id.b_Dodaj);
b_Dodaj.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String zmienna_pom = et_Ilosc.getText()
.toString();
i = Integer.valueOf(zmienna_pom);
if (i < 0) {
Toast t = Toast.makeText(
getContext(),
"Niepoprawna wartość",
Toast.LENGTH_SHORT);
t.show();
} else if (i == items.get(position)
.getTow_ilosc_value()) {
Toast t = Toast
.makeText(
getContext(),
"Osiągnięto wartość maksymalną "
+ items.get(
position)
.getTow_ilosc_value(),
Toast.LENGTH_SHORT);
t.show();
} else if (i > items.get(position)
.getTow_ilosc_value()) {
Toast t = Toast
.makeText(
getContext(),
"Przekroczono wartość maksymalną "
+ items.get(
position)
.getTow_ilosc_value(),
Toast.LENGTH_SHORT);
t.show();
}
else if (et_Ilosc.getText().toString()
.equals("")) {
Toast t = Toast.makeText(
getContext(),
"Uzupełnij pole ilość",
Toast.LENGTH_SHORT);
t.show();
} else {
setI(i);
int k = getI();
k++;
setI(k);
et_Ilosc.setText(String.valueOf(i));
}
}
});
b_Odejmij = (Button) d1
.findViewById(R.id.b_Odejmij);
b_Odejmij
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String zmienna_pom = et_Ilosc
.getText().toString();
i = Integer
.valueOf(zmienna_pom);
if (i < 0) {
Toast t = Toast
.makeText(
getContext(),
"Niepoprawna wartość",
Toast.LENGTH_SHORT);
t.show();
} else if (et_Ilosc.getText()
.toString().equals("")) {
Toast t = Toast
.makeText(
getContext(),
"Uzupełnij pole ilość",
Toast.LENGTH_SHORT);
t.show();
} else {
setI(i);
i--;
setI(i);
et_Ilosc.setText(String
.valueOf(i));
}
}
});
b_Ok = (Button) d1.findViewById(R.id.b_Ok);
b_Ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String zmiennna_pom = et_Ilosc
.getText().toString();
int k = Integer.valueOf(zmiennna_pom);
if (k <= 0
|| k > items.get(position)
.getTow_ilosc_value()) {
Toast t = Toast
.makeText(
getContext(),
"Wybierz z przedziału 1-"
+ items.get(
position)
.getTow_ilosc_value(),
Toast.LENGTH_SHORT);
t.show();
} else if (et_Ilosc.getText()
.toString().equals("")) {
Toast t = Toast.makeText(
getContext(),
"Uzupełnij pole ilość",
Toast.LENGTH_SHORT);
t.show();
} else {
view.chb_czy_zamowic
.setEnabled(false);
// String zmiennna_pom = et_Ilosc
// / .getText().toString();
// int k = Integer
// .valueOf(zmiennna_pom);
items.get(position).Tow_ilosc -= k;
Towar checkedObject = new Towar();
checkedObject.Tow_ilosc = k;
checkedObject.Kat_id = items
.get(position).Kat_id;
checkedObject.kategoria = items
.get(position).kategoria;
checkedObject.Tow_cena = items
.get(position).Tow_cena;
checkedObject.Tow_id = items
.get(position).Tow_id;
checkedObject.Tow_nazwa = items
.get(position).Tow_nazwa;
MainActivity.lista_wybranych_towarow
.add(checkedObject);
k = 0;
setI(0);
// et_Ilosc.setText("");
d1.dismiss();
}
// view.chb_czy_zamowic.setChecked(false);
if (MainActivity.lista_wybranych_towarow
.size() > 0) {
b_zatwierdz
.setVisibility(View.VISIBLE);
}
else
b_zatwierdz
.setVisibility(View.INVISIBLE);
}
});
d1.show();
}
;
}
}
});
return convertView;
}
}
To make the button invisible, you need to do the following (I'm just mentioning the logic for hiding the button - you will have to implement this in a listener):
Button button = (Button) findViewById(R.layout.button_id); // Point it to the button
if(list_is_empty) {
button.setVisibility(Button.GONE); // This line hides the button
}
Know that in Android, 'GONE' is used to hide the element from the view and this space is now available in the layout. 'INVISIBLE' means that while the widget is hidden, the space for this widget is still unavailable.
You could put an extra in the intent when calling the activity, or save the flag in a shared preference. Then depending on the flag you can set the visibility to true or false?
you can use startActivityForResult here. when you delete object from list. pass back the boolean where like 'isDelete' and check this variable in onActivityResult (it is first activity) if it is true i.e object is delete so set button visibility to false else do nothing.
you can also used sharedpreferences here. track the boolean variable and depending on its value set the button visibility.
for shared preference do this :
when you delete object do this, to write boolean value to shared preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); //creating object of shared preference
SharedPreferences.Editor editor = preferences.edit(); //getting editor to write value
editor.putBoolean("isShow",false); //first value is key and second is the value which you are going to assign it
editor.commit();
and in your main adapter class do :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean show = preferences.getBoolean("isShow",false); //first value is key and second value is used if isShow is not defined.
if(show)
//show the button
else
//hide the button

Categories