In my Android Client App I'm trying to send virtual joystick coordinates over socket from client(Android) to a server(Arduino).I'm Tray Codding a thread 't' in main activity containing a socket 's', to send x,y Coordinate to arduino Server.
the JoystickView Class give me 'x' and 'y' when I move the joystick.
this will be done after user Click Connect button,
'x' is from 0 to 255, also 'y' but to be able to know witch value is 'x' and witch is 'y' in arduino side, I added 255 to y so y will be from 255 to 510.
virtual joy stick provide me with 'x','y' Coordinate Stored in public variables 'xxx' and 'yyy'.
Linked a Connect Button with thread 't, Created I socket 's' to send 'x','y' to server.
**my Question: can my Code works with the Arduino and Can I get x,y in Arduino Side ?, also I couldn't put thread 't' in "public void onClick(View v)" function. its the second problem :( **
package com.ravensoft.daniel.joysticktest;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.DataOutputStream;
public class MainActivity extends AppCompatActivity implements
JoystickView.JoystickListener{
TextView x;
TextView y;
public float xxx=0;//bublic var will Contain x value from virtual
joystick
public float yyy=0;//bublic var will Contain x value from virtual
joystick
EditText txt_IP;//arduino ip
EditText txt_PORT;//arduino port
private volatile Socket socket = null;
private boolean connectionOk = false;
private Button buttonDisconnect; //button for disconnect connection
private Button buttonConnect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
JoystickView joystick = new JoystickView(this);
setContentView(R.layout.activity_main);
buttonConnect = findViewById(R.id.buttonConnect);
buttonDisconnect = findViewById(R.id.buttonDisconnect);
JoystickView joystic =findViewById(R.id.joystick);
txt_IP=(EditText)findViewById(R.id.editText_IP);
txt_PORT=(EditText)findViewById(R.id.editText_PORT);
buttonConnect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttonDisconnect.setEnabled(false);
buttonConnect.setEnabled(true);
}
Thread t=new Thread(new Runnable() {
#Override
public void run() {
try {
Socket s = new Socket(txt_IP.getText().toString(),Integer.parseInt(txt_PORT.getText().toString() ));
s.connect(new InetSocketAddress(txt_IP.getText().toString(), Integer.parseInt(txt_PORT.getText().toString() )), 50);
if(s == null)System.out.println("SOCKET NULL");
DataOutputStream DataOut = new DataOutputStream(s.getOutputStream());
String message= Float.toString(xxx+256);
byte[] msgBuffer=message.getBytes();
String message2= Float.toString(yyy);
byte[] msgBuffer2=message2.getBytes();
try {
DataOut.write(msgBuffer);
DataOut.write(msgBuffer2);
}catch (IOException e){
}
DataOut.flush();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
#Override
public void onJoystickMoved( float xPercent, float yPercent) {
x = (TextView) findViewById(R.id.x_value);
x.setText(Float.toString(xPercent));
y = (TextView) findViewById(R.id.y);
y.setText(Float.toString(-yPercent));
xxx=xPercent;
yyy=yPercent;
Log.d("Right Joystick", "X percent: " + xPercent + " Y percent: " + yPercent);
}}
Related
I am a beginner to coding in general and am working with Java in Android Studio. I am working on an app and I cannot get my if/else statement to work properly. Right now it is accepting any number. Can someone please let me know what I am doing wrong here?
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.DecimalFormat;
public class Cost extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cost);
TextView totalCost = (TextView)findViewById(R.id.txtCost);
ImageView image = (ImageView)findViewById(R.id.imgRental);
SharedPreferences sharedPref =
PreferenceManager.getDefaultSharedPreferences(this);
float floatTruckSize = sharedPref.getFloat("key1", 0);
float floatMiles = sharedPref.getFloat("key2", 0);
float floatCost;
if (floatTruckSize == 10) {
floatTruckSize = (float) 19.95;
image.setImageResource(R.drawable.tenfoot);
} else if (floatTruckSize == 17) {
floatTruckSize = (float) 29.95;
image.setImageResource(R.drawable.seventeenfoot);
} else if (floatTruckSize == 26) {
floatTruckSize = (float) 39.95;
image.setImageResource(R.drawable.twentysixfoot);
} else {
totalCost.setText("Enter 10, 17, or 26 foot truck rental");
}
floatCost = (float) (floatTruckSize * (floatMiles * .99));
DecimalFormat currency = new DecimalFormat("$###,###.##");
totalCost.setText("Total cost for 1-day truck rental " +
currency.format(floatCost));
}
}
I am developing something like X11 server for Android and I need some help.
I found out that applications like bVNC and Microsoft Remote Desktop client can intercept Super, Alt-Tab, Alt-F4 and almost all keyboard events.
I tried to guess what exactly is done to achieve this but failed.
I found out that after running bVNC on my phone I can run my own com.iiordanov.bVNC.RemoteCanvasActivity with simple View.OnKeyListener and focused View receives all the events I need without system response (i.e. no recents menu on Alt-Tab). But when I change package name or class name I loose this ability.
Is there anyone who can help with this please?
package com.iiordanov.bVNC;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.TextView;
public class RemoteCanvasActivity extends AppCompatActivity implements OnKeyListener {
private final static String TAG = "RemoteCanvas";
TextView log;
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
log = new TextView(this);
setContentView(log);
log.setSingleLine(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
log.setDefaultFocusHighlightEnabled(false);
}
log.setOnKeyListener(this);
log.setFocusableInTouchMode(true);
log.setDrawingCacheEnabled(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
log.setFocusedByDefault(true);
}
log.requestFocus();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent evt) {
if (log != null) {
log.append("Got keycode " + keyCode + " " + evt.getAction() + "\n");
final int scrollAmount = log.getLayout().getLineTop(log.getLineCount()) - log.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
log.scrollTo(0, scrollAmount);
else
log.scrollTo(0, 0);
}
return true;
}
}
117 is KeyEvent.KEYCODE_META_LEFT.
25 is KeyEvent.KEYCODE_VOLUME_DOWN.
Thank you very much.
I have an app on Google Play that works on my phone when using it as a remote testing device but when I upload it to the Play Store and then download it onto my phone it wont work it fails to transmit any packets.
See code below, I dont know what the problem is i've been scratching my head all day perhaps a permissions issue?
package com.example.dale.whatismyip;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Created by Dale on 22/01/2017.
*/
public class PingActivity extends AppCompatActivity
{
private EditText pingEdit;
private String pingVal;
private TextView finalResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ping);
finalResult = (TextView) findViewById(R.id.result);
pingEdit = (EditText) findViewById(R.id.editText2);
final Button button = (Button) findViewById(R.id.button5);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finalResult.setText("");
pingVal = pingEdit.getText().toString();
if(pingVal.contains(".") && pingVal.length() > 6)
{
PingTest runner = new PingTest();
runner.execute();
}
else
{
finalResult.setText("Invalid Address");
}
}
});
}
private class PingTest extends AsyncTask<String, String, String>
{
private String res;
#Override
protected String doInBackground(String... strings) {
try {
boolean sudo = false;
String cmd = "/system/bin/ping -c 4 -w 4 " + pingVal;
Process p;
if(!sudo)
p= Runtime.getRuntime().exec(cmd);
else{
p= Runtime.getRuntime().exec(new String[]{"su", "-c", cmd});
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
res = "";
while ((s = stdInput.readLine()) != null) {
// CODE TO DO - create an array and populate it
System.out.println(res += s + "\n");
}
p.destroy();
return res;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
// CODE TO DO - pass this method both an array of type string and a string
// then do a while loop through it whilst the array is populated and set the value of the textview to the strings
finalResult.setText(result);
}
}
}
Issue sorted.
The code itself was fine but the power saving feature on android stops the ping functionality as it disables background network usage.
Okay this is such a suggestion but are you testing your phone through a computer? is the phone connected through a usb to a computer?
and could you print a toast to see what's going on in doInBackground
I can't find anything wrong in your code.
Im building a converter app and it's to convert centimetres into inches but i want it to do the opposite too, so the user can enter a value into either box to convert it. Ive tried various ways but won't work.
Here's my src code
package com.qub.buildersbuddy;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class CentInch extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cent_inch);
final EditText editCentimeters = (EditText) findViewById(R.id.editCentimeters);
final EditText editInches = (EditText) findViewById(R.id.editInches);
Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
double centimeters = Double.valueOf(editCentimeters.getText()
.toString());
double inches = centimeters * 0.393700787;
editInches.setText(String.valueOf(inches));
}
});
}
}
I know little about android but try to make something like this:
public void onClick(View arg0) {
double centimeters = 0;
double inches = 0;
//convert inches to centimeters
if(editCentimeters.getText().toString().isEmpty()){
inches = Double.valueOf(editInches.getText().toString());
//do the conversion
editCentimeters.setText(String.valueOf(inches));
}
//convert centimeters to inches
else if(editInches.getText().toString().isEmpty()){
centimeters = Double.valueOf(editCentimeters.getText().toString());
//do the conversion
editInches.setText(String.valueOf(inches));
}
}
if isEmpty() doesn't work try with .equals("") or == "". You get the point
I'm working on an app that involved comparing to numbers inputted by the user via text box, but wen I put in any if statements the program crashes whenever they are called. Otherwise the program runs just fine without any crashes or errors.
package improvecredit.app.basic;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.text.Editable;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ImprovrCreditBasicActivity extends Activity {
/** Called when the activity is first created. */
public int minCredScore = 300;
public int maxCredScore = 850;
public int inputScore;
public int idealScore;
public Editable inputString;
public Editable idealString;
public EditText user;
public EditText desired;
public TextView output;
public Button submit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
user = (EditText) findViewById(R.id.user_text);
desired = (EditText) findViewById(R.id.desired_text);
output = (TextView) findViewById(R.id.output_text);
submit = (Button) findViewById(R.id.submit_button);
//submit.setOnClickListener(new View.OnClickListener());
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//inputString = user.getText();
//idealString = desired.getText();
inputScore = Integer.getInteger(user.getText().toString());
idealScore = Integer.getInteger(desired.getText().toString());
if (inputScore >= 0 && idealScore >= 0){
if (inputScore < minCredScore || idealScore < minCredScore){
output.setText("Invalid Entries");
}
if (inputScore > maxCredScore || idealScore > maxCredScore){
output.setText("Invalid Entries");
}
if (inputScore > idealScore){
output.setText("Nice Credit Score!");
}
if (inputScore < idealScore){
output.setText("For more information on how to improve your credit score, please visit" + "/n" + "http://www.creditscoresandcredit.com/");
}
}
else{
output.setText("Please enter valid credit scores");
}
}
});
}
If someone can point out what may have been done wrong in the code I would really appreciate it.
On first glance, don't use Integer.getInteger(), use Integer.parseInt().
If that doesn't fix it, please include the crash log from the console so we can see exactly what exception is being raised.
I'm betting that there is a null value introduced. If you check for null before using the variables idealScore and inputScore in the If statement, it will avoid this error. Until you paste the error trace, we can only guess for you.