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
Related
I have been trying to figure this out all day, as I would like to add an image depending on the outcome of the emotion may detect. Just wanted to add some some images but I'm still new to this. Can anyone help me with this one to.
btw here's my code:
public class DetectionActivity extends AppCompatActivity {
// Background task of face detection.
private class DetectionTask extends AsyncTask<InputStream, String, Face[]> {
private boolean mSucceed = true;
#Override
protected Face[] doInBackground(InputStream... params) {
// Get an instance of face service client to detect faces in image.
FaceServiceClient faceServiceClient = SampleApp.getFaceServiceClient();
try {
publishProgress("Detecting...");
// Start detection.
return faceServiceClient.detect(
params[0], /* Input stream of image to detect */
true, /* Whether to return face ID */
true, /* Whether to return face landmarks */
new FaceServiceClient.FaceAttributeType[]{
FaceServiceClient.FaceAttributeType.Emotion,
});
} catch (Exception e) {
mSucceed = false;
publishProgress(e.getMessage());
addLog(e.getMessage());
return null;
}
}
#Override
protected void onPreExecute() {
mProgressDialog.show();
addLog("Request: Detecting in image " + mImageUri);
}
#Override
protected void onProgressUpdate(String... progress) {
mProgressDialog.setMessage(progress[0]);
setInfo(progress[0]);
}
#Override
protected void onPostExecute(Face[] result) {
if (mSucceed) {
addLog("Response: Success. Detected " + (result == null ? 0 : result.length)
+ " face(s) in " + mImageUri);
}
// Show the result on screen when detection is done.
setUiAfterDetection(result, mSucceed);
}
}
// Flag to indicate which task is to be performed.
private static final int REQUEST_SELECT_IMAGE = 0;
// The URI of the image selected to detect.
private Uri mImageUri;
// The image selected to detect.
private Bitmap mBitmap;
// Progress dialog popped up when communicating with server.
ProgressDialog mProgressDialog;
// When the activity is created, set all the member variables to initial state.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detection);
//this hides the back button and I thank you
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle(getString(R.string.progress_dialog_title));
// Disable button "detect" as the image to detect is not selected.
setDetectButtonEnabledStatus(false);
LogHelper.clearDetectionLog();
}
// Save the activity state when it's going to stop.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("ImageUri", mImageUri);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menuAbout:
// Toast.makeText(this, "You clicked about", Toast.LENGTH_SHORT).show();
View messageView = getLayoutInflater().inflate(R.layout.about, null, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.smile);
builder.setTitle(R.string.app_name);
builder.setView(messageView);
builder.create();
builder.show();
break;
case R.id.menuHelp:
// Toast.makeText(this, "You clicked settings", Toast.LENGTH_SHORT).show();
// Intent help = new Intent(this, HelpActivity.class);
//startActivity(help);
// break;
View messageViewh = getLayoutInflater().inflate(R.layout.help, null, false);
AlertDialog.Builder builderh = new AlertDialog.Builder(this);
builderh.setIcon(R.drawable.smile);
builderh.setTitle(R.string.app_nameh);
builderh.setView(messageViewh);
builderh.create();
builderh.show();
break;
}
return true;
}
// Recover the saved state when the activity is recreated.
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageUri = savedInstanceState.getParcelable("ImageUri");
if (mImageUri != null) {
mBitmap = ImageHelper.loadSizeLimitedBitmapFromUri(
mImageUri, getContentResolver());
}
}
// Called when image selection is done.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_SELECT_IMAGE:
if (resultCode == RESULT_OK) {
// If image is selected successfully, set the image URI and bitmap.
mImageUri = data.getData();
mBitmap = ImageHelper.loadSizeLimitedBitmapFromUri(
mImageUri, getContentResolver());
if (mBitmap != null) {
// Show the image on screen.
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageBitmap(mBitmap);
// Add detection log.
addLog("Image: " + mImageUri + " resized to " + mBitmap.getWidth()
+ "x" + mBitmap.getHeight());
}
// Clear the detection result.
FaceListAdapter faceListAdapter = new FaceListAdapter(null);
ListView listView = (ListView) findViewById(R.id.list_detected_faces);
listView.setAdapter(faceListAdapter);
// Clear the information panel.
setInfo("");
// Enable button "detect" as the image is selected and not detected.
setDetectButtonEnabledStatus(true);
}
break;
default:
break;
}
}
// Called when the "Select Image" button is clicked.
public void selectImage(View view) {
Intent intent = new Intent(this, SelectImageActivity.class);
startActivityForResult(intent, REQUEST_SELECT_IMAGE);
}
// Called when the "Detect" button is clicked.
public void detect(View view) {
// Put the image into an input stream for detection.
ByteArrayOutputStream output = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
ByteArrayInputStream inputStream = new ByteArrayInputStream(output.toByteArray());
// Start a background task to detect faces in the image.
new DetectionTask().execute(inputStream);
// Prevent button click during detecting.
setAllButtonsEnabledStatus(false);
}
// View the log of service calls.
public void viewLog(View view) {
Intent intent = new Intent(this, DetectionLogActivity.class);
startActivity(intent);
}
// Show the result on screen when detection is done.
private void setUiAfterDetection(Face[] result, boolean succeed) {
// Detection is done, hide the progress dialog.
mProgressDialog.dismiss();
// Enable all the buttons.
setAllButtonsEnabledStatus(true);
// Disable button "detect" as the image has already been detected.
setDetectButtonEnabledStatus(false);
if (succeed) {
// The information about the detection result.
String detectionResult;
if (result != null) {
detectionResult = result.length + " face"
+ (result.length != 1 ? "s" : "") + " detected";
// Show the detected faces on original image.
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageBitmap(ImageHelper.drawFaceRectanglesOnBitmap(
mBitmap, result, true));
// Set the adapter of the ListView which contains the details of the detected faces.
FaceListAdapter faceListAdapter = new FaceListAdapter(result);
// Show the detailed list of detected faces.
ListView listView = (ListView) findViewById(R.id.list_detected_faces);
listView.setAdapter(faceListAdapter);
} else {
detectionResult = "0 face detected";
}
setInfo(detectionResult);
}
mImageUri = null;
mBitmap = null;
}
// Set whether the buttons are enabled.
private void setDetectButtonEnabledStatus(boolean isEnabled) {
Button detectButton = (Button) findViewById(R.id.detect);
detectButton.setEnabled(isEnabled);
}
// Set whether the buttons are enabled.
private void setAllButtonsEnabledStatus(boolean isEnabled) {
Button selectImageButton = (Button) findViewById(R.id.select_image);
selectImageButton.setEnabled(isEnabled);
Button detectButton = (Button) findViewById(R.id.detect);
detectButton.setEnabled(isEnabled);
// Button ViewLogButton = (Button) findViewById(R.id.view_log);
// ViewLogButton.setEnabled(isEnabled);
}
// Set the information panel on screen.
private void setInfo(String info) {
TextView textView = (TextView) findViewById(R.id.info);
textView.setText(info);
}
// Add a log item.
private void addLog(String log) {
LogHelper.addDetectionLog(log);
}
// The adapter of the GridView which contains the details of the detected faces.
private class FaceListAdapter extends BaseAdapter {
// The detected faces.
List<Face> faces;
// The thumbnails of detected faces.
List<Bitmap> faceThumbnails;
// Initialize with detection result.
FaceListAdapter(Face[] detectionResult) {
faces = new ArrayList<>();
faceThumbnails = new ArrayList<>();
if (detectionResult != null) {
faces = Arrays.asList(detectionResult);
for (Face face : faces) {
try {
// Crop face thumbnail with five main landmarks drawn from original image.
faceThumbnails.add(ImageHelper.generateFaceThumbnail(
mBitmap, face.faceRectangle));
} catch (IOException e) {
// Show the exception when generating face thumbnail fails.
setInfo(e.getMessage());
}
}
}
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public int getCount() {
return faces.size();
}
#Override
public Object getItem(int position) {
return faces.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.item_face_with_description, parent, false);
}
convertView.setId(position);
// Show the face thumbnail.
((ImageView) convertView.findViewById(R.id.face_thumbnail)).setImageBitmap(
faceThumbnails.get(position));
// Show the face details.
String getEmotion;
// String improve = improveMessage(getEmotion);
DecimalFormat formatter = new DecimalFormat("#0.0");
//add
// String message = findMessage(getEmotion());
// String improve = improveMessage(getEmotion);
String face_description = String.format("Emotion: %s\n",
getEmotion(faces.get(position).faceAttributes.emotion)
);
((TextView) convertView.findViewById(R.id.text_detected_face)).setText(face_description);
return convertView;
}
private String getEmotion(Emotion emotion) {
String emotionType = "";
double emotionValue = 0.0;
String emotionInfo = "";
if (emotion.anger > emotionValue) {
emotionValue = emotion.anger;
emotionType = "Anger";
emotionInfo = "If you haven't fed him/her yet maybe this precious one is thirsty or hungry.\n Try giving your attention. If your baby is acting unusual it's best to seek for medical help.";
}
if (emotion.contempt > emotionValue) {
emotionValue = emotion.contempt;
emotionType = "Contempt";
emotionInfo = "You go girl!";
}
if (emotion.disgust > emotionValue) {
emotionValue = emotion.disgust;
emotionType = "Disgust";
emotionInfo = "Look! If your baby is feeling this way mabye she/he doesn't like this. \n If what your doing right now is good for him/her maybe you can support that.";
}
if (emotion.fear > emotionValue) {
emotionValue = emotion.fear;
emotionType = "Fear";
emotionInfo = "Your baby looks somewhat uncomfortable.\n Make your baby feel comfortable and take note of what makes them feel like that. ";
}
if (emotion.happiness > emotionValue) {
emotionValue = emotion.happiness;
emotionType = "Happiness";
emotionInfo = "Just continue what you are doing. It is important to remember what can make them happy. \n";
}
if (emotion.neutral > emotionValue) {
emotionValue = emotion.neutral;
emotionType = "Neutral";
emotionInfo = "Maybe you should just observe first";
}
if (emotion.sadness > emotionValue) {
emotionValue = emotion.sadness;
emotionType = "Sadness";
emotionInfo = "Just cuddle or dandle your baby.";
}
if (emotion.surprise > emotionValue) {
emotionValue = emotion.surprise;
emotionType = "Surprise";
emotionInfo = "Oooh look. Play with your baby. Try doing peek a boo";
}
return String.format("%s: %f \n\n%s", emotionType, emotionValue, emotionInfo);
}
}
}
Just would like to add some images like happy if that is the detected emotion. Please do help me. Any help is highly appreciated. Thank you :)
I would like to add that after the emotionInfo.
I guess detectWithStream is you want.
Official Doc: Faces.detectWithStream Method
From Java SDK, the List<DetectedFace> object will return if successful.
The below code is downloading images from a database showing into an sdcard. When previewing it was showing images. The first image showed perfectly, but from next image onwards it was showing like blank and loading images from the sdcard, but from sdcard it was not downloading image directly displaying images.
java
public class ImageGallery extends Activity {
Bundle bundle;
String catid, temp, responseJson;
JSONObject json;
ImageView imageViewPager;
// for parsing
JSONObject o1, o2;
JSONArray a1, a2;
int k;
Boolean toggleTopBar;
ArrayList<String> imageThumbnails;
ArrayList<String> imageFull;
public static int imagePosition=0;
SubsamplingScaleImageView imageView, imageViewPreview, fullImage ;
ImageView thumb1, back;
private LinearLayout thumb2;
RelativeLayout topLayout, stripeView;
RelativeLayout thumbnailButtons;
FrameLayout gridFrame;
public ImageLoader imageLoader;
//SharedPreferences data
SharedPreferences s1;
SharedPreferences.Editor editor;
int swipeCounter;
ParsingForFinalImages parsingObject;
int position_grid;
SharedPreferences p;
Bitmap bm;
int numOfImagesInsidee;
LinearLayout backLinLayout;
public static boolean isThumb2=false;
public static boolean isThumb1=false;
public static ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
//isThumb2=false;
toggleTopBar = false;
//position_grid=getIntent().getExtras().getInt("position");
thumbnailButtons = (RelativeLayout)findViewById(R.id.thumbnailButtons);
topLayout = (RelativeLayout)findViewById(R.id.topLayout);
//fullImage = (SubsamplingScaleImageView)findViewById(R.id.fullimage);
backLinLayout = (LinearLayout)findViewById(R.id.lin_back);
backLinLayout.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent io = new Intent(getBaseContext(), MainActivity.class);
// clear the previous activity and start a new task
// System.gc();
// io.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(io);
finish();
}
});
ConnectionDetector cd = new ConnectionDetector(getBaseContext());
Boolean isInternetPresent = cd.isConnectingToInternet();
thumb1 = (ImageView)findViewById(R.id.thumb1);
thumb2 = (LinearLayout)findViewById(R.id.thumb2);
stripeView = (RelativeLayout)findViewById(R.id.stripeView) ;
gridFrame = (FrameLayout)findViewById(R.id.gridFrame);
thumb1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
stripeView.setVisibility(View.GONE);
gridFrame.setVisibility(View.VISIBLE);
viewPager.setVisibility(View.GONE);
//fullImage.setVisibility(View.GONE);
thumb1.setClickable(false);
isThumb1=true;
isThumb2=false;
Log.i("Thumb Position 1",""+ImageGallery.imagePosition);
viewPager.removeAllViews();
Fragment newFragment = new GridFragment2();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.gridFrame, newFragment).commit();
}
});
thumb2.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
// stripeView.setVisibility(View.VISIBLE);
stripeView.setVisibility(View.GONE);
gridFrame.setVisibility(View.VISIBLE);
viewPager.setVisibility(View.GONE);
// fullImage.setVisibility(View.GONE);
thumb1.setClickable(true);
isThumb2=true;
isThumb1=false;
Log.i("Thumb Position 2",""+ImageGallery.imagePosition);
viewPager.removeAllViews();
Fragment newFragment = new ImageStripeFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.gridFrame, newFragment).commit();
}
});
// allow networking on main thread
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/*bundle = getIntent().getExtras();
catid = bundle.getString("catid");*/
// Toast.makeText(getBaseContext(), catid, Toast.LENGTH_LONG).show();
// making json using the catalogue id we got
p = getSharedPreferences("gridData", Context.MODE_APPEND);
catid = p.getString("SelectedCatalogueIdFromGrid1", "");
int clickedListPos = p.getInt("clickedPosition", 0);
imageViewPreview = (SubsamplingScaleImageView)findViewById(R.id.preview);
imageThumbnails = new ArrayList<String>();
imageFull = new ArrayList<String>();
s1 = this.getSharedPreferences("data", Context.MODE_APPEND);
editor = s1.edit();
Log.d("catidfnl", catid);
numOfImagesInsidee = p.getInt("numberOfItemsSelectedFromGrid1", 0);
Log.d("blingbling2", String.valueOf(numOfImagesInsidee));
// adding downloaded images to arraylist
for(int m=0;m<numOfImagesInsidee;m++){
imageThumbnails.add(Environment.getExternalStorageDirectory()+"/"+"thumbImage" + catid + m+".png");
imageFull.add(Environment.getExternalStorageDirectory()+"/"+"fullImage" + catid + m+".png");
// imageFull.add("file://" + Environment.getExternalStorageDirectory() + "/" + "fullImage32.png");
}
viewPager = (ViewPager) findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);
// code to display image in a horizontal strip starts here
LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
for (int i = 0; i < imageThumbnails.size(); i++) {
imageView = new SubsamplingScaleImageView(this);
imageView.setId(i);
imageView.setPadding(2, 2, 2, 2);
// Picasso.with(this).load("file://"+imageThumbnails.get(i)).into(imageView);
// imageView.setScaleType(ImageView.ScaleType.FIT_XY);
layout.addView(imageView);
ViewGroup.LayoutParams params = imageView.getLayoutParams();
params.width = 200;
params.height = 200;
imageView.setLayoutParams(params);
imageView.setZoomEnabled(false);
imageView.setDoubleTapZoomScale(0);
imageView.setImage(ImageSource.uri(imageThumbnails.get(0)));
imageView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
imageView.setZoomEnabled(false);
imageViewPreview.setImage(ImageSource.uri(imageFull.get(view.getId())));
imageView.recycle();
imageViewPreview.recycle();
}
});
}
// code to display image in a horizontal strip ends here
imageViewPreview.setZoomEnabled(false);
/*imageViewPreview.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
imageViewPreview.setZoomEnabled(false);
stripeView.setVisibility(View.GONE);
gridFrame.setVisibility(View.GONE);
viewPager.setVisibility(View.VISIBLE);
}
});*/
imageViewPreview.setOnClickListener(new DoubleClickListener() {
#Override
public void onSingleClick(View v) {
Log.d("yo click", "single");
}
#Override
public void onDoubleClick(View v) {
Log.d("yo click", "double");
}
});
}
public abstract class DoubleClickListener implements View.OnClickListener {
private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds
long lastClickTime = 0;
#Override
public void onClick(View v) {
long clickTime = System.currentTimeMillis();
if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
onDoubleClick(v);
} else {
onSingleClick(v);
}
lastClickTime = clickTime;
}
public abstract void onSingleClick(View v);
public abstract void onDoubleClick(View v);
}
// #Override
// public void onBackPressed() {
// Intent io = new Intent(getBaseContext(), MainActivity.class);
// // clear the previous activity and start a new task
// super.onBackPressed();
// finish();
// // System.gc();
// // io.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// startActivity(io);
// }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_image_gallery, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
/* private int[] mImages = new int[] {
R.drawable.scroll3,
R.drawable.scroll1,
R.drawable.scroll2,
R.drawable.scroll4
};*/
/* private String[] description=new String[]
{
"One","two","three","four"
};
*/
#Override
public int getCount() {
Log.i("Image List Size", "" + imageFull.size());
return imageFull.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((SubsamplingScaleImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = ImageGallery.this;
// ImageLoader loader = new ImageLoader(context, 1);
// loader.DisplayImage(ImageSource.uri(imageFull.get(imagePosition)),imageView,imagePosition,new ProgressDialog(context));
SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);
// for placeholder
// fullImage.setImage(ImageSource.resource(R.drawable.tan2x));
if(!GridFragment2.isSelectedGrid2&&!ImageStripeFragment.isImageStripe) {
imagePosition = position;
fullImage.setImage(ImageSource.uri(imageFull.get(imagePosition)));
}
/* else if(!ImageStripeFragment.isImageStripe)
{
imagePosition = position;
fullImage.setImage(ImageSource.uri(imageFull.get(imagePosition)));
}
else if(ImageStripeFragment.isImageStripe)
{
position=imagePosition;
viewPager.setCurrentItem(imagePosition);
fullImage.setImage(ImageSource.uri(imageFull.get(position)));
}*/
else
{
position=imagePosition;
viewPager.setCurrentItem(imagePosition);
fullImage.setImage(ImageSource.uri(imageFull.get(position)));
//viewPager.removeAllViews();
}
// ImageView imageViewPager = new ImageView(context);
// ImageView imageViewPager = new ImageView(getApplicationContext());
// SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);
GridFragment2.isSelectedGrid2=false;
ImageStripeFragment.isImageStripe=false;
// Log.i("Image Resource", "" + ImageSource.uri(imageFull.get(position)));
// imageViewPager.setImageBitmap(BitmapFactory.decodeFile(imageFull.get(position)));
// imageViewPager.setImageBitmap(myBitmap);
// fullImage.setImage(ImageSource.bitmap(bmImg));
//imageView.setImageResource(Integer.parseInt(imageFull.get(position)));
/*int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);*/
/*imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(Integer.parseInt(imageFull.get(position)));
if(position==3)
{
}*/
// Log.i("Image Position",""+position);
/*text.setText(description[position]);
Log.i("Text Position",""+position);*/
/*switch(position)
{
case 0:
String pos=String.valueOf(position);
text.setText(pos);
break;
case 1:
String pos1=String.valueOf(position);
text.setText(pos1);
break;
case 2:
String pos2=String.valueOf(position);
text.setText(pos2);
break;
case 3:
String pos3=String.valueOf(position);
text.setText(pos3);
break;
}*/
fullImage.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
if (toggleTopBar == false) {
// thumbnailButtons.setVisibility(View.GONE);
thumbnailButtons.animate()
.translationY(-2000)
.setDuration(1000)
.start();
toggleTopBar = true;
} else if (toggleTopBar == true) {
// thumbnailButtons.setVisibility(View.VISIBLE);
thumbnailButtons.animate()
.translationY(0)
.setDuration(1000)
.start();
toggleTopBar = false;
}
}
});
((ViewPager) container).addView(fullImage, 0);
return fullImage;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((SubsamplingScaleImageView) object);
}
/* #Override
public void destroyItem(View collection, int position, Object o) {
Log.d("DESTROY", "destroying view at position " + position);
View view = (View) o;
((ViewPager) collection).removeView(view);
view = null;
}*/
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
This will be the best approach for your Solution,Try using Universal Image Loader.
Features:
Multithread image loading (async or sync)
Wide customization of ImageLoader's configuration (thread executors, downloader, decoder, memory and disk cache, display image options, etc.)
Many customization options for every display image call (stub images, caching switch, decoding options, Bitmap processing and displaying, etc.)
Image caching in memory and/or on disk (device's file system or SD card)
Listening loading process (including downloading progress)
Find link here : https://github.com/nostra13/Android-Universal-Image-Loader
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.
Hello stackoverflow users,
I have a problem, I have a variable named counter that is inscrementing or decrementing by 2 buttons, this variable is displayed with 2 TextViews.The problem is that the variable need to be setted local not global ( global is working, but I use inflation to duplicate the layer many times, if he is global, when I increment or decrement the value of a layout he modify in every layout )
The error is this:
Description Resource Path Location Type
Cannot refer to a non-final variable counter inside an inner class defined in a different method Tabel.java /Instances_temperature/src/com/example/instances_temperature line 67 Java Problem
Line 67 would be this:
if( mAutoIncrement && counter < 35)
If I set the variable final it can't be accesed by decrementing ( counter-- ) or incrementing ( counter++ )
Hope I explained the program how it work for the moment, thank you for your helping.
Below is my code of the java file:
public class Tabel extends ActionBarActivity {
int i;
int value; // Ignore this, this is the number that is taked from mainactivity for Inflation
//int counter=20; // counter default value for start = 20
static int REP_DELAY = 50; // Constant value for long click update
private Handler repeatUpdateHandler = new Handler();
private boolean mAutoIncrement = false;
private boolean mAutoDecrement = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabel);
Intent intentObject = getIntent();
value = intentObject.getIntExtra("max", 0);
LinearLayout layout = (LinearLayout)findViewById(R.id.container2);
for(i=1;i<=value;i++)
{
LayoutInflater layoutinflate = null;
layoutinflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowview = layoutinflate.inflate( R.layout.inflation_layout, null);
Button add,sub;
final TextView display;
final TextView showup;
int counter = 20;
add = (Button) rowview.findViewById(R.id.plus);
sub = (Button) rowview.findViewById(R.id.minus);
display = (TextView) rowview.findViewById(R.id.showtemp);
showup = (TextView) rowview.findViewById(R.id.showvalue);
class RptUpdater implements Runnable {
public void run() {
if( mAutoIncrement && counter < 35){
//increment();
if(counter<35)
{
counter++;
display.setText( "" + counter+"°C");
showup.setText(" "+counter+"°C ");
}
else
{
Context context = getApplicationContext();
CharSequence text = "Maximum value is 35°C!";
int duration = Toast.LENGTH_SHORT;
final Toast toast = Toast.makeText(context, text, duration);
toast.show();
toast.setGravity(Gravity.TOP, 0, 100);
}
repeatUpdateHandler.postDelayed( new RptUpdater(), REP_DELAY );
}
else
if( mAutoDecrement && counter > 10){
// decrement();
if(counter>10)
{
counter--;
display.setText( "" + counter+"°C");
showup.setText(" "+counter+"°C ");
repeatUpdateHandler.postDelayed( new RptUpdater(), REP_DELAY );
}
else
{
Context context = getApplicationContext();
CharSequence text = "Minimum value is 10°C!";
int duration = Toast.LENGTH_SHORT;
final Toast toast = Toast.makeText(context, text, duration);
toast.show();
toast.setGravity(Gravity.BOTTOM, 0, 50);
}
}
}
}
showup.setText(" "+counter+"°C ");
display.setText(""+counter+"°C");
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(counter<35){
counter++;
display.setText( "" + counter+"°C ");
showup.setText(" "+counter+"°C ");
}
else{
Context context = getApplicationContext();
CharSequence text = "Maximum value is 35°C!";
int duration = Toast.LENGTH_SHORT;
final Toast toast = Toast.makeText(context, text, duration);
toast.show();
toast.setGravity(Gravity.TOP, 0, 100);
}
}
});
sub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(counter>10){
counter--;
display.setText( "" + counter+"°C");
showup.setText(" "+counter+"°C ");
}
else{
Context context = getApplicationContext();
CharSequence text = "Minimum value is 10°C!";
int duration = Toast.LENGTH_SHORT;
final Toast toast = Toast.makeText(context, text, duration);
toast.show();
toast.setGravity(Gravity.BOTTOM, 0, 50);
}
}
});
add.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
mAutoIncrement = true;
repeatUpdateHandler.post(new RptUpdater() );
return false;
}
});
add.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if( (event.getAction()==MotionEvent.ACTION_UP || event.getAction()==MotionEvent.ACTION_CANCEL) && mAutoIncrement )
mAutoIncrement = false;
return false;
}
});
sub.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
mAutoDecrement = true;
repeatUpdateHandler.post(new RptUpdater() );
return false;
}
});
sub.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if( (event.getAction()==MotionEvent.ACTION_UP || event.getAction()==MotionEvent.ACTION_CANCEL) && mAutoDecrement )
mAutoDecrement = false;
return false;
}
});
layout.addView(rowview);
}
//showvalue.setText(String.valueOf(getIntent().getExtras().getInt("max")));
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tabel, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tabel,
container, false);
return rootView;
}
}
protected void onSaveInstanceState(Bundle savedInstance) {
super.onSaveInstanceState(savedInstance);
//savedInstance.putInt("myCounter",counter);
}
}
If you want a dirty fix. Make counter a final int[] counter = {20} and then when you want to access it just call counter[0]
Use AtomicInteger rather than int. This means you can set the variable to be final, and still increment it by calling methods on it.
it is the Java specification.
why not keep a "counter" filed in RptUpdater class.
the variables that you want to use , which android says to make it final .
declare those variables here.
than android will not give warning to make it as final
public class Tabel extends ActionBarActivity {
int counter = 20;
TextView display;
TextView showup;
First off, apologies, I'm new to all this and I'm struggling with Android / Java. Ive spent days looking stuff up and I KNOW I'm doing something stupid but would appreciate someone to tell me why / where I'm going wrong.
The app is a simple quiz, puts a picture up, use a spinner to select the answer, press a button to submit, get a toast message to verify and add a score. I know the code is horrendous and a hack but I lack the knowledge to do it more elegantly (part of the reason I'm here). I am trying to place a while loop, using the variable sflags that will be counting up from 0 to 26. When I place it, I can never seem to place it correctly so it works. I suspect some of the code gets broken when I try and wrap it.
Here's the (terrible) code :
public class MainActivity extends Activity implements TextWatcher {
private static final String TAG = "MainActivity";
private EditText mName;
private EditText mEmail;
private ListView countrieslist;
private String comments;
private int score = 0;
private int sflags = 0;
private String emailok;
private String answer;
private String flags;
private Spinner spinnerct;
private Object countries;
// private AdapterView<ListAdapter> spinnerct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countries = getResources().getStringArray(R.array.flagnames);
mName = (EditText) findViewById(R.id.name);
mEmail = (EditText) findViewById(R.id.email);
mEmail.addTextChangedListener(this);
}
#Override
public void afterTextChanged(Editable s) {
emailok = s.toString();
String sub_but = getString(R.string.sub_but);
boolean valid = emailok.length() > 0 &&
emailok.toLowerCase().indexOf(sub_but) == -1;
View view = findViewById(R.id.imageButton1);
boolean isVisible = view.getVisibility() == View.VISIBLE;
if (isVisible == valid) {
// No animation required if both values are true or both values are
// false
return;
}
Animation anim;
if (valid) {
view.setVisibility(View.VISIBLE);
// Create a new animation object
anim = AnimationUtils.makeInAnimation(this, true);
} else {
// Create a new animation object
anim = AnimationUtils.makeOutAnimation(this, true);
view.setVisibility(View.INVISIBLE);
}
// Tell the view it's time to start animating
view.startAnimation(anim);
}
public void thequiz(View view) {
setContentView(R.layout.activity_quiz);
Toast.makeText(
this.getApplicationContext(),
"Thanks ! Now try to identify the flags of these European Countries!",
Toast.LENGTH_LONG
).show();
sflags = 0;
score = 0;
// LinearLayOut Setup
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// ImageView Setup
ImageView imageView = new ImageView(this);
// Constructing the filename using "flag" + the item number from
// variable loop
// using GetIndentifier to return resource to a string
// while loop start here?
//while (sflags<27){
// display correct flag
imageView.setImageResource(
this.getResources().getIdentifier("drawable/flag" + sflags, null, this.getPackageName())
);
// setting image position
imageView.setLayoutParams(
new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
);
// =================================================================
// creating spinner object
final Spinner spinnerct = new Spinner(this);
// Now to populate spinner with contents of array flagnames[]
ArrayAdapter<String> spinnercountry = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.flagnames)
);
spinnerct.setAdapter(spinnercountry);
// creating button
Button myButton = new Button(this);
myButton.setText("Submit Answer");
myButton.setBackgroundColor(Color.rgb(250, 200, 250));
// ===================================================================
// adding view to layout
linearLayout.addView(imageView);
linearLayout.addView(spinnerct);
linearLayout.addView(myButton);
// Show layout
setContentView(linearLayout);
// OnclickListener to see when button is clicked
//=========================================================
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
answer = spinnerct.getSelectedItem().toString();
Toast.makeText(
MainActivity.this,
"You selected " + answer,
Toast.LENGTH_SHORT
).show();
// now check the answer is right by calling checkanswer()
//=======================================================
boolean tester = false;
checkanswer(tester); // jumps to procedure, returns boolean
if (tester = true) {
score = score + 1;
Toast.makeText(
MainActivity.this,
"Well done, correct answer! Your Score is " + score + " out of 27",
Toast.LENGTH_LONG
).show();
}
//========================================================
if (tester != true) {
Toast.makeText(
MainActivity.this,
"Sorry wrong answer! ",
Toast.LENGTH_SHORT
).show();
}
//=========================================================
sflags = sflags + 1;
}
});
};
// sendSMS();
// sendEmail();
// }
//=======================================================
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
//========================================================
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
//=========================================================
public void checkanswer(boolean Isitright) {
if (sflags == 0 && answer == "Estonia") {
Isitright = true;
}
}
//=======================================================
}