I am trying to create an android application which acts as a Web Socket server. Here is my MainActivity.java.
package com.example.websocket;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import org.apache.http.conn.util.InetAddressUtils;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText port, msg;
Button listen, send;
TextView status;
int p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
port = (EditText)findViewById(R.id.editText1);
msg = (EditText)findViewById(R.id.editText2);
listen = (Button)findViewById(R.id.button1);
send = (Button)findViewById(R.id.button2);
status = (TextView)findViewById(R.id.textView1);
listen.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
String temp = port.getText().toString();
p = Integer.parseInt(temp);
try
{
custom_web_socket wsocket = new custom_web_socket(p);
wsocket.start();
}
catch (UnknownHostException e) {
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class custom_web_socket extends WebSocketServer
{
public custom_web_socket(int port_add) throws UnknownHostException {
super(new InetSocketAddress(port_add));
// pass
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
status.setText("Connection closed.");
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
status.setText((CharSequence) arg1);
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
// TODO Auto-generated method stub
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
status.setText("Connected");
}
}
}
When I run the program, the application starts. However, wheneve I try to enter value into the EditText field, the application hangs and ends. I am referring this example for web sockets - https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/example/ChatServer.java
I have imported the necessary jar file. This is my first attempt at android programming and I am not sure what the problem could be.
You are using an event onClick.
So whenever you are trying to type something , it calls your method. and hangs up.
your action should happen when user finished typing the code.
You can use following code
port.setOnEditorActionListener(
new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent
event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode()==KeyEvent.KEYCODE_ENTER)
{
if (!event.isShiftPressed()) {
// the user is done typing.
return true; // consume.
}
}
return false; // pass on to other listeners.
}
});
Also , refer to http://developer.android.com/reference/android/widget/EditText.html
you will get the clear idea.
Related
I have attempted to integrate simple Unity shape figure to display using Android Studio IDE however it shows like this:
Your hardware does not support this application sorry
My phone is Android 6.0 Marshmallow and the version of Unity is 5.4.1f1
The logcat in Android Studio does not show any error except when I dismiss the message about hardware not supported, then crashed.
package com.cs4.android_lcitresearch.schoolsafetyemergencyapplication.maps_class;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import com.cs4.android_lcitresearch.schoolsafetyemergencyapplication.R;
import com.cs4.android_lcitresearch.schoolsafetyemergencyapplication.SplashInterface;
import com.cs4.android_lcitresearch.schoolsafetyemergencyapplication.comic_class.comiclass;
import com.cs4.android_lcitresearch.schoolsafetyemergencyapplication.phone_class.phoneclass;
import com.cs4.android_lcitresearch.schoolsafetyemergencyapplication.scenario_class.scenarioclass;
import com.unity3d.player.UnityPlayer;
public class lcoldclass extends AppCompatActivity {
protected UnityPlayer mUnityPlayer;
public static Context mContext;
private Handler handler=new Handler();
public FrameLayout fl_forUnity;
public ImageButton scenario1, comic1, phoneclass1, maps1, homeb;
public Toolbar toolbar;
public TextView txttitle;
public void init_home() {
homeb= (ImageButton)findViewById(R.id.homebutton);
homeb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent first = new Intent(lcoldclass.this,SplashInterface.class);
startActivity(first);
}
});
}
public void init_scenario() {
scenario1= (ImageButton)findViewById(R.id.scenario);
scenario1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent first = new Intent(lcoldclass.this,scenarioclass.class);
startActivity(first);
}
});
}
public void init_comic() {
comic1= (ImageButton)findViewById(R.id.comicbutton);
comic1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent first = new Intent(lcoldclass.this,comiclass.class);
startActivity(first);
}
});
}
public void init_phone() {
phoneclass1= (ImageButton)findViewById(R.id.callbutton);
phoneclass1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent first = new Intent(lcoldclass.this,phoneclass.class);
startActivity(first);
}
});
}
public void init_maps() {
maps1= (ImageButton)findViewById(R.id.mapsl);
maps1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent first = new Intent(lcoldclass.this,SecondInterfaceF.class);
startActivity(first);
}
});
}
private void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.include2);
toolbar.showOverflowMenu();
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
mContext = this;
getWindow().takeSurface(null);
setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
getWindow().setFormat(PixelFormat.RGB_888);
mUnityPlayer = new UnityPlayer(this);
if (mUnityPlayer.getSettings ().getBoolean ("hide_status_bar", true))
getWindow ().setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
int glesMode = mUnityPlayer.getSettings().getInt("gles_mode", 1);
boolean trueColor8888 = false;
mUnityPlayer.init(glesMode, trueColor8888);
View playerView = mUnityPlayer.getView();
setContentView(R.layout.lcmapsold1);
this.fl_forUnity = (FrameLayout)findViewById(R.id.frameunity);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(750, 630);
fl_forUnity.addView(playerView, 0, lp);
initToolbar();
init_home();
init_scenario();
init_comic();
init_phone();
init_maps();
txtformation_init();
mUnityPlayer.requestFocus();
}
///////////////////////////// Unity Codes Override///////////////////////////////////////////
// Quit Unity
#Override protected void onDestroy ()
{
mUnityPlayer.quit();
super.onDestroy();
}
// Pause Unity
#Override protected void onPause()
{
super.onPause();
mUnityPlayer.pause();
}
// Resume Unity
#Override protected void onResume()
{
super.onResume();
mUnityPlayer.resume();
}
// This ensures the layout will be correct.
#Override public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
mUnityPlayer.configurationChanged(newConfig);
}
// Notify Unity of the focus change.
#Override public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
mUnityPlayer.windowFocusChanged(hasFocus);
}
// For some reason the multiple keyevent type is not supported by the ndk.
// Force event injection by overriding dispatchKeyEvent().
#Override public boolean dispatchKeyEvent(KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_MULTIPLE)
return mUnityPlayer.injectEvent(event);
return super.dispatchKeyEvent(event);
}
// Pass any events not handled by (unfocused) views straight to UnityPlayer
#Override public boolean onKeyUp(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); }
#Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mUnityPlayer.injectEvent(event); }
#Override public boolean onTouchEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); }
/*API12*/ public boolean onGenericMotionEvent(MotionEvent event) { return mUnityPlayer.injectEvent(event); }
///////////////////////////// Unity Codes Override///////////////////////////////////////////
}
How to solve it? I cannot understand how users manage to work the program without issues on integration.
I am working on an app that implements a Web Socket server. I am referring this library - https://github.com/TooTallNate/Java-WebSocket
The problem is that the thread holds up the entire UI. Here is the code -
package com.example.websocket;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.nio.ByteBuffer;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.framing.FrameBuilder;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import android.os.Bundle;
import android.provider.Settings.Global;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText port, msg;
Button listener, send;
TextView status;
int p;
int count = 0;
boolean connect = false;
boolean listen = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msg = (EditText)findViewById(R.id.editText2);
listener = (Button)findViewById(R.id.button1);
send = (Button)findViewById(R.id.button2);
status = (TextView)findViewById(R.id.textView1);
listener.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
SimpleServer server = new SimpleServer();
server.start();
status.setText("Working inside Thread");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
});
t.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class SimpleServer extends WebSocketServer {
public SimpleServer() throws UnknownHostException {
super(new InetSocketAddress(9998));
// TODO Auto-generated constructor stub
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
// TODO Auto-generated method stub
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
// TODO Auto-generated method stub
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
status.setText("Working");
}
}
}
You cannot update ui from other threads:
status.setText("Working inside Thread");
use runOnUiThread method of activity
runOnUiThread(new Runnable() {
#Override
public void run() {
status.setText("Working inside Thread");
}
});
By the way youre code cause memory leack and crashes. You cannot start long living operations in activity context. You should run service ,or make this thread in application context, results to ui you can pass by using EventBus.
I have two buttons that increment and decrement a value by one with each press and they're working just fine with the onClickListener. I see that an onLongClickListener exists, which I assume is for touch and hold events. How would I have the number rapidly increment/decrement if the button is held?
Am I correct in assuming that onLongClickListener only fires once per long click? Is there a more appropriate listener or a property somewhere that I'm not aware of?
You may implement it as in the following code.
package org.me.rapidchange;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MainActivity extends Activity implements OnKeyListener,
OnTouchListener, OnClickListener {
private class UpdateCounterTask implements Runnable {
private boolean mInc;
public UpdateCounterTask(boolean inc) {
mInc = inc;
}
public void run() {
if (mInc) {
mHandler.sendEmptyMessage(MSG_INC);
} else {
mHandler.sendEmptyMessage(MSG_DEC);
}
}
}
private static final int MSG_INC = 0;
private static final int MSG_DEC = 1;
private Button mIncButton;
private Button mDecButton;
private TextView mText;
private int mCounter;
private Handler mHandler;
private ScheduledExecutorService mUpdater;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_INC:
inc();
return;
case MSG_DEC:
dec();
return;
}
super.handleMessage(msg);
}
};
mIncButton = (Button) findViewById(R.id.inc_button);
mDecButton = (Button) findViewById(R.id.dec_button);
mText = (TextView) findViewById(R.id.text);
mIncButton.setOnTouchListener(this);
mIncButton.setOnKeyListener(this);
mIncButton.setOnClickListener(this);
mDecButton.setOnTouchListener(this);
mDecButton.setOnKeyListener(this);
mDecButton.setOnClickListener(this);
}
private void inc() {
mCounter++;
mText.setText(Integer.toString(mCounter));
}
private void dec() {
mCounter--;
mText.setText(Integer.toString(mCounter));
}
private void startUpdating(boolean inc) {
if (mUpdater != null) {
Log.e(getClass().getSimpleName(), "Another executor is still active");
return;
}
mUpdater = Executors.newSingleThreadScheduledExecutor();
mUpdater.scheduleAtFixedRate(new UpdateCounterTask(inc), 200, 200,
TimeUnit.MILLISECONDS);
}
private void stopUpdating() {
mUpdater.shutdownNow();
mUpdater = null;
}
public void onClick(View v) {
if (mUpdater == null) {
if (v == mIncButton) {
inc();
} else {
dec();
}
}
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
boolean isKeyOfInterest = keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER;
boolean isReleased = event.getAction() == KeyEvent.ACTION_UP;
boolean isPressed = event.getAction() == KeyEvent.ACTION_DOWN
&& event.getAction() != KeyEvent.ACTION_MULTIPLE;
if (isKeyOfInterest && isReleased) {
stopUpdating();
} else if (isKeyOfInterest && isPressed) {
startUpdating(v == mIncButton);
}
return false;
}
public boolean onTouch(View v, MotionEvent event) {
boolean isReleased = event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL;
boolean isPressed = event.getAction() == MotionEvent.ACTION_DOWN;
if (isReleased) {
stopUpdating();
} else if (isPressed) {
startUpdating(v == mIncButton);
}
return false;
}
}
I had this same goal and ended up using an OnLongClick to catch the down portion to start a repeating event via a handler, then the normal OnClick to catch the release and stop it. Works beautifully for me.
mOngoingRunnable = new Runnable() {
public void run() {
// do stuff
mHandler.postDelayed(mOngoingRunnable, delayMsecs);
}
};
public boolean onLongClick(View view) {
mHandler.post(mOngoingRunnable);
mOngoing = true;
return false;
}
public void onClick(View view) {
if (mOngoing) {
mHandler.removeCallbacks(mOngoingRunnable);
mOngoing = false;
}
}
package com.example.android.home;
import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
import android.view.*;
public class HomeActivity extends Activity {
/** Called when the activity is first created. */
private EditText input;
private EditText result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
input = (EditText) findById(R.id.input1);
result = (EditText) ***findById***(R.id.result); //Error:Undefined for the type HomeActivity
input.addKeyListener(new View.OnKeyListener() { Error: Undefined for the type EditText
public boolean onKey(View v, int keycode, KeyEvent keyevent) {
if (keyevent.getAction() == KeyEvent.ACTION_UP) {
doCalculation();
}
return false;
}
});
}
private void doCalculation()
{
String strValue = input.getText().toString();
int resultt = Integer.parseInt(strValue) * 2;
result.setText("Result: "+ resultt);
}
}
As #Varun states, there is no findById() method. You are probably thinking of findViewById().
You would have found this on your own by examining any sample Android activity and seeing how it accesses the widgets. There are many sample activities in your SDK installation, plus online.
I have two buttons that increment and decrement a value by one with each press and they're working just fine with the onClickListener. I see that an onLongClickListener exists, which I assume is for touch and hold events. How would I have the number rapidly increment/decrement if the button is held?
Am I correct in assuming that onLongClickListener only fires once per long click? Is there a more appropriate listener or a property somewhere that I'm not aware of?
You may implement it as in the following code.
package org.me.rapidchange;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MainActivity extends Activity implements OnKeyListener,
OnTouchListener, OnClickListener {
private class UpdateCounterTask implements Runnable {
private boolean mInc;
public UpdateCounterTask(boolean inc) {
mInc = inc;
}
public void run() {
if (mInc) {
mHandler.sendEmptyMessage(MSG_INC);
} else {
mHandler.sendEmptyMessage(MSG_DEC);
}
}
}
private static final int MSG_INC = 0;
private static final int MSG_DEC = 1;
private Button mIncButton;
private Button mDecButton;
private TextView mText;
private int mCounter;
private Handler mHandler;
private ScheduledExecutorService mUpdater;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_INC:
inc();
return;
case MSG_DEC:
dec();
return;
}
super.handleMessage(msg);
}
};
mIncButton = (Button) findViewById(R.id.inc_button);
mDecButton = (Button) findViewById(R.id.dec_button);
mText = (TextView) findViewById(R.id.text);
mIncButton.setOnTouchListener(this);
mIncButton.setOnKeyListener(this);
mIncButton.setOnClickListener(this);
mDecButton.setOnTouchListener(this);
mDecButton.setOnKeyListener(this);
mDecButton.setOnClickListener(this);
}
private void inc() {
mCounter++;
mText.setText(Integer.toString(mCounter));
}
private void dec() {
mCounter--;
mText.setText(Integer.toString(mCounter));
}
private void startUpdating(boolean inc) {
if (mUpdater != null) {
Log.e(getClass().getSimpleName(), "Another executor is still active");
return;
}
mUpdater = Executors.newSingleThreadScheduledExecutor();
mUpdater.scheduleAtFixedRate(new UpdateCounterTask(inc), 200, 200,
TimeUnit.MILLISECONDS);
}
private void stopUpdating() {
mUpdater.shutdownNow();
mUpdater = null;
}
public void onClick(View v) {
if (mUpdater == null) {
if (v == mIncButton) {
inc();
} else {
dec();
}
}
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
boolean isKeyOfInterest = keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER;
boolean isReleased = event.getAction() == KeyEvent.ACTION_UP;
boolean isPressed = event.getAction() == KeyEvent.ACTION_DOWN
&& event.getAction() != KeyEvent.ACTION_MULTIPLE;
if (isKeyOfInterest && isReleased) {
stopUpdating();
} else if (isKeyOfInterest && isPressed) {
startUpdating(v == mIncButton);
}
return false;
}
public boolean onTouch(View v, MotionEvent event) {
boolean isReleased = event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL;
boolean isPressed = event.getAction() == MotionEvent.ACTION_DOWN;
if (isReleased) {
stopUpdating();
} else if (isPressed) {
startUpdating(v == mIncButton);
}
return false;
}
}
I had this same goal and ended up using an OnLongClick to catch the down portion to start a repeating event via a handler, then the normal OnClick to catch the release and stop it. Works beautifully for me.
mOngoingRunnable = new Runnable() {
public void run() {
// do stuff
mHandler.postDelayed(mOngoingRunnable, delayMsecs);
}
};
public boolean onLongClick(View view) {
mHandler.post(mOngoingRunnable);
mOngoing = true;
return false;
}
public void onClick(View view) {
if (mOngoing) {
mHandler.removeCallbacks(mOngoingRunnable);
mOngoing = false;
}
}