I have a drag and drop game. The user should choose the correct shape to drag and drop onto the box. I followed this tutorial here When the user has dragged the wrong object, it won't be displaying WRONG ANSWER yet. The warning should displayed when he drops it onto the basket object. I have tried this:
TextView objBasket, tx, timer;
int trial = 0;
TextView obj[] = new TextView[4];
int[] images = {
R.drawable.stage4_object1, // Correct Answer a
R.drawable.stage4_object2,
R.drawable.stage4_object3,
R.drawable.stage4_object4
};
List<TextView> iv = new ArrayList<TextView>();
String[] tagList = {"a","b","c","d"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.stage4_1);
// I created a custom countdown timer c/o Say
counter = new MyCount(30000,1000);
counter.start();
initControls();
getCorrectObject();
}
private void getCorrectObject() {
// TODO Auto-generated method stub
List<Integer> objects = new ArrayList<Integer>();
for(int arr : images){
objects.add(arr);
}
// Shuffle the collection
Collections.shuffle(objects);
iv.add((TextView) findViewById(R.id.txtStage4_object1));
iv.add((TextView) findViewById(R.id.txtStage4_object2));
iv.add((TextView) findViewById(R.id.txtStage4_object3));
iv.add((TextView) findViewById(R.id.txtStage4_object4));
Collections.shuffle(iv);
iv.get(0).setBackgroundResource(images[0]);
iv.get(1).setBackgroundResource(images[1]);
iv.get(2).setBackgroundResource(images[2]);
iv.get(3).setBackgroundResource(images[3]);
iv.get(0).setOnTouchListener(new ChoiceTouchListener());
iv.get(1).setOnTouchListener(new ChoiceTouchListener());
iv.get(2).setOnTouchListener(new ChoiceTouchListener());
iv.get(3).setOnTouchListener(new ChoiceTouchListener());
for (int i = 0; i < tagList.length; i++) {
iv.get(i).setTag(tagList[i]);
}
}
#SuppressLint("NewApi")
private class ChoiceTouchListener implements OnTouchListener {
#SuppressLint("NewApi")
#Override
public boolean onTouch(View v, MotionEvent motionEvent) {
// TODO Auto-generated method stub
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
//setup drag
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
//start dragging the item touched
v.startDrag(data, shadowBuilder, v, 0);
return true;
}
else {
return false;
}
}
}
#SuppressLint("NewApi")
private class ChoiceDragListener implements OnDragListener {
#Override
public boolean onDrag(View v, DragEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
//no action necessary
break;
case DragEvent.ACTION_DRAG_ENTERED:
//no action necessary
break;
case DragEvent.ACTION_DRAG_EXITED:
//no action necessary
break;
case DragEvent.ACTION_DROP:
//handle the dragged view being dropped over a drop view
View view = (View) event.getLocalState();
//stop displaying the view where it was before it was dragged
view.setVisibility(View.INVISIBLE);
//view dragged item is being dropped on
TextView dropTarget = (TextView) v;
//view being dragged and dropped
TextView dropped = (TextView) view;
for (int i = 0; i < iv.size(); i++) {
final int k = i;
String tmp = "a";
if (tmp.equals(iv.get(k).getTag())) {
Log.i("result","CORRECT ANSWER: "+ tmp);
goToNextQuestion();
} else {
Log.i("result","WRONG ANSWER: "+ iv.get(k).getTag());
trial++;
guessedWrong();
playWrongSound();
}
}
break;
case DragEvent.ACTION_DRAG_ENDED:
//no action necessary
break;
default:
break;
}
return true;
}
}
But it won't go to the next question whenever I choose the correct object. What am I missing in here? I really need help to finish this game. Thanks in advance.
I think that I see two problems with your program.
You created your ChoiceDragListener class but you didn't register it with any of those items you wish to drag around. This appears to be missing from your getCorrectObject method.
iv.get(0).setOnDragListener(new ChoiceDragListener ());
iv.get(1).setOnDragListener(new ChoiceDragListener ());
iv.get(2).setOnDragListener(new ChoiceDragListener ());
iv.get(3).setOnDragListener(new ChoiceDragListener ());
The other problem that I see is with your ACTION_DROP case from your switch statement. First you get the TextView that the user has dropped but then you begin to cycle through all of your text views anyways. The code inside the ACTION_DROP case should look more like:
View view = (View) event.getLocalState();
view.setVisibility(View.INVISIBLE);
TextView dropTarget = (TextView) v;
TextView dropped = (TextView) view;
String temp = "a";
if(temp.equals(view.getTag()){
goToNextQuestion();
}else{
guessedWrong()
}
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.
I have been looking all over SOF and online tutorials, but for some reason I still can't get it to work. I want to implement a drag and drop functionality in my game. Here is the activity:
I want to be able to drag and drop the 4 shapes in the bottom. If the correct shape fits, I want the shape with the "?" to change into the correct shape. Can someone show me how I can do this?
Here is my code:
public class SecondActivity extends AppCompatActivity {
int n;
ImageView shape1, shape2, shape3, shape4, guessShape;
ImageButton exit;
private android.widget.RelativeLayout.LayoutParams layoutParams;
Random rand = new Random();
ImageView[] shapes = new ImageView[4];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//declare each imageview
shape1 = (ImageView) findViewById(R.id.shape1);
shape2 = (ImageView) findViewById(R.id.shape2);
shape3 = (ImageView) findViewById(R.id.shape3);
shape4 = (ImageView) findViewById(R.id.shape4);
guessShape = (ImageView) findViewById(R.id.guessShape);
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
});
//add each imageView to the shapes[] array
shapes[0] = shape1;
shapes[1] = shape2;
shapes[2] = shape3;
shapes[3] = shape4;
//store all the shapes in an array
int[] images = new int[]{R.drawable.img_0, R.drawable.img_1, R.drawable.img_2, R.drawable.img_3, R.drawable.img_4,
R.drawable.img_5, R.drawable.img_6, R.drawable.img_7, R.drawable.img_8, R.drawable.img_9, R.drawable.img_10,
R.drawable.img_11, R.drawable.img_12, R.drawable.img_13, R.drawable.img_14, R.drawable.img_15, R.drawable.img_16,
R.drawable.img_17};
//store all the guessShapes in an array
int[] outlines = new int[]{R.drawable.outline_0, R.drawable.outline_1, R.drawable.outline_2,
R.drawable.outline_3, R.drawable.outline_4, R.drawable.outline_5, R.drawable.outline_6,
R.drawable.outline_7, R.drawable.outline_8, R.drawable.outline_9, R.drawable.outline_10,
R.drawable.outline_11, R.drawable.outline_12, R.drawable.outline_13, R.drawable.outline_14,
R.drawable.outline_15, R.drawable.outline_16, R.drawable.outline_17};
//generate 4 random images from the array's and ensure that they don't match each other
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 18; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
int whichImg = (int) Math.round((Math.random() * 4));
int img1 = list.get(0);
int img2 = list.get(1);
int img3 = list.get(2);
int img4 = list.get(3);
if (whichImg == 1) {
whichImg = img1;
} else if (whichImg == 2) {
whichImg = img2;
} else if (whichImg == 3) {
whichImg = img3;
} else {
whichImg = img4;
}
int outlineID = outlines[whichImg];
//set the shape in each imageview
guessShape.setBackgroundResource(outlineID);
shape1.setBackgroundResource(images[img1]);
shape2.setBackgroundResource(images[img2]);
shape3.setBackgroundResource(images[img3]);
shape4.setBackgroundResource(images[img4]);
//ensures that 1/4 shape has the guess shape correspondence
final Object currentBackground = guessShape.getBackground().getConstantState();
//for loop to have the guess shape and 1/4 shapes to match
for (int i = 0; i < 18; i++) {
if (currentBackground.equals(getResourceID("outline_" + i, "drawable", getApplicationContext()))) {
int random = new Random().nextInt(shapes.length);
shapes[random].setBackgroundResource(getResourceID("img_" + i, "drawable", getApplicationContext()));
}
//set tags for each view
guessShape.setTag("gShape");
shape1.setTag("S_1");
shape2.setTag("S_2");
shape3.setTag("S_3");
shape4.setTag("S_4");
}
}
//method to get the ID of an image in drawable folder
protected final static int getResourceID(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
}
Although you were not clear enough.
Try this, First make a class that implements onTouchListener
private final class MyTouchListener implements OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(
view);
view.startDrag(data, shadowBuilder, view, 0);
view.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
}
Then define a drag listener
class MyDragListener implements OnDragListener {
Drawable enterShape = getResources().getDrawable(
R.drawable.shape_droptarget);
Drawable normalShape = getResources().getDrawable(R.drawable.shape);
#Override
public boolean onDrag(View v, DragEvent event) {
int action = event.getAction();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// do nothing
break;
case DragEvent.ACTION_DRAG_ENTERED:
v.setBackgroundDrawable(enterShape);
break;
case DragEvent.ACTION_DRAG_EXITED:
v.setBackgroundDrawable(normalShape);
break;
case DragEvent.ACTION_DROP:
// Dropped, reassign View to ViewGroup
View view = (View) event.getLocalState();
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
LinearLayout container = (LinearLayout) v;
container.addView(view);
view.setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_ENDED:
v.setBackgroundDrawable(normalShape);
default:
break;
}
return true;
}
}
Now simply use these lines
findViewById(R.id.myimage1).setOnTouchListener(new MyTouchListener());
and
findViewById(R.id.bottomleft).setOnDragListener(new MyDragListener());
Here are some tutorials that might help you
Tutorialpoint
Link 2
could really do with some help.
I have a random number of buttons being created on the fly and each button is setOnTouchListener, which looks to be working fine. The buttons are added to Linearlayout (Top) and there is another empty Linearlayout (Bottom).
I want to be able to do the following:
Drag & Drop buttons between Linearlayout (Top) & Linearlayout (Bottom)
public class GetString extends Activity{
myDragEventListener mDragListen = new myDragEventListener();
public void getString(Context context, String[] temp, int no, LinearLayout words1, LinearLayout words2) {
Button bt;
int i = 0;
for (i = 0; i < no; i++) {
bt = new Button(context);
bt.setId(i);
bt.setText(temp[i]);
bt.setOnTouchListener(new MyTouchListener());
words1.addView(bt);
bt.setOnDragListener(mDragListen);
}
}
protected class myDragEventListener implements View.OnDragListener {
public boolean onDrag(View v, DragEvent event) {
// Defines a variable to store the action type for the incoming event
final int action = event.getAction();
// Handles each of the expected events
switch(action) {
case DragEvent.ACTION_DRAG_STARTED:
return false;
case DragEvent.ACTION_DRAG_ENTERED:
v.invalidate();
return true;
case DragEvent.ACTION_DRAG_LOCATION:
return true;
case DragEvent.ACTION_DRAG_EXITED:
v.invalidate();
return true;
case DragEvent.ACTION_DROP:
return true;
case DragEvent.ACTION_DRAG_ENDED:
return true;
// An unknown action type was received.
default:
Log.e("DragDrop Example", "Unknown action type received by OnDragListener.");
break;
}
return false;
}
}
public class MyTouchListener implements View.OnTouchListener {
#Override
public boolean onTouch(View v, MotionEvent arg1) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadow = new View.DragShadowBuilder(v);
v.startDrag(data, shadow, null, 0);
return false;
}
}
}
Very new to android java programming. I created a car payment calculator application for one of my classes and I am trying to create a checkbox that the user can check so that all the values stored in the TextViews and EditViews remain the same when the application is opened again.
Here is my activity:
public class MainActivity extends Activity implements OnClickListener,
OnEditorActionListener, OnItemSelectedListener, OnFocusChangeListener,
OnCheckedChangeListener {
private TextView payment;
private TextView interest;
private EditText principle;
private TextView interestText;
private CheckBox interestBox;
private EditText years;
private TextView apr;
Button plusbutton;
Button minusbutton;
private static String TAG = "CAR";
private Spinner period;
private double aprPercent;
private int t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate");
this.getReferences();
this.setListeners();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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);
}
public void getReferences() {
payment = (TextView) findViewById(R.id.paymentLabel);
interest = (TextView) findViewById(R.id.interestLabel);
apr = (TextView) findViewById(R.id.aprLabel);
aprPercent = Double.parseDouble(apr.getText().toString());
interestText = (TextView) findViewById(R.id.interestText);
interestBox = (CheckBox) findViewById(R.id.checkBox1);
interestBox.setChecked(false);
principle = (EditText) findViewById(R.id.principleEditText);
years = (EditText) findViewById(R.id.yearsEditText);
period = (Spinner) findViewById(R.id.spinner1);
minusbutton = (Button) findViewById(R.id.minusbutton);
plusbutton = (Button) findViewById(R.id.plusbutton);
ArrayAdapter<CharSequence> adapter = ArrayAdapter
.createFromResource(this, R.array.split_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
period.setAdapter(adapter);
// principle.setOnFocusChangeListener(this);
Log.d(TAG, "getReferences principle: " + principle.getText()
+ " years:" + years.getText());
}
public void setListeners() { // where the event being consumed will be
// responding
principle.setOnFocusChangeListener(this);
principle.setOnEditorActionListener(this);
years.setOnFocusChangeListener(this);
years.setOnEditorActionListener(this);
interestBox.setOnCheckedChangeListener(this);
period.setOnItemSelectedListener(this);
Log.d(TAG, "setListeners principle: " + principle.getText() + " years:"
+ years.getText());
}
public void setPeriodValue() {
if (period.getSelectedItem().toString().equalsIgnoreCase("Monthly")) {
t = 12;
} else if (period.getSelectedItem().toString()
.equalsIgnoreCase("Quarterly")) {
t = 4;
} else if (period.getSelectedItem().toString()
.equalsIgnoreCase("Annually")) {
t = 1;
}
}
public void updateResults() {
double dblPrinciple = Double
.parseDouble(principle.getText().toString());
double dblYears = Double.parseDouble(years.getText().toString());
double num, denom, dblPayment;
double r = aprPercent / 100;
NumberFormat nf = NumberFormat.getNumberInstance();
NumberFormat curr = NumberFormat.getCurrencyInstance();
apr.setText(nf.format(aprPercent));
setPeriodValue();
num = (r / t);
denom = (1 - Math.pow((1 + num), (t * -dblYears)));
dblPayment = dblPrinciple * (num / denom);
payment.setText(curr.format(dblPayment));
interest.setText(curr
.format((dblPayment * t * dblYears) - dblPrinciple));
}
public void onFocusChange(View v, boolean hasfocus) {
Log.d(TAG, "Focus Change principle: " + principle.getText() + " years"
+ years.getText());
switch (v.getId()) {
case R.id.principleEditText:
case R.id.yearsEditText:
updateResults();
default:
updateResults();
}
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(interestBox.isChecked()) {
interest.setVisibility(View.VISIBLE);
interestText.setVisibility(View.VISIBLE);
}
else {
interest.setVisibility(View.INVISIBLE);
interestText.setVisibility(View.INVISIBLE);
}
if (interestBox.isChecked()!=true){
interest.setVisibility(View.INVISIBLE);
interestText.setVisibility(View.INVISIBLE);
}
else {
interest.setVisibility(View.VISIBLE);
interestText.setVisibility(View.VISIBLE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
updateResults();
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
updateResults();
return false;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.minusbutton:
if (aprPercent == 1) {
break;
} else {
aprPercent = aprPercent - 1.0;
updateResults();
break;
}
case R.id.plusbutton:
if (aprPercent == 20) {
break;
} else {
aprPercent = aprPercent + 1.0;
updateResults();
break;
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
updateResults();
}
My guess is that I have to do something with sharedprefs but I'm not exactly sure how to go about it. Any push in the right direction would be great. thank you.
Use getSharedPreferences(...).edit().putString(...).commit() to store values in "onPause()" and again use getSharedPreferences(...).getString(...) to retrieve information in your "onResume()". It's just that easy.
You will have to read how to save your Activity data. In my opinion you should not use checkbox to save this data but save it by default.
To save your data while the screen rotate you will have to check the OnSaveInstanceState and OnRestoreInstanceState like in this post. It will handle the data when rotated too.
To save your data for a longer time (changing of applications, closing application), You will have to use the Android preferences but check how works the lifecycle of an Activity. Basically you will need to save in the OnPause or OnDestroy and reload it in the OnResume or OnCreate.
Concerning the preferences you have a nice tutorial on the Vogella Website
//Get Data
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
String url = settings.getString("url", "n/a");
//Save Data
Editor edit = preferences.edit();
edit.putString("username", "new_value_for_user");
edit.apply();
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;
}
}
//=======================================================
}