I'm new at java and i would like to know how to click multiple buttons on same page without making the app force close. I tried to make the code more simple. For now , the first button is work well but the second button will force close the app when get clicked.
Im sorry if im not clear enough to explain my problem
im open for any advices
public static enum CONN_TYPE {
LEJOS_PACKET, LEGO_LCP
}
class UIMessageHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE:
_message.setText((String) msg.getData().get(MESSAGE_CONTENT));
break;
case TOAST:
showToast((String) msg.getData().get(MESSAGE_CONTENT));
break;
}
_message.setVisibility(View.VISIBLE);
_message.requestLayout();
}
}
public static final String MESSAGE_CONTENT = "String_message";
public static final int MESSAGE = 1000;
public static final int TOAST = 2000;
private BTSend Right;
private TachoCount tachoCount;
private Toast reusableToast;
private TextView _message;
//static final String START_MESSAGE = "Please make sure you NXT is on and both it and your Android handset have bluetooth enabled";
private static final String GO_AHEAD = "Choose one!";
public static UIMessageHandler mUIMessageHandler;
private final static String TAG = "LeJOSDroid";
public static NXTConnector connect(final CONN_TYPE connection_type) {
Log.d(TAG, " about to add LEJOS listener ");
NXTConnector conn = new NXTConnector();
conn.setDebug(true);
conn.addLogListener(new NXTCommLogListener() {
public void logEvent(String arg0) {
Log.e(TAG + " NXJ log:", arg0);
}
public void logEvent(Throwable arg0) {
Log.e(TAG + " NXJ log:", arg0.getMessage(), arg0);
}
});
switch (connection_type) {
case LEGO_LCP:
conn.connectTo("btspp://NXT", NXTComm.LCP);
break;
case LEJOS_PACKET:
conn.connectTo("btspp://");
break;
}
return conn;
}
public static void displayToastOnUIThread(String message) {
Message message_holder = formMessage(message);
message_holder.what = LeJOSDroid.TOAST;
mUIMessageHandler.sendMessage(message_holder);
}
private static Message formMessage(String message) {
Bundle b = new Bundle();
b.putString(LeJOSDroid.MESSAGE_CONTENT, message);
Message message_holder = new Message();
message_holder.setData(b);
return message_holder;
}
public static void sendMessageToUIThread(String message) {
Message message_holder = formMessage(message);
message_holder.what = LeJOSDroid.MESSAGE;
mUIMessageHandler.sendMessage(message_holder);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUIMessageHandler = new UIMessageHandler();
setContentView(R.layout.main);
_message = (TextView) findViewById(R.id.messageText);
seupNXJCache();
setupTachoCount(this);
setupRight(this);
setupBackward(this);
reusableToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
}
#Override
protected void onPause() {
super.onPause();
if (Right != null) {
Log.d(TAG, "onPause() closing btSend ");
Right.closeConnection();
Right = null;
}
if (tachoCount != null) {
Log.d(TAG, "onPause() closing btSend ");
tachoCount.closeConnection();
}
}
#Override
protected void onResume() {
super.onResume();
}
public void onCreate1 (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button3 = (Button) findViewById(R.id.button3);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.button2:
try {
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
} catch (Exception e) {
Log.e(TAG, "failed to run BTSend:" + e.getMessage(), e);
}
break;
}
}
});
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.button3:
try {
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
} catch (Exception e) {
Log.e(TAG, "failed to run TachoCount:" + e.getMessage(), e);
}
break;
}
}
});
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.button1:
try {
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
} catch (Exception e) {
Log.e(TAG, "failed to run TachoCount:" + e.getMessage(), e);
}
break;
}
}
});
}
private void seupNXJCache() {
File root = Environment.getExternalStorageDirectory();
try {
String androidCacheFile = "nxj.cache";
File mLeJOS_dir = new File(root + "/leJOS");
if (!mLeJOS_dir.exists()) {
mLeJOS_dir.mkdir();
}
File mCacheFile = new File(root + "/leJOS/", androidCacheFile);
if (root.canWrite() && !mCacheFile.exists()) {
FileWriter gpxwriter = new FileWriter(mCacheFile);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write("");
out.flush();
out.close();
_message.setText("nxj.cache (record of connection addresses) written to: " + mCacheFile.getName() + GO_AHEAD);
} else {
_message.setText("nxj.cache file not written as"
+ (!root.canWrite() ? mCacheFile.getName() + " can't be written to sdcard." : " cache already exists.") + GO_AHEAD);
}
} catch (IOException e) {
Log.e(TAG, "Could not write nxj.cache " + e.getMessage(), e);
}
_message.setVisibility(View.VISIBLE);
_message.requestLayout();
}
private void showToast(String textToShow) {
reusableToast.setText(textToShow);
reusableToast.show();
}
}
You can use this method to your Button View, to manually click it.
View.performClick();
The same you can do to other button, to click them together.
It is hard to say, why your app is closing, looking on your code. What I have noticed, is that you are doing the same work, in all 3 buttons clickMethods. In all 3 buttons you are doing:
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
Also, I see from your code, that you can use only one button onCLick listener, by combine all your listeners code together.
View.OnClickListener buttonListener = new View.OnClickListener() {
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.button1:
try {
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
} catch (Exception e) {
Log.e(TAG, "failed to run TachoCount:" + e.getMessage(), e);
}
break;
case R.id.button3:
try {
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
} catch (Exception e) {
Log.e(TAG, "failed to run TachoCount:" + e.getMessage(), e);
}
break;
case R.id.button2:
try {
tachoCount = new TachoCount();
_message.setVisibility(View.INVISIBLE);
tachoCount.start();
} catch (Exception e) {
Log.e(TAG, "failed to run BTSend:" + e.getMessage(), e);
}
break;
}
}
And later
button2.setOnClickListener(buttonListener);
Check your logfile if it is memory related issue you can increase you heap memory Increase Heap Memory
Related
I have created an android application using the DJI SDK. I have followed the instruction, and basically copied the code from the DJI Sample Code (https://github.com/dji-sdk/Mobile-SDK-Android/blob/master/Sample%20Code/app/src/main/java/com/dji/sdk/sample/demo/camera/LiveStreamView.java), since it was working properly.
After launching a Connectivity activity, which registers the SDK and connects to the Mavic 2 Zoom drone, another activity comes, which handles live streaming to a RTMP server. When using the sample code, streaming to the same RTMP server, it has no delay, but when using my app, it has a good 15 second delay. I can't figure out why, I'm using the same components. The only difference is that I'm setting the camera focus to the max, but I did the same in the Sample Code, so it shouldn't cause any problems. Also using the same VideoFeedView as in the Sample.
public class MainActivity extends Activity implements View.OnClickListener {
private static final String TAG = MainActivity.class.getName();
private String liveShowUrl = "rtmp://192.168.00.00/live";
private VideoFeedView primaryVideoFeedView;
private VideoFeedView fpvVideoFeedView;
private EditText showUrlInputEdit;
private Button startLiveShowBtn;
private Button enableVideoEncodingBtn;
private Button disableVideoEncodingBtn;
private Button stopLiveShowBtn;
private Button soundOnBtn;
private Button soundOffBtn;
private Button isLiveShowOnBtn;
private Button showInfoBtn;
private Button showLiveStartTimeBtn;
private Button showCurrentVideoSourceBtn;
private Button changeVideoSourceBtn;
private Camera camera;
private LiveStreamManager.OnLiveChangeListener listener;
private LiveStreamManager.LiveStreamVideoSource currentVideoSource = LiveStreamManager.LiveStreamVideoSource.Primary;
private CommonCallbacks.CompletionCallback focusSetCompletionCallback = new CommonCallbacks.CompletionCallback() {
#Override
public void onResult(DJIError djiError) {
Log.d(TAG, "Camera focus is set to manual");
Toast.makeText(getApplicationContext(), "camera focus set to manual", Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
initListener();
camera = DronifyApplication.getCameraInstance();
camera.getFocusRingValueUpperBound(new CommonCallbacks.CompletionCallbackWith<Integer>() {
#Override
public void onSuccess(Integer integer) {
Toast.makeText(getApplicationContext(), "UPPER IS: " + integer.toString(),Toast.LENGTH_LONG).show();
Log.d(TAG, "UPPER IS: " + integer.toString());
}
#Override
public void onFailure(DJIError djiError) {
Toast.makeText(getApplicationContext(), "UPPER IS NOT SUPPORTED", Toast.LENGTH_LONG).show();
}
});
camera.setFocusMode(SettingsDefinitions.FocusMode.MANUAL, focusSetCompletionCallback);
if (camera.isAdjustableFocalPointSupported()) {
camera.setFocusRingValue(65, new CommonCallbacks.CompletionCallback() {
#Override
public void onResult(DJIError djiError) {
Log.i(TAG, "set focus ring value to max");
Toast.makeText(getApplicationContext(), "set focus ring value to max", Toast.LENGTH_SHORT).show();
}
});
}
Intent intent = new Intent(getApplication(), TCPService.class);
getApplication().startService(intent);
}
#Override
protected void onResume() {
super.onResume();
}
public static boolean isMultiStreamPlatform() {
if (DJISDKManager.getInstance() == null){
return false;
}
Model model = DJISDKManager.getInstance().getProduct().getModel();
return model != null && (model == Model.INSPIRE_2
|| model == Model.MATRICE_200
|| model == Model.MATRICE_210
|| model == Model.MATRICE_210_RTK
|| model == Model.MATRICE_600
|| model == Model.MATRICE_600_PRO
|| model == Model.A3
|| model == Model.N3);
}
private void initUI() {
primaryVideoFeedView = (VideoFeedView) findViewById(R.id.video_view_primary_video_feed);
primaryVideoFeedView.registerLiveVideo(VideoFeeder.getInstance().getPrimaryVideoFeed(), true);
fpvVideoFeedView = (VideoFeedView) findViewById(R.id.video_view_fpv_video_feed);
fpvVideoFeedView.registerLiveVideo(VideoFeeder.getInstance().getSecondaryVideoFeed(), false);
if (isMultiStreamPlatform()){
fpvVideoFeedView.setVisibility(View.VISIBLE);
}
showUrlInputEdit = (EditText) findViewById(R.id.edit_live_show_url_input);
showUrlInputEdit.setText(liveShowUrl);
startLiveShowBtn = (Button) findViewById(R.id.btn_start_live_show);
enableVideoEncodingBtn = (Button) findViewById(R.id.btn_enable_video_encode);
disableVideoEncodingBtn = (Button) findViewById(R.id.btn_disable_video_encode);
stopLiveShowBtn = (Button) findViewById(R.id.btn_stop_live_show);
soundOnBtn = (Button) findViewById(R.id.btn_sound_on);
soundOffBtn = (Button) findViewById(R.id.btn_sound_off);
isLiveShowOnBtn = (Button) findViewById(R.id.btn_is_live_show_on);
showInfoBtn = (Button) findViewById(R.id.btn_show_info);
showLiveStartTimeBtn = (Button) findViewById(R.id.btn_show_live_start_time);
showCurrentVideoSourceBtn = (Button) findViewById(R.id.btn_show_current_video_source);
changeVideoSourceBtn = (Button) findViewById(R.id.btn_change_video_source);
startLiveShowBtn.setOnClickListener(this);
enableVideoEncodingBtn.setOnClickListener(this);
disableVideoEncodingBtn.setOnClickListener(this);
stopLiveShowBtn.setOnClickListener(this);
soundOnBtn.setOnClickListener(this);
soundOffBtn.setOnClickListener(this);
isLiveShowOnBtn.setOnClickListener(this);
showInfoBtn.setOnClickListener(this);
showLiveStartTimeBtn.setOnClickListener(this);
showCurrentVideoSourceBtn.setOnClickListener(this);
changeVideoSourceBtn.setOnClickListener(this);
}
private void initListener() {
showUrlInputEdit.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
liveShowUrl = s.toString();
}
#Override
public void afterTextChanged(Editable s) {
}
});
listener = new LiveStreamManager.OnLiveChangeListener() {
#Override
public void onStatusChanged(int i) {
//Toast.makeText(getApplicationContext(), "status changed : " + i, Toast.LENGTH_SHORT).show();
}
};
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
BaseProduct product = DronifyApplication.getProductInstance();
if (product == null || !product.isConnected()) {
//Toast.makeText(getApplicationContext(), "disconnected", Toast.LENGTH_SHORT).show();
return;
}
if (isLiveStreamManagerOn()){
DJISDKManager.getInstance().getLiveStreamManager().registerListener(listener);
}
}
#Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (isLiveStreamManagerOn()){
DJISDKManager.getInstance().getLiveStreamManager().unregisterListener(listener);
}
}
private boolean isLiveStreamManagerOn() {
if (DJISDKManager.getInstance().getLiveStreamManager() == null) {
//Toast.makeText(getApplicationContext(), "no liveStream manager", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start_live_show:
startLiveShow();
break;
case R.id.btn_enable_video_encode:
enableReEncoder();
break;
case R.id.btn_disable_video_encode:
disableReEncoder();
break;
case R.id.btn_stop_live_show:
stopLiveShow();
break;
case R.id.btn_sound_on:
soundOn();
break;
case R.id.btn_sound_off:
soundOff();
break;
case R.id.btn_is_live_show_on:
isLiveShowOn();
break;
case R.id.btn_show_info:
showInfo();
break;
case R.id.btn_show_live_start_time:
showLiveStartTime();
break;
case R.id.btn_show_current_video_source:
showCurrentVideoSource();
break;
case R.id.btn_change_video_source:
changeVideoSource();
break;
default:
break;
}
}
private void enableReEncoder() {
if (!isLiveStreamManagerOn()) {
return;
}
DJISDKManager.getInstance().getLiveStreamManager().setVideoEncodingEnabled(true);
Toast.makeText(getApplicationContext(), "Force Re-Encoder Enabled!", Toast.LENGTH_SHORT).show();
}
private void disableReEncoder() {
if (!isLiveStreamManagerOn()) {
return;
}
DJISDKManager.getInstance().getLiveStreamManager().setVideoEncodingEnabled(false);
Toast.makeText(getApplicationContext(), "Disable Force Re-Encoder!", Toast.LENGTH_SHORT).show();
}
private void soundOn() {
if (!isLiveStreamManagerOn()) {
return;
}
DJISDKManager.getInstance().getLiveStreamManager().setAudioMuted(false);
Toast.makeText(getApplicationContext(), "Sound ON", Toast.LENGTH_SHORT).show();
}
private void soundOff() {
if (!isLiveStreamManagerOn()) {
return;
}
DJISDKManager.getInstance().getLiveStreamManager().setAudioMuted(true);
Toast.makeText(getApplicationContext(), "Sound OFF", Toast.LENGTH_SHORT).show();
}
private void isLiveShowOn() {
if (!isLiveStreamManagerOn()) {
return;
}
Toast.makeText(getApplicationContext(), "Is Live Show On:" + DJISDKManager.getInstance().getLiveStreamManager().isStreaming(), Toast.LENGTH_SHORT).show();
}
private void showLiveStartTime() {
if (!isLiveStreamManagerOn()) {
return;
}
if (!DJISDKManager.getInstance().getLiveStreamManager().isStreaming()){
Toast.makeText(getApplicationContext(), "Please Start Live First", Toast.LENGTH_SHORT).show();
return;
}
long startTime = DJISDKManager.getInstance().getLiveStreamManager().getStartTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String sd = sdf.format(new Date(Long.parseLong(String.valueOf(startTime))));
Toast.makeText(getApplicationContext(), "Live Start Time: " + sd, Toast.LENGTH_SHORT).show();
}
private void changeVideoSource() {
if (!isLiveStreamManagerOn()) {
return;
}
if (!isSupportSecondaryVideo()) {
return;
}
if (DJISDKManager.getInstance().getLiveStreamManager().isStreaming()) {
Toast.makeText(getApplicationContext(), "Before change live source, you should stop live stream!", Toast.LENGTH_SHORT).show();
return;
}
currentVideoSource = (currentVideoSource == LiveStreamManager.LiveStreamVideoSource.Primary) ?
LiveStreamManager.LiveStreamVideoSource.Secoundary :
LiveStreamManager.LiveStreamVideoSource.Primary;
DJISDKManager.getInstance().getLiveStreamManager().setVideoSource(currentVideoSource);
Toast.makeText(getApplicationContext(), "Change Success ! Video Source : " + currentVideoSource.name(), Toast.LENGTH_SHORT).show();
}
private void showCurrentVideoSource(){
Toast.makeText(getApplicationContext(), "Video Source : " + currentVideoSource.name(), Toast.LENGTH_SHORT).show();
}
private boolean isSupportSecondaryVideo(){
if (isMultiStreamPlatform()) {
Toast.makeText(getApplicationContext(), "No secondary video!", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void showInfo() {
StringBuilder sb = new StringBuilder();
sb.append("Video BitRate:").append(DJISDKManager.getInstance().getLiveStreamManager().getLiveVideoBitRate()).append(" kpbs\n");
sb.append("Audio BitRate:").append(DJISDKManager.getInstance().getLiveStreamManager().getLiveAudioBitRate()).append(" kpbs\n");
sb.append("Video FPS:").append(DJISDKManager.getInstance().getLiveStreamManager().getLiveVideoFps()).append("\n");
sb.append("Video Cache size:").append(DJISDKManager.getInstance().getLiveStreamManager().getLiveVideoCacheSize()).append(" frame");
Toast.makeText(getApplicationContext(), sb.toString(), Toast.LENGTH_LONG).show();
}
void startLiveShow() {
Toast.makeText(getApplicationContext(), "start live show: " + isLiveStreamManagerOn(), Toast.LENGTH_SHORT).show();
if (!isLiveStreamManagerOn()) {
Toast.makeText(getApplicationContext(), "1. return", Toast.LENGTH_SHORT).show();
return;
}
if (DJISDKManager.getInstance().getLiveStreamManager().isStreaming()) {
Toast.makeText(getApplicationContext(), "live show already started", Toast.LENGTH_SHORT).show();
return;
}
new Thread() {
#Override
public void run() {
DJISDKManager.getInstance().getLiveStreamManager().setLiveUrl(liveShowUrl);
DJISDKManager.getInstance().getLiveStreamManager().setVideoEncodingEnabled(true);
DJISDKManager.getInstance().getLiveStreamManager().setAudioMuted(false);
final int result = DJISDKManager.getInstance().getLiveStreamManager().startStream();
DJISDKManager.getInstance().getLiveStreamManager().setStartTime();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplication(), "RESULT: " + result, Toast.LENGTH_SHORT).show();
}
});
}
}.start();
}
private void stopLiveShow() {
if (!isLiveStreamManagerOn()) {
return;
}
DJISDKManager.getInstance().getLiveStreamManager().stopStream();
Toast.makeText(getApplicationContext(), "stop live show", Toast.LENGTH_SHORT).show();
}
}
Any idea why? I have tested it on Google Pixel 2, and Huawei Mate 10. The sample has no problem on both devices, my app has the delay. Thanks!
Answering my own question, the only difference I noticed was that the SampleCode asked for 4 permission, and all the projects I've tried or copied the permissions, always just 3 permissions.
So Manifest:
< uses-permission android:name="android.permission.RECORD_AUDIO" />
your runtime permissions:
Manifest.permission.RECORD_AUDIO
and the delay is gone, all works fine. Still don't know why :)
Theres edit text field. It has to work like this:
1) if it is empty - nothing happen
2) if user put some NEW text starts method of TextWatcher with HTTP request which takes JSON object. Also the value of String will put in sharedpreference
3) if user open activity when sharedpreference already have value of previous string it has to just set text from that string and don't start method of TextWatcher with HTTP request.
So there are three conditions and progrmm has to make request only in case when value of string is not tha same as in shared pref. Now it sends request even if person just open app. I want to avoid wrong requests and make request only after new value of string.
THE MAIN QUESTION: How to launch HTTP request code ONLY in case if value in textfield is not the same as in sharedpref?
P.S. If you think my question is bad. Please tell me in notes NOT JUST MAKE -1 please. Teach new programmers
Here is the code
public class MainActivity extends AppCompatActivity {
AppCompatButton chooseLanguageButton;
AppCompatButton cleanButton;
AppCompatEditText translatedTextOutput;
AppCompatEditText translatedTextInput;
String translatedInputString;
RequestQueue requestQueue;
final String TAG = "myTag";
String language;
SharedPreferences mSettings;
SharedPreferences textReference;
SharedPreferences translateReference;
SharedPreferences longLangReference;
SharedPreferences shortLangReference;
final String SAVED_TEXT = "text";
final String SAVED_TRANSLATION = "translation";
final String LANGUAGE_LONG = "lang_long";
final String LANGUAGE_SHORT = "lang_short";
public static final String APP_PREFERENCES = "mysettings";
private ProgressBar progressBar;
private Timer timer;
private TextWatcher searchTextWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
Log.v(TAG, "in afterTextChanged");
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (translatedTextInput.getText().length() != 0){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
requestQueue = Volley.newRequestQueue(MainActivity.this);
sendJsonRequest();
}
});
}
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(translatedTextInput.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 600);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (timer != null) {
timer.cancel();
}
saveText();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "in Oncreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseLanguageButton = (AppCompatButton) findViewById(R.id.choose_language_button);
cleanButton = (AppCompatButton) findViewById(R.id.clean_button);
translatedTextOutput = (AppCompatEditText) findViewById(R.id.translated_text_field);
translatedTextInput = (AppCompatEditText) findViewById(R.id.translation_input_edit);
int textLength = translatedTextInput.getText().length();
translatedTextInput.setSelection(textLength);
translatedTextInput.addTextChangedListener(searchTextWatcher);
chooseLanguageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v(TAG, "in chooseLanguageListener");
Intent intent = new Intent(MainActivity.this, ChooseLanguageList.class);
startActivity(intent);
}
});
cleanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
translatedTextInput.setText("");
translatedTextOutput.setText("");
}
});
mSettings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
if (mSettings.contains(LANGUAGE_LONG)){
Log.v(TAG, "here");
chooseLanguageButton.setText(mSettings.getString(LANGUAGE_LONG,""));
} else {
Log.v(TAG, "THERE");
chooseLanguageButton.setText("Choose language");
}
if (mSettings.contains(SAVED_TEXT)){
Log.v(TAG, "here");
translatedTextInput.setText(mSettings.getString(SAVED_TEXT,""));
} else {
Log.v(TAG, "boooooom");
}
if (mSettings.contains(SAVED_TRANSLATION)){
Log.v(TAG, "here in TRANSLATION FIELD" + mSettings.getString(SAVED_TRANSLATION,""));
translatedTextOutput.setText(mSettings.getString(SAVED_TRANSLATION,""));
} else {
Log.v(TAG, "boooooom");
}
}
#Override
protected void onResume() {
super.onResume();
translatedTextInput.post(new Runnable() {
#Override
public void run() {
Selection.setSelection(translatedTextInput, );
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mSettings = null;
}
void saveText() {
// mSettings = getSharedPreferences(SAVED_TEXT, MODE_PRIVATE);
SharedPreferences.Editor ed = mSettings.edit();
ed.putString(SAVED_TEXT, translatedTextInput.getText().toString());
ed.putString(SAVED_TRANSLATION, translatedTextOutput.getText().toString());
ed.apply();
Log.v(TAG, "Text saved==========>" + translatedTextInput.getText().toString());
Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
}
void loadText() {
textReference = getSharedPreferences(SAVED_TEXT, MODE_PRIVATE);
translatedTextInput.setText(mSettings.getString(SAVED_TEXT,""));
translateReference = getSharedPreferences(SAVED_TRANSLATION, MODE_PRIVATE);
translatedTextOutput.setText(mSettings.getString(SAVED_TRANSLATION,""));
Log.v(TAG, "IN LOAD TEXT METHOD" + mSettings.getString(SAVED_TEXT,""));
Log.v(TAG, "IN LOAD TRANSLATION METHOD" + mSettings.getString(SAVED_TRANSLATION,""));
}
public void sendJsonRequest() {
Log.v(TAG, "in sendJsonObject");
Intent myIntent = getIntent();
// language = myIntent.getStringExtra("short");
shortLangReference = getSharedPreferences(LANGUAGE_SHORT, MODE_PRIVATE);
language = mSettings.getString(LANGUAGE_SHORT,"");
Log.v(getClass().getSimpleName(), "language short = " + language);
translatedInputString = translatedTextInput.getText().toString().replace(" ","+");
String url = String.format(getApplicationContext().getResources().getString(R.string.request_template),
String.format(getApplicationContext().getResources().getString(R.string.query_Template), translatedInputString, language ));
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v(TAG, "Inside OnResponse" + response.toString());
JSONArray results = null;
try {
results = response.getJSONObject("data").getJSONArray("translations");
for (int i=0,j=results.length();i<j;i++) {
String webTitle = results.getJSONObject(i).getString("translatedText");
translatedTextOutput.setText(webTitle);
}
} catch (JSONException e) {
Log.e(TAG, "Error :" + e);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
Log.e(TAG, "NetworkError");
} else if (error instanceof ServerError) {
Log.e(TAG, "The server could not be found. Please try again after some time!!");
} else if (error instanceof AuthFailureError) {
Log.e(TAG, "AuthFailureError");
} else if (error instanceof ParseError) {
Log.e(TAG, "Parsing error! Please try again after some time!!");
} else if (error instanceof NoConnectionError) {
Log.e(TAG, "NoConnectionError!");
} else if (error instanceof TimeoutError) {
Log.e(TAG, "Connection TimeOut! Please check your internet connection.");
}
}
});
requestQueue.add(jsObjRequest);
}
}
I want to make a TCP client that can sent and receive data for server. I use Hercules(TCP/UDP test program) as Server. My code can send string "Submit" to Server. I try to make my code can receive data from Hercules but it not work.what I have to do for edit it?
This is my MainActivity code
public class MainActivity extends Activity {
// Used to reference UI elements of main.xml
private TextView text,serverResponse;
private EditText ipBox;
private EditText portBox;
private ToggleButton connect;
private Button send;
private static final String TAG = "CClient";
private String ipAddress;
private Socket client;
private DataOutputStream outToServer;
private DataInputStream inFromServer;
private boolean connected = false;
private final int START = 0xffffff;
private final int msgBoxHint = START;
private final int appendText = START + 1;
Toast mytoast , savetoast;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Log.d(TAG, "Here 1");
ipAddress = getLocalIpAddress();
Log.d(TAG, "Get local IP="+ ipAddress);
text = (TextView) findViewById(R.id.text);
ipBox = (EditText) findViewById(R.id.ipBox);
serverResponse = (TextView) findViewById(R.id.response);
portBox = (EditText) findViewById(R.id.portBox);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(buttonsendOnClickListener);
connect = (ToggleButton) findViewById(R.id.connect);
connect.setOnClickListener(buttonConnectOnClickListener);
Button buttonExit = (Button) findViewById(R.id.btnExit);
buttonExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "Exit");
Log.d(TAG, "Disconnect" );
if(client != null)
{
try {
client.close();
} catch (IOException e) {
Log.d(TAG, "Disconnect"+e.toString() );
}
}
finish();
}
});
}
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
/** Manages all button clicks from the screen */
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.connect:
if(connect.isChecked())
{
Log.d(TAG, "Connect" );
EditText edIP = (EditText) findViewById(R.id.ipBox);
String ed_textIP = edIP.getText().toString().trim();
if(ed_textIP.isEmpty() || ed_textIP.length() == 0 || ed_textIP.equals("") || ed_textIP == null )
{
Toast.makeText(MainActivity.this, "IP Address or PORT is incorrect", Toast.LENGTH_SHORT).show();
Log.d(TAG, "IP Address or PORT is incorrect");
}
setValues(R.id.connect,true);
setValues(R.id.send,true);
setValues(R.id.ipBox,false);
String tMsg = welcomeMsg.toString();
MyClientTask myClientTask = new MyClientTask(ipBox
.getText().toString(), Integer.parseInt(portBox
.getText().toString()),
tMsg);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
myClientTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
myClientTask.execute();
}
else
{ /*Toast.makeText(this, ipBox.getText(), Toast.LENGTH_LONG).show();*/
Log.d(TAG, "Disconnect" );
if(client != null)
{
try {
client.close();
} catch (IOException e) {
Log.d(TAG, "Disconnect"+e.toString() );
}
setText(R.id.text,"Press the connect button to start the client");
setText(msgBoxHint,"");
setValues(R.id.connect,false);
setValues(R.id.ipBox,true);
setValues(R.id.send,false);
}
else
{
setValues(R.id.connect,false);
}
}
break;
}
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String msgToServer;
MyClientTask(String addr, int port, String msgTo) {
dstAddress = addr;
dstPort = port;
msgToServer = msgTo;
}
protected Void doInBackground(Void... Arg0) {
Log.d(TAG, "InBackground");
Socket socket = null;
DataOutputStream outToServer = null;
DataInputStream inFromServer = null;
try {
client = new Socket(dstAddress, dstPort);
outToServer = new DataOutputStream(client.getOutputStream());
inFromServer = new DataInputStream(new BufferedInputStream(client.getInputStream())); // Input stream <- from server
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.d(TAG, "InBackground 1");
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mytoast = Toast.makeText(MainActivity.this, "Error UnknownHostException",
Toast.LENGTH_SHORT);
mytoast.show();
setValues(R.id.send,false);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mytoast.cancel();
}
}, 500);
}
});
} catch (IOException e) {
Log.d(TAG, "InBackground 2");
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mytoast = Toast.makeText(MainActivity.this, "Error IOException",
Toast.LENGTH_SHORT);
mytoast.show();
setValues(R.id.connect,false);
setValues(R.id.send,false);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mytoast.cancel();
}
}, 500);
}
});
}finally {
Log.d(TAG, "InBackground 3");
if (socket != null) {
try {
socket.close();
Log.d(TAG, "InBackground 3.11");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "InBackground 3.12");
}
}
Log.d(TAG, "InBackground 3.1");
}
Log.d(TAG, "InBackground 4");
return null;
}
#Override
protected void onPostExecute(Void result) {
serverResponse.setText(response);
super.onPostExecute(result);
}
}
OnClickListener buttonsendOnClickListener = new OnClickListener() {
/** Manages all button clicks from the screen */
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.send:
Log.d(TAG, "Sent" );
String sentence = "Submit";
String recieve = "";
serverResponse = (TextView) findViewById(R.id.response);
try {
outToServer = new DataOutputStream(client.getOutputStream());
inFromServer = new DataInputStream(new BufferedInputStream(client.getInputStream()));
Log.d(TAG, "Sent 1-1" );
if(sentence != null){
outToServer.writeUTF(sentence);
outToServer.flush();
}
/*
*
*
*
*
*
*/
Log.d(TAG, "Sent 1-2"+ recieve);
} catch (IOException e) {
setValues(R.id.ipBox,true);
setValues(R.id.connect,false);
setValues(R.id.send,false);
}
break;
}
}
};
private String getLocalIpAddress() {
Log.d(TAG, "Here 2");
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Log.d(TAG, "Here 3");
WifiInfo info = wifi.getConnectionInfo();
Log.d(TAG, "Here 4");
return Formatter.formatIpAddress(info.getIpAddress());
}
private void setText(int view, String content)
{
switch(view)
{
case R.id.ipBox: ipBox.setText(content); break;
case R.id.text: text.setText(content+"\n\n"); break;
case appendText: text.append(content+"\n\n"); break;
}
}
private void setValues(int view, boolean value)
{
switch(view)
{
case R.id.ipBox: ipBox.setEnabled(value); break;
case R.id.send: send.setEnabled(value); break;
case R.id.connect: connect.setChecked(value); break;
}
}
}
I think, I have to add receive code in buttonsendOnClickListener near /*****/.
Do not work with sockets in main (gui) thread. Use AsyncTask!
Android fails if work with sockets in main (gui) thread.
Example:
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
// do in main thread before
}
#Override
protected Void doInBackground(Void... v) {
// do in thread, use sockets
return null;
}
#Override
protected void onPostExecute(Void v) {
super.onPostExecute(integer);
// do in main thread after
}
}.execute();
Learn about AsyncTask advance.
I have a big struggle in sending bytes through Bluetooth in Android, I would make clear that I have watched several tutorial and the Android developers' page.
What my app essentially does is to turn on/off Bluetooth, search devices and connect to them, list the paired devices and also connect to them and it has a control (they are just ImageButtons that send data), I have to activities for when the user searches for a device and for when it wants to see the paired devices so if sending data works on one of them it can work on the other one.
My struggle is on sending the data and it clearly seems that I am doing something wrong in the code. I have saturated the code with toast to know when I do some steps of my app (this toast will be removed once I finish this last step of my app).
And in these saturation I found that my code actually sends the bytes but it does not seems to send them, which is something I do not know how to solve (my code connects to the other Bluetooth device - it even stops flashing its red LED to tell me and the log tell that I am connected to it), I have even copied some code and change it to be part of mine and do what I want it to do.
My XML has all of the necessary permissions.
Code:
public class SerachDevices extends ActionBarActivity {
private final BluetoothAdapter BT = BluetoothAdapter.getDefaultAdapter();
private BluetoothDevice bluetoothDevice;
ListView FoundD;
ImageButton btBUp;
ImageButton btBDown;
ImageButton btBLeft;
ImageButton btBRigth;
ImageButton btBStop;
String mensaje; private ArrayAdapter<String> discoveredDevices;
int Gone = View.GONE;
int Visible = View.VISIBLE;
ConexionABluetooth conectar;
//Metod to find devices
public void Descubrir() {
BT.startDiscovery();
if (BT.startDiscovery()) {
mensaje = "Buscando dispositivos";
Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_SHORT).show();
} else {
mensaje = "Fallo la busqueda de dispositivos";
Toast.makeText(getApplicationContext(), mensaje, Toast.LENGTH_SHORT).show();
}
}
//Reciever for found device
private final BroadcastReceiver FoundDReciever = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
discoveredDevices.add(bluetoothDevice.getName() + "\n" + bluetoothDevice.getAddress());
}
}
};
//Brings up the imageviews, to control the robot
public void btControl(View view) {
if (!BT.isEnabled()) {
mensaje = "Activate bluetooth to use control";
Toast.makeText(getBaseContext(), mensaje, Toast.LENGTH_SHORT).show();
} else {
FoundD.setVisibility(Gone);
btBUp.setVisibility(Visible);
btBDown.setVisibility(Visible);
btBLeft.setVisibility(Visible);
btBRigth.setVisibility(Visible);
btBStop.setVisibility(Visible);
}
}
public void btUp(View view) {
if(BT.isEnabled()){
String w = "w";
conectar.write(w);
Toast.makeText(getBaseContext(), w, Toast.LENGTH_SHORT).show();
}else{
mensaje = "make sure you have \nan active bluetooth connection";
}
}
public void btDown(View view) {
if(BT.isEnabled()){
String s = "s";
conectar.write(s);
Toast.makeText(getBaseContext(), s, Toast.LENGTH_SHORT).show();
}else{
mensaje = "make sure you have \n" +
"an active bluetooth connection";
}
}
public void btLeft(View view) {
if(BT.isEnabled()){
String a = "a";
conectar.write(a);
Toast.makeText(getBaseContext(), a, Toast.LENGTH_SHORT).show();
}else{
mensaje = "make sure you have \n" +
"an active bluetooth connection";
}
}
public void btRigth(View view) {
if(BT.isEnabled()){
String d = "d";
conectar.write(d);
Toast.makeText(getBaseContext(), d, Toast.LENGTH_SHORT).show();
}else{
mensaje = "make sure you have \n" +
"an active bluetooth connection";
}
}
public void btStop(View view) {
if(BT.isEnabled()){
String q = "q";
conectar.write(q);
Toast.makeText(getBaseContext(), q, Toast.LENGTH_SHORT).show();
}else{
mensaje = "make sure you have \n" +
"an active bluetooth connection";
}
}
#Override
protected void onResume() {
super.onResume();
// Register the BroadcastReceiver for ACTION_FOUND
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(FoundDReciever, filter);
}
#Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(FoundDReciever);
}
//Star onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_serach_devices);
btBUp = (ImageButton) findViewById(R.id.btUp);
btBDown = (ImageButton) findViewById(R.id.btDown);
btBRigth = (ImageButton) findViewById(R.id.btRight);
btBLeft = (ImageButton) findViewById(R.id.btLeft);
btBStop = (ImageButton) findViewById(R.id.btStop);
FoundD = (ListView) findViewById(R.id.btFoundD);
discoveredDevices = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
Descubrir();
FoundD.setAdapter(discoveredDevices);
FoundD.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemValue = (String) FoundD.getItemAtPosition(position);
String MAC = itemValue.substring(itemValue.length() - 17);
BluetoothDevice bluetoothDevice = BT.getRemoteDevice(MAC);
if (BT.isEnabled()) {
conectar = new ConexionABluetooth(bluetoothDevice);
conectar.start();
} else if (!BT.isEnabled()) {
mensaje = "Bluetooth is not activated";
Toast.makeText(getBaseContext(), mensaje, Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_serach_devices, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
////////////////////////////////////////////////////////////////////////////////
public class ConexionABluetooth extends Thread {
public OutputStream btOutputStream = null;
private BluetoothDevice btShield;
public BluetoothSocket mySocket = null;
private UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConexionABluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try {
mySocket = btShield.createRfcommSocketToServiceRecord(SPP_UUID);
try {
BT.cancelDiscovery();
mySocket.connect();
try {
btOutputStream = mySocket.getOutputStream();
mensaje = "Output catched";
Toast.makeText(getBaseContext(), mensaje, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.e("ConnectToBluetooth", "Error when getting output Stream");
}
} catch (IOException e) {
Log.e("ConnectToBluetooth", "Error with Socket Connection");
}
} catch (IOException e) {
Log.e("ConnectToBluetooth", "Error with Socket Creation");
try {
mySocket.close();
} catch (IOException closeException) {
Log.e("ConnectToBluetooth", "Error Closing socket");
}
return;
}
}
#Override
public void run() {
Log.d("fail to send", "...In onPause()...");
if (btOutputStream != null) {
try {
btOutputStream.flush();
} catch (IOException e) {
Log.d("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
mySocket.connect();
} catch (IOException connectException) {
try {
mySocket.close(); //try to close the socket
} catch (IOException closeException) {
}
return;
}
}
public void write(String str) {
try {
byte[] sd = str.getBytes();
mensaje = "Message send";
Toast.makeText(getBaseContext(), mensaje, Toast.LENGTH_SHORT).show();
btOutputStream.write(sd);
} catch (IOException e) {
Log.e("Writing to Stream", "Error when writing to btOutputStream");
}
}
public void cancel() {
try {
mySocket.close();
} catch (IOException e) {
}
}
}
}
I'm trying to show an animation in my app while connecting to a web server, just so that the user doesn't think that it's crashed/frozen.
Here's the bit in the code that may be relevant:
private void waitForWebSocketConnect() {
long start = System.currentTimeMillis();
long end = start + 3*1000; // 3 seconds
while (!mWebSocketClient.isOpen()) {
try {
Thread.sleep(200);
if(System.currentTimeMillis() >= end){
throw new InterruptedException();
}
} catch (InterruptedException e) {
fatalError("WebSocket did not connect. Please try again.");
}
}
}
I think this might also be of use:
private void connectWebSocket() {
final Activity faActivity = super.getActivity();
URI uri;
try {
String uriString;
if(isRegistering){
//uriString = "ws://app.touchtechpayments.com:80/reg";
uriString = "wss://ec2-52-16-13-241.eu-west-1.compute.amazonaws.com/reg";
} else {
//uriString = "ws://app.touchtechpayments.com:80/trans";
uriString = "wss://ec2-52-16-13-241.eu-west-1.compute.amazonaws.com/trans";
}
Log.d("uriString", uriString);
uri = new URI(uriString);
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
this.progressBar.setVisibility(View.GONE);
Log.d("Websocket", "Opened");
}
#Override
public void onMessage(String s) {
Log.d("Websocket", "Received message " + s);
if(isRegistering) {
confirmRegistration(s);
} else {
confirmTransaction(s);
}
}
#Override
public void onClose(int i, String s, boolean b) {
Log.d("Websocket", "Closed " + s);
if(!allDone) {
if (triedTwice) {
final String printToast = "Error received: " + s + "\nPlease try again.";
faActivity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, printToast, Toast.LENGTH_LONG).show();
faActivity.getFragmentManager().popBackStack();
}
});
} else {
Log.d("Websocket", "Trying for second time.");
triedTwice = true;
if (lastInputToServer != null) {
setupSSL();
connectWebSocket();
waitForWebSocketConnect();
mWebSocketClient.send(lastInputToServer);
}
}
}
}
#Override
public void onError(Exception e) {
this.progressBar.setVisibility(View.GONE);
Log.d("Websocket", "Error " + e.getMessage());
}
};
setupSSL();
mProgressBar.setVisibility(View.VISIBLE);
mWebSocketClient.connect();
}
The webSocketClient isn't actually defined in onCreate(), but the above method IS used in onCreate() anyway.
First define a ProgressBar in your layout.xml and enable the indeterminate mode by using indeterminate parameter:
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:indeterminate = "true"/>
Then hide your progressBar as soon as the websocket connection has been established:
public void onCreate(){
[...]
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mWebSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake){
this.progressBar.setVisibility(View.GONE); // or INVISIBLE
}
#Override
public void onMessage(String s) {
}
#Override
public void onClose(int i, String s, boolean b) {
}
#Override
public void onError(Exception e) {
this.progressBar.setVisibility(View.GONE); // or INVISIBLE
}
};
mProgressBar.setVisibility(View.VISIBLE);
mWebSocketClient.connect();
}
You can also define your ProgressBar as invisible and show it later before mWebSocketClient.connect() call.
P.S. I'm using this java websocket library in this example
dependencies {
compile "org.java-websocket:Java-WebSocket:1.3.0"
}
you can use j Progress bar in the program simultaneously with timer so it will be ok for the user to see the moving progress bar...if you want so reply me i will give you the coding of how to use the progress bar...