How To Get Position's Value from ArrayList - java

I m displaying Image and name From ArrayList>
on View I want to get Position value From The view
profileimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
use=arraylist.get(i).get("User_Id");
new userbyid().execute();
}
});
i m getting Like this In Array List But Its Always giving Same id On image Click
I want to get Value Of view position
here is setimage fuction Where i m displaying image and name
public void settheimage(int j)
{
for (i = j; i < j+10; i++)
{
LayoutInflater inflate = (LayoutInflater)getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View m_view = inflate.inflate(R.layout.custom_layout, null);
ImageView m_image = (ImageView) m_view.findViewById(R.id.sp_image);
LinearLayout m_topLayout = (LinearLayout) m_view.findViewById(R.id.sp_color);
tempusername=(TextView)m_view.findViewById(R.id.username);
ImageView profileimage=(ImageView)m_view.findViewById(R.id.profileimage);
LinearLayout m_bottomLayout = (LinearLayout) m_view.findViewById(R.id.sp_linh);
//final RelativeLayout myRelView = new RelativeLayout(this);
m_view.setLayoutParams(new LayoutParams((windowwidth - 80), 450));
m_view.setX(40);
m_view.setY(40);
m_view.setTag(i);
Image=arraylist.get(i).get("User_Image");
tempuser_id=arraylist.get(i).get("User_Id");
username=arraylist.get(i).get("FirstName");
tempusername.setText(username);
Picasso.with(getActivity()).load(Image).into(m_image);
// m_image.setBackgroundResource(myImageList[i]);
if (i == 0) {
m_view.setRotation(-1);
} else if (i == 1) {
m_view.setRotation(-5);
} else if (i == 2) {
m_view.setRotation(3);
} else if (i == 3) {
m_view.setRotation(7);
} else if (i == 4) {
m_view.setRotation(-2);
} else if (i == 5) {
m_view.setRotation(5);
}
// ADD dynamically like button on image.
final Button imageLike = new Button(getActivity());
imageLike.setLayoutParams(new LayoutParams(100, 50));
imageLike.setBackgroundDrawable(getResources().getDrawable(R.drawable.like));
imageLike.setX(20);
imageLike.setY(-250);
imageLike.setAlpha(alphaValue);
m_topLayout.addView(imageLike);
// ADD dynamically dislike button on image.
final Button imagePass = new Button(getActivity());
imagePass.setLayoutParams(new LayoutParams(100, 50));
imagePass.setBackgroundDrawable(getResources().getDrawable(R.drawable.dislike));
imagePass.setX(260);
imagePass.setY(-300);
imagePass.setAlpha(alphaValue);
m_topLayout.addView(imagePass);
profileimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
use=arraylist.get(i).get("User_Id");
new userbyid().execute();
}
});
m_topLayout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
x_cord = (int) event.getRawX();
y_cord = (int) event.getRawY();
/* m_view.setX(x_cord - screenCenter + 40);
m_view.setY(y_cord - 150);*/
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x = (int) event.getX();
y = (int) event.getY();
Log.v("On touch", x + " " + y);
break;
case MotionEvent.ACTION_MOVE:
x_cord = (int) event.getRawX(); // Updated for more
// smoother animation.
y_cord = (int) event.getRawY();
m_view.setX(x_cord - x);
m_view.setY(y_cord - y);
// m_view.setY(y_cord-y);
// y_cord = (int) event.getRawY();
// m_view.setX(x_cord - screenCenter + 40);
// m_view.setY(y_cord - 150);
if (x_cord >= screenCenter) {
m_view.setRotation((float) ((x_cord - screenCenter) * (Math.PI / 32)));
if (x_cord > (screenCenter + (screenCenter / 2))) {
imageLike.setAlpha(1);
if (x_cord > (windowwidth - (screenCenter / 4))) {
Likes = 2;
} else {
Likes = 0;
}
} else {
Likes = 0;
imageLike.setAlpha(0);
}
imagePass.setAlpha(0);
} else {
// rotate
m_view.setRotation((float) ((x_cord - screenCenter) * (Math.PI / 32)));
if (x_cord < (screenCenter / 2)) {
imagePass.setAlpha(1);
if (x_cord < screenCenter / 4) {
Likes = 1;
} else {
Likes = 0;
}
} else {
Likes = 0;
imagePass.setAlpha(0);
}
imageLike.setAlpha(0);
}
break;
case MotionEvent.ACTION_UP:
x_cord = (int) event.getRawX();
y_cord = (int) event.getRawY();
Log.e("X Point", "" + x_cord + " , Y " + y_cord);
imagePass.setAlpha(0);
imageLike.setAlpha(0);
if (Likes == 0) {
// Log.e("Event Status", "Nothing");
m_view.setX(40);
m_view.setY(40);
m_view.setRotation(0);
} else if (Likes == 1) {
//Toast.makeText(getActivity(), "dislike the image",Toast.LENGTH_SHORT).show();
listvalue_pos--;
if(listvalue_pos==-1)
{
i=i+10;
listvalue_pos=9;
settheimage(i);
parentView.removeView(m_view);
}
else {
parentView.removeView(m_view);
}
// new deletUSer().execute();
} else if (Likes == 2) {
//Toast.makeText(getActivity(), "like the image",Toast.LENGTH_SHORT).show();
listvalue_pos--;
if(listvalue_pos==-1)
{
i=i+10;
listvalue_pos=9;
settheimage(i);
parentView.removeView(m_view);
}
else {
parentView.removeView(m_view);
}
// new adduser().execute();
}
break;
default:
break;
}
return true;
}
});
parentView.addView(m_view);
}
}
here I m Add hashmap into arraylist
map.put("User_Id", USer_id);
map.put("FirstName",FirstName);
map.put("User_Image", USer_Image);
// Set the JSON Objects into the array
/* list.add(USer_Image);
useridlist.add(USer_id);
usernamelist.add(FirstName);*/
arraylist.add(map);
please give me the answer how to get arralist index value

You can use int index = arraylist.indexOf(yourObject);

I'm not sure that correctly understood what you wanna do
can you show screenshot?
you can set tag for your imageview

Related

BukkitRunnable gives me a NPE

Basically, this code works as I need it to, perfectly fine, however, If I move even the slightest bit or get out of the water, my console gets SPAMMED with NPE's... What have I done wrong with my code? What I'm trying to do is, if a player is in a specific location, inside of water, it will start a countdown, in this case, of 5 seconds. And after the 5 seconds, it's meant to say "Testing", etc. That part works, just not when I move or step out of the water. And yes, I'm aware that the code is sloppy and a bunch of junk but I don't want to create a whole class for cuboid for just one event.
private HashMap<UUID, Integer> afkCountdown;
private HashMap<UUID, BukkitRunnable> afkCountdownTask;
#EventHandler
public void onPlayerMoveEvent(PlayerMoveEvent e) {
afkCountdown = new HashMap<UUID, Integer>();
afkCountdownTask = new HashMap<UUID, BukkitRunnable>();
Player p = e.getPlayer();
int x = 52;
int y = 80;
int z = 255;
int x1 = 72;
int y1 = 100;
int z1 = 275;
Location l1 = new Location(Bukkit.getWorld("Void"), x, y, z);
Location l2 = new Location(Bukkit.getWorld("Void"), x1, y1, z1);
Location loc = new Location(Bukkit.getWorld("Void"), p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ());
if (p.getWorld().equals(loc.getWorld())) {
if (Objects.requireNonNull(e.getTo()).getBlock().isLiquid()) {
if (loc.getX() > l1.getX() && loc.getX() < l2.getX()) {
if (loc.getY() > l1.getY() && loc.getY() < l2.getY()) {
if (loc.getZ() > l1.getZ() && loc.getZ() < l2.getZ()) {
if (!afkCountdown.containsKey(p.getUniqueId())) {
afkCountdown.put(p.getUniqueId(), 5);
afkCountdownTask.put(p.getUniqueId(), new BukkitRunnable() {
#Override
public void run() {
afkCountdown.put(p.getUniqueId(), afkCountdown.get(p.getUniqueId()) - 1);
if (afkCountdown.get(p.getUniqueId()) == 0) {
p.sendMessage("Testing");
afkCountdown.remove(p.getUniqueId());
afkCountdownTask.remove(p.getUniqueId());
afkCountdown.put(p.getUniqueId(), 5);
} else if (!afkCountdown.containsKey(p.getUniqueId())) {
cancel();
}
}
});
afkCountdownTask.get(p.getUniqueId()).runTaskTimer(plugin, 20, 20);
} else {
return;
}
} else {
if (afkCountdown.containsKey(p.getUniqueId())) {
afkCountdown.remove(p.getUniqueId());
afkCountdownTask.remove(p.getUniqueId());
} else {
return;
}
}
} else {
if (afkCountdown.containsKey(p.getUniqueId())) {
afkCountdown.remove(p.getUniqueId());
afkCountdownTask.remove(p.getUniqueId());
} else {
return;
}
}
} else {
if (afkCountdown.containsKey(p.getUniqueId())) {
afkCountdown.remove(p.getUniqueId());
afkCountdownTask.remove(p.getUniqueId());
} else {
return;
}
}
} else {
if (afkCountdown.containsKey(p.getUniqueId())) {
afkCountdown.remove(p.getUniqueId());
afkCountdownTask.remove(p.getUniqueId());
} else {
return;
}
}
} else {
if (afkCountdown.containsKey(p.getUniqueId())) {
afkCountdown.remove(p.getUniqueId());
afkCountdownTask.remove(p.getUniqueId());
} else {
return;
}
}
}
I have multiple things to say about this code :
The value of e.getTo() will never be null. So the Objects.requireNonNull code is a useless import.
You get multiple time the same world instance with Bukkit.getWorld("Void"), but only one time is better.
Instead of create Location's object, you can check directly the x/y/z values that are given just before.
For the issue :
When you left liquid, all task will remove the value linked with the player's uuid. So, you will not be able to get id with afkCountdown.get() or afkCountdownTask.get(). To fix it, you should use afkCountdown.getOrDefault(p.getUniqueId(), 0).
For timers, you never stop already started timer. So, your server with crash because of overflow. When you do afkCountdownTask.remove() you should do :
BukkitRunnable task = afkCountdownTask.remove(p.getUniqueId()); // return the removed one, or null if nothing removed
if(task != null) // if was existing
task.cancel(); // cancel task
You are creating and resetting hashmap EACH move with afkCountdown = new HashMap<UUID, Integer>(). You should do it only one time.
Finally, this is the code that I propose to fix everything :
private final HashMap<UUID, Integer> afkCountdown = new HashMap<>();
private final HashMap<UUID, BukkitRunnable> afkCountdownTask = new HashMap<>();
#EventHandler
public void onPlayerMoveEvent(PlayerMoveEvent e) {
Player p = e.getPlayer();
int x = 52;
int y = 80;
int z = 255;
int x1 = 72;
int y1 = 100;
int z1 = 275;
Location loc = e.getTo();
if (p.getWorld().getName().equals("Void")) {
if (loc.getBlock().isLiquid()) {
if (loc.getX() > x && loc.getX() < x1) {
if (loc.getY() > y && loc.getY() < y1) {
if (loc.getZ() > z && loc.getZ() < z1) {
if (!afkCountdown.containsKey(p.getUniqueId())) {
afkCountdown.put(p.getUniqueId(), 5);
afkCountdownTask.put(p.getUniqueId(), new BukkitRunnable() {
#Override
public void run() {
int amount = afkCountdown.getOrDefault(p.getUniqueId(), 0) - 1;
afkCountdown.put(p.getUniqueId(), amount);
if (amount <= 0) {
p.sendMessage("Testing");
afkCountdown.put(p.getUniqueId(), 5);
} else if (!afkCountdown.containsKey(p.getUniqueId())) {
cancel();
}
}
});
afkCountdownTask.get(p.getUniqueId()).runTaskTimer(Main.getInstance(), 20, 20);
}
return; // don't want to remove, so end method now
}
}
}
}
}
if (afkCountdown.containsKey(p.getUniqueId())) {
afkCountdown.remove(p.getUniqueId());
BukkitRunnable task = afkCountdownTask.remove(p.getUniqueId());
if(task != null)
task.cancel();
}
}

Draw bitmap in specified XY positions in the Canvas

I am trying to overlay a image in a specific position in the video so that i can combine both.But could not place the image to exact position selected.its moving somewhere else the final output.
I am using this library to combine image and video https://github.com/MasayukiSuda/Mp4Composer-android (out of box Any other library suggestions)In this library i can set the image in 4 different positions:
public enum Position {
LEFT_TOP,
LEFT_BOTTOM,
RIGHT_TOP,
RIGHT_BOTTOM
}
mp4Composer = new Mp4Composer(inputVideoPath, videoPath)
.filter(new WatermarkFilter(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_launcher_sample),WatermarkFilter.Position.LEFT_TOP))
In the Processing this happens:
case LEFT_TOP:
canvas.drawBitmap(bitmap,0,0,null);
break;
case LEFT_BOTTOM:
canvas.drawBitmap(bitmap, 0, canvas.getHeight() - bitmap.getHeight(), null);
break;
What i did i slightly modified my code to set anywhere in the canvas by getting the X Y position of the bitmap using MotionEvent
protected boolean onTouchDown(#NonNull MotionEvent event) {
currentMode = ActionMode.DRAG;
downX = event.getX();
downY = event.getY();
midPoint = calculateMidPoint();
oldDistance = calculateDistance(midPoint.x, midPoint.y, downX, downY);
oldRotation = calculateRotation(midPoint.x, midPoint.y, downX, downY);
currentIcon = findCurrentIconTouched();
if (currentIcon != null) {
currentMode = ActionMode.ICON;
currentIcon.onActionDown(this, event);
} else {
handlingSticker = findHandlingSticker();
}
if (handlingSticker != null) {
downMatrix.set(handlingSticker.getMatrix());
if (bringToFrontCurrentSticker) {
stickers.remove(handlingSticker);
stickers.add(handlingSticker);
}
if (onStickerOperationListener != null){
onStickerOperationListener.onStickerTouchedDown(handlingSticker);
}
}
if (currentIcon == null && handlingSticker == null) {
return false;
}
invalidate();
return true;
}
public float[] getMappedBoundPoints() {
float[] dst = new float[8];
getMappedPoints(dst, getBoundPoints());
return dst;
}
By this Method i get my X Y points
float X = sticker.getMappedBoundPoints()[0];
float Y = sticker.getMappedBoundPoints()[1];
Log.d(TAG, "SavedVideo: " + "X" + X + "?/" + "Y" + Y);
And Finally Passing my X Y to the Mp4Composer method:
.filter(new WatermarkFilter(bitmap,X,Y))
on the other side
canvas.drawBitmap(bitmap,X,Y,null);
Can anyone help out or point out where the mistake is ! Thanks

Making a responsive control in JavaFX

I'm trying to make a responsive design like in Word. I used Toolbar and ToolbarSkin code and made changes to it. Now I don't know how to make it so it will check the priority of the control, and the lowest priority gets resized, while the control with the highest priority still shows full-size.
Code I changed in ToolbarSkin:
private void addNodesToToolBar() {
final Responser toolbar = getSkinnable();
double length = 0;
if (getSkinnable().getOrientation() == Orientation.VERTICAL) {
length = snapSize(toolbar.getHeight()) - snappedTopInset() - snappedBottomInset() + getSpacing();
} else {
length = snapSize(toolbar.getWidth()) - snappedLeftInset() - snappedRightInset() + getSpacing();
}
// Is there overflow ?
double x = 0;
boolean hasOverflow = false;
for (Node node : getSkinnable().getItems()) {
if (getSkinnable().getOrientation() == Orientation.VERTICAL) {
x += snapSize(node.prefHeight(-1)) + getSpacing();
} else {
x += snapSize(node.prefWidth(-1)) + getSpacing();
}
if (x > length) {
hasOverflow = true;
break;
}
}
if (hasOverflow) {
if (getSkinnable().getOrientation() == Orientation.VERTICAL) {
length -= snapSize(overflowMenu.prefHeight(-1));
} else {
length -= snapSize(overflowMenu.prefWidth(-1));
}
length -= getSpacing();
}
// Determine which node goes to the toolbar and which goes to the overflow.
x = 0;
overflowMenuItems.clear();
box.getChildren().clear();
for (Node node : getSkinnable().getItems()) {
node.getStyleClass().remove("menu-item");
node.getStyleClass().remove("custom-menu-item");
if (getSkinnable().getOrientation() == Orientation.VERTICAL) {
x += snapSize(node.prefHeight(-1)) + getSpacing();
} else {
x += snapSize(node.prefWidth(-1)) + getSpacing();
}
if (x <= length) {
box.getChildren().add(node);
} else {
if (node.isFocused()) {
if (!box.getChildren().isEmpty()) {
Node last = engine.selectLast();
if (last != null) {
last.requestFocus();
}
} else {
overflowMenu.requestFocus();
}
}
if (node instanceof Separator) {
overflowMenuItems.add(new SeparatorMenuItem());
} else {
CustomMenuItem customMenuItem = new CustomMenuItem(node);
// RT-36455:
// We can't be totally certain of all nodes, but for the
// most common nodes we can check to see whether we should
// hide the menu when the node is clicked on. The common
// case is for TextField or Slider.
// This list won't be exhaustive (there is no point really
// considering the ListView case), but it should try to
// include most common control types that find themselves
// placed in menus.
final String nodeType = node.getTypeSelector();
switch (nodeType) {
case "Button":
case "Hyperlink":
case "Label":
customMenuItem.setHideOnClick(true);
break;
case "CheckBox":
case "ChoiceBox":
case "ColorPicker":
case "ComboBox":
case "DatePicker":
case "MenuButton":
case "PasswordField":
case "RadioButton":
case "ScrollBar":
case "ScrollPane":
case "Slider":
case "SplitMenuButton":
case "SplitPane":
case "TextArea":
case "TextField":
case "ToggleButton":
case "ToolBar":
customMenuItem.setHideOnClick(false);
break;
}
overflowMenuItems.add(customMenuItem);
box.getChildren().clear();
setNameToButton(make,box.getParent().getId());
box.getChildren().add(make);
// overflowMenuItems.remove(overflowMenuItems.size()-1);
}
}
}
// Check if we overflowed.
overflow = overflowMenuItems.size() > 0;
if (!overflow && overflowMenu.isFocused()) {
Node last = engine.selectLast();
if (last != null) {
last.requestFocus();
}
}
overflowMenu.setVisible(overflow);
overflowMenu.setManaged(overflow);
}
and:
#Override protected void layoutChildren(final double x,final double y,
final double w, final double h) {
final Responser toolbar = getSkinnable();
if (toolbar.getOrientation() == Orientation.VERTICAL) {
if (snapSize(toolbar.getHeight()) != previousHeight || needsUpdate) {
((VBox)box).setSpacing(getSpacing());
((VBox)box).setAlignment(getBoxAlignment());
previousHeight = snapSize(toolbar.getHeight());
addNodesToToolBar();
}
} else {
if (snapSize(toolbar.getWidth()) != previousWidth || needsUpdate) {
((HBox)box).setSpacing(getSpacing());
((HBox)box).setAlignment(getBoxAlignment());
previousWidth = snapSize(toolbar.getWidth());
addNodesToToolBar();
}
}
needsUpdate = false;
double toolbarWidth = w;
double toolbarHeight = h;
if (getSkinnable().getOrientation() == Orientation.VERTICAL) {
toolbarHeight -= (overflow ? snapSize(overflowMenu.prefHeight(-1)) : 0);
} else {
toolbarWidth -= (overflow ? snapSize(overflowMenu.prefWidth(-1)) : 0);
}
box.resize(toolbarWidth, toolbarHeight);
positionInArea(box, x, y,
toolbarWidth, toolbarHeight, /*baseline ignored*/0, HPos.CENTER, VPos.CENTER);
// If popup menu is not null show the overflowControl
if (overflow) {
double overflowMenuWidth = snapSize(overflowMenu.prefWidth(-1));
double overflowMenuHeight = snapSize(overflowMenu.prefHeight(-1));
double overflowX = x;
double overflowY = x;
if (getSkinnable().getOrientation() == Orientation.VERTICAL) {
// This is to prevent the overflow menu from moving when there
// are no items in the toolbar.
if (toolbarWidth == 0) {
toolbarWidth = savedPrefWidth;
}
HPos pos = ((VBox)box).getAlignment().getHpos();
if (HPos.LEFT.equals(pos)) {
overflowX = x + Math.abs((toolbarWidth - overflowMenuWidth)/2);
} else if (HPos.RIGHT.equals(pos)) {
overflowX = (snapSize(toolbar.getWidth()) - snappedRightInset() - toolbarWidth) +
Math.abs((toolbarWidth - overflowMenuWidth)/2);
} else {
overflowX = x +
Math.abs((snapSize(toolbar.getWidth()) - (x) +
snappedRightInset() - overflowMenuWidth)/2);
}
overflowY = snapSize(toolbar.getHeight()) - overflowMenuHeight - y;
} else {
// This is to prevent the overflow menu from moving when there
// are no items in the toolbar.
if (toolbarHeight == 0) {
toolbarHeight = savedPrefHeight;
}
VPos pos = ((HBox)box).getAlignment().getVpos();
if (VPos.TOP.equals(pos)) {
overflowY = y +
Math.abs((toolbarHeight - overflowMenuHeight)/2);
} else if (VPos.BOTTOM.equals(pos)) {
overflowY = (snapSize(toolbar.getHeight()) - snappedBottomInset() - toolbarHeight) +
Math.abs((toolbarHeight - overflowMenuHeight)/2);
} else {
overflowY = y + Math.abs((toolbarHeight - overflowMenuHeight)/2);
}
overflowX = snapSize(toolbar.getWidth()) - overflowMenuWidth - snappedRightInset();
}
overflowMenu.resize(overflowMenuWidth, overflowMenuHeight);
positionInArea(overflowMenu, overflowX, overflowY, overflowMenuWidth, overflowMenuHeight, /*baseline ignored*/0,
HPos.CENTER, VPos.CENTER);
}
}
Also I don't know how can I implement so only one control will shrink at the time, not all of them.
Thank you for your help.

A_star search what am I doing wrong?

Hi I am implementing an A* search algorithm based on WikiLink but I am not getting an answer from my search at all. any hints and/or help on what I may be doing wrong
I get a map that contains dirt and obstacles, I need to travel to all dirt particles and hoover them up and return to my starting point
Search Function
private void search_Astar(State start){ // we have confirmed a valid start state
// needed vars
Map<State, Integer> g_score = new HashMap<>();
Map<State, Integer> f_score = new HashMap<>();
Queue<State> openQueue = new PriorityQueue<State>(((State o1, State o2) -> f_score.get(o1) - f_score.get(o2)));
HashSet<State> closedSet = new HashSet<>();
// inits
g_score.put(start, 0);
f_score.put(start, start.heuristic());
openQueue.add(start);
// search
while (!openQueue.isEmpty()){
State current = openQueue.poll();
if (current.isGoal()){
// create path
solutionStack.push(Actions.Turn_Off);
while (current.takenAction != null){
solutionStack.push(current.takenAction);
current = current.parent;
}
return;
}
closedSet.add(current);
for (String action:current.legalActions()){
State child = current.CreateState(action);
if (closedSet.contains(child)) continue;
int tentativeG = g_score.get(current) + 1; // the cost to take an action
if (!openQueue.contains(child)) openQueue.add(child);
else if (tentativeG >= g_score.getOrDefault(child, Integer.MAX_VALUE)) continue;
g_score.put(child, tentativeG);
f_score.put(child, tentativeG + child.heuristic());
}
}
}
and State class (sorry for huge-ness)
import java.util.ArrayList;
import java.util.Collection;
public class State {
// keep track of position and orientation
public Orientation orientation;
public Position position;
public boolean turned_on;
// track world state
private Collection<Position> dirt;
private Collection<Position> obstacles;
private Position size;
// variables for detirmining goal state and heuristic
private Position home;
// for calculating G
public State parent;
public String takenAction;
public State(Position position, Orientation orientation, boolean turned_on, Collection dirt, Collection obs, Position home,
Position size, State parent, String action) {
this.position = position;
this.orientation = orientation;
this.turned_on = turned_on;
this.dirt = dirt;
this.obstacles = obs;
this.home = home;
this.size = size;
this.parent = parent;
this.takenAction = action;
}
public int G(){
State curr = parent;
int total = 0;
while (curr != null){
total += 1;
curr = parent.parent;
}
return total;
}
public String toString() {
return "State{position: " + position + ", orientation: " + orientation + ", on:" + turned_on + "}";
}
#Override
public int hashCode(){
int hashVal = 23;
hashVal = ((hashVal + position.x) << 5) - (hashVal + position.x);
hashVal = ((hashVal + position.y) << 5) - (hashVal + position.y);
if(turned_on){
hashVal += 1243;
}
if (orientation == Orientation.NORTH){
hashVal += 12;
}else if (orientation == Orientation.EAST){
hashVal += 2234;
}else if (orientation == Orientation.WEST){
hashVal += 32345;
}
return hashVal + dirt.size();
}
#Override
public boolean equals(Object o){
if (o instanceof State){
State other = (State)o;
if(!other.position.equals(this.position)){
return false;
}else if( other.turned_on != this.turned_on){
return false;
}else if( other.orientation != this.orientation){
return false;
}else if (other.dirt.size() != this.dirt.size()){
return false;
} else{
return true;
}
}else {
return false;
}
}
/**
* check to see if current node is a valid goal node
*
* #return true if valid, false otherwise
*/
public Boolean isGoal(){
return dirt.isEmpty() && position.equals(home);
}
/**
* Calculate all legal moves from current state
*
* #return Collection of legal actions (as string)
*/
public Collection<String> legalActions(){
Collection<String> actions = new ArrayList<String>();
if (!turned_on){
actions.add(Actions.Turn_On);
}else{
// no reason we couldn't turn
actions.add(Actions.Turn_Left);
actions.add(Actions.Turn_Right);
if (dirt.contains(position)){
actions.add(Actions.Suck);
}
// check if we can move forward
// ATTENTION this must be at bottom of function
if (orientation == Orientation.NORTH){
for (Position o: obstacles) {
if (o.y == position.y + 1 && o.x == position.x || position.y == size.y){
return actions;
}
}
// we have checked every obstacle and we would not collide
actions.add(Actions.Go);
}else if (orientation == Orientation.SOUTH){
for (Position o: obstacles) {
if (o.y == position.y - 1 && o.x == position.x || position.y == 1){
return actions;
}
}
actions.add(Actions.Go);
}else if (orientation == Orientation.WEST){
for (Position o: obstacles) {
if (o.x == position.x - 1 && o.y == position.y|| position.x == 1){
return actions;
}
}
actions.add(Actions.Go);
}else {
// we are pointing east
for (Position o: obstacles) {
if (o.x == position.x + 1 && o.y == position.y|| position.x == size.x){
return actions;
}
}
actions.add(Actions.Go);
}
}
return actions;
}
/**
* return a value to determine how optimal this state is
*
* evaluation methood: number of dirt left times a constant
* which is the added to the distance to the closest dirt
* if there are no dirts left it is the mannhatan distance to home
*
* note: should add state depth?
* #return int
*/
public int heuristic(){
int h = 0;
for (Position p:obstacles){
h += mannhatandist(p);
}
h += mannhatandist(home);
return h + dirt.size();
}
private int mannhatandist(Position p){
return Math.abs(p.x - position.x) + Math.abs(p.y - position.y);
}
private int distToClosest(){
int min = Integer.MAX_VALUE;
if (dirt.isEmpty()){
int dist = Math.abs(home.x - position.x) + Math.abs(home.y - position.y);
return dist;
}
for (Position p: dirt) {
int dist = Math.abs(p.x - position.x) + Math.abs(p.y - position.y);
min = Math.min(min, dist);
}
if (!turned_on) min++;
return min;
}
public State CreateState(String action) {
//Copy the "old" values from the current state.
//Before any action done, the "new" state has the same values.
Position new_position = new Position(position.x, position.y);
Orientation new_orientation = orientation;
boolean new_turned_on = turned_on;
Collection new_dirt = new ArrayList(dirt);
State new_parent = this;
//If the action is to turn the robot on, the turned_on variable for the new state takes the value "true".
if(action == "TURN_ON") {
new_turned_on = true;
}
//If the action is to turn the robot on, the turned_on variable for the new state takes the value "true".
else if(action == "TURN_OFF") {
new_turned_on = false;
}
//If the action is to suck, the current position needs to be taken out of the new state's dirt collection.
else if(action == "SUCK") {
new_dirt.remove(position);
}
//If the action is to go it depends on the orientation of the robot how the position of the new state will change.
else if(action == "GO") {
//If it's facing north, the y position increases by one, considering the old state and so on.
if(orientation == Orientation.NORTH) {
new_position.y++;
}
else if(orientation == Orientation.EAST) {
new_position.x++;
}
else if(orientation == Orientation.SOUTH) {
new_position.y--;
}
else {
new_position.x--;
}
}
//If the action is to turn left it depends on the orientation of the robot in the current state what the new orientation will be.
else if(action == "TURN_LEFT") {
if(orientation == Orientation.NORTH) {
new_orientation = Orientation.WEST;
}
else if(orientation == Orientation.EAST) {
new_orientation = Orientation.NORTH;
}
else if(orientation == Orientation.SOUTH) {
new_orientation = Orientation.EAST;
}
else {
new_orientation = Orientation.SOUTH;
}
}
//If the action is to turn right it depends on the orientation of the robot in the current state what the new orientation will be.
else if(action == "TURN_RIGHT") {
if(orientation == Orientation.NORTH) {
new_orientation = Orientation.EAST;
}
else if(orientation == Orientation.EAST) {
new_orientation = Orientation.SOUTH;
}
else if(orientation == Orientation.SOUTH) {
new_orientation = Orientation.WEST;
}
else {
new_orientation = Orientation.NORTH;
}
}
//Make a new state from the new variables that have been changed according to the action done.
State new_state = new State(new_position, new_orientation, new_turned_on, new_dirt, obstacles, home, size, new_parent, action);
return new_state;
}
}
I have Fixed it now. the problem was that my heuristic was not consistent. I have modified it and it is performing correctly now
I will not share my answer since this was for a school project and since the automatic anti-cheating system at school will probably detect this I will add my school username to this comment (dagur13)
p.s. I will post my updated code when I have recieved a grade for the project

Running loop to check integer, not working

I'm trying to get the location of the user's finger touch and detect if it is within the bounds of an image view. I'm getting all the right integers returned to me, there is no problem with the values. The problem I'm getting is when trying to detect whether returnX is greater or less than the imageview X int.
ImageView img;
float eventX;
float eventY;
float x,y,x2,y2;
String TAG = "imgPos";
String TAG2 = "downcheck";
String TAG3 = "bounds";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img = (ImageView)findViewById(R.id.imageView1);
}
public void fingerDownLoop(){
if (SingleTouchEventView.userDown == true){
Log.e(TAG2, "Down is true");
Thread myThread = new Thread(myRunnable);
myThread.start();
} else if (SingleTouchEventView.userDown == false){
Log.e(TAG2, "Down is false");
}
}
public void getFingerLocation(){
float returnX = SingleTouchEventView.eventX;
float returnY = SingleTouchEventView.eventY;
Log.e(TAG3, " - X -");
Log.e(TAG3, " getX: " + returnX);
Log.e(TAG3, " - Y -");
Log.e(TAG3, " getY: " + returnY);
if (returnX < x){
Log.e(TAG3, "Outside bounds");
}
if (returnX > x){
Log.e(TAG3, "Inside bounds");
}
}
Runnable myRunnable = new Runnable() {
#Override
public void run() {
while (SingleTouchEventView.userDown == true) {
try {
Log.e(TAG2, "FingerDown");
getFingerLocation();
x = img.getLeft();
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // Waits for 1 second (1000 milliseconds)
}
}
};
}
testText is a button click, it gets the imageviews position and stores it as the values. The problem I'm getting is here:
if (returnX < x){
Log.e(TAG3, "Outside bounds");
}
if (returnX > x){
Log.e(TAG3, "Inside bounds");
}
It is all ways showing as Inside bounds even though returnX is less than X. Any ideas?
Updated get img position.
int[] img_coordinates = new int[2];
img.getLocationOnScreen(img_coordinates);
double x_center = (double)img_coordinates[0] + img.getWidth()/2.0;
double y_center = (double)img_coordinates[1] + img.getHeight()/2.0;
int halfwidth = 150 / 2;
int halfheight = 150 / 2;
yboundtop = y_center - halfheight;
yboundbottom = y_center + halfheight;
xboundleft = x_center - halfwidth;
xboundright = x_center + halfwidth;
float returnX = eventX;
float returnY = eventY;
if (returnX < xboundleft || returnX > xboundright || returnY < yboundtop || returnY > yboundbottom) {
Log.e(TAG3, "Outside bounds");
}
if (returnX > xboundleft && returnX < xboundright && returnY > yboundtop && returnY < yboundbottom) {
Log.e(TAG3, "Inside bounds");
}
I'am not sure what you want to accomplish by your code, but checking in a loop is not very efficient and in this case probably not necessary.
Your imageView has a method getHitRect() and you could use it like this:
Rect hitRect = new Rect();
imageView.getHitRect(hitRect);
if(hitRect.contains(touchEvent.getX(), touchEvent.getY())){
// your touch is inside, do something useful
}
Use it inside your touch-method
Now that I kind of know what you are looking for I think I may be able to help. Override the onTouchEvent() method of your Activity to capture your touch events. This will be much more efficient than doing the loop yourself.
private boolean mTouchInImage = false;
public boolean onTouchEvent(MotionEvent event) {
boolean handledTouch = false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Rect hitRect = new Rect((int)img.getX(), (int)img.getY(),
(int)(mg.getX() + img.getWidth()), (int)(img.getY() + img.getHeight()));
handledTouch = mTouchInImage = hitRect.contains((int)event.getX(), (int)event.getY());
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
handledTouch = mTouchInImage;
mTouchInImage = false;
break;
case MotionEvent.ACTION_MOVE:
if (mTouchInImage) {
img.setX(event.getX() - img.getWidth() / 2);
img.setY(event.getY() - img.getHeight() / 2);
img.invalidate();
handledTouch = true;
}
break;
}
return handledTouch;
}

Categories

Resources