android app using Socket IO not logging in - java

I'm creating an app in Android using Socket.IO. I am stuck at the Login itself. Here is my code for Login
public class MainActivity extends AppCompatActivity {
EditText uname_et, pwd_et;
Button log;
String username, password;
private Socket mSocket;
private Emitter.Listener onLogin = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e(args[0].toString(), "data");
Log.w("yes ", "in evtLogin");
// JSONObject data = (JSONObject) args[0];
}
};
{
try {
String URL = "http://MYIP:8081";
mSocket = IO.socket(URL);
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname_et = (EditText) findViewById(R.id.username_input);
pwd_et = (EditText) findViewById(R.id.pwd);
log = (Button) findViewById(R.id.sign_in_button);
log.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signin();
}
});
mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i("Make Emit", "Emit");
Log.w(mSocket.connected() + " - ", "Connection status");
}
});
mSocket.on("evtLogin", onLogin);
mSocket.connect();
}
private void signin() {
username = uname_et.getText().toString();
password = pwd_et.getText().toString();
mSocket.emit("userName", username);
mSocket.emit("Password", password);
}
#Override
protected void onDestroy() {
super.onDestroy();
mSocket.off("evtLogin", onLogin);
}
}
I'm not sure that socket is even connected or not, I'm gettong logs from Socket.EVENT_CONNECT
08-31 12:22:22.062 13399-13441/com.fis.kotsocket I/Make Emit﹕ Emit
08-31 12:22:22.063 13399-13441/com.fis.kotsocket W/true -﹕ Connection status
But onLogin listener is not called.
As a newbie I am not sure what to do exactly.
js code
//code for login event
socket.on('evtLogin', function (loginData) {
console.log('loged');
User.findOne({'login.userName':loginData.userName,'login.password':loginData.password},function(err,user){
if(err){throw err;}
else {if(!user){
console.log('not a authenticated user');
}
else
{
var userType;
User.find({'login.userName':loginData.userName,'login.password':loginData.password},function(err,rslt){
if(err){throw err;}
else
{
userType = JSON.stringify(rslt[0]['userType'].userId);
socket.emit('evtUserType',userType);
}
})
}
}
});
console.log('done');
});

Your socket is not getting initialized.
Try this initialization:
private Socket mSocket;
{
try {
mSocket = IO.socket("enter url here");
} catch (URISyntaxException e) {}
}
Or it might be that you are not emitting the evtLogin event from your javascript code.

Related

How to reconnect MQTT with this program?

I'm have some project, realtime sending RSSI and MAC of Bluetooth Low Energy.
I've seen questions regarding MQTT reconnecting. But I'm confused when it is applied to my origin code.
MainActivity.Java
public class MainActivity extends AppCompatActivity {
private Button turnon, changeLayout;
MqttAndroidClient client;
private boolean state=false;
private BluetoothAdapter bluetoothAdapter;
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
public static String mqtt_server,mqtt_port,mqtt_id,mqtt_topic;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
Log.d("Logger", "On Create Android");
turnon = findViewById(R.id.turnon);
changeLayout = findViewById(R.id.mqttSet);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
textView = findViewById(R.id.textView4);
textView.setText("id "+mqtt_id+" port "+mqtt_port+" server "+mqtt_server);
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://"+mqtt_server+":"+mqtt_port,mqtt_id);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stateCheck();
Log.d("Logger", "State Check");
handler.postDelayed(this, 1000);
}
}, 1000);
turnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!state){
turnon.setText("Turn Off");
Log.d("Logger", "Turn On State");
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null||mqtt_topic!=null){
try {
Log.d("Logger", "Try ");
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("Logger", "Connect MQTT");
Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d("Logger", "Connect Failed");
Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
Log.d("Logger", "error"+e);
}}
state = true;
}else{
turnon.setText("Turn On");
state = false;
}
}
});
changeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,MqttActivity.class));
}
});
}
public void stateCheck(){
if (state){
Log.d("Logger", "Discover");
}
}
}
The code I made has not been able to reconnect when my server restarts.
Can anyone help me? But I'm asking for help with indicating which code I should change. Thanks

Attempting to Publish message from Android to Raspberry pi using MQTT

I own raspberry pi and android smartphone. I am trying to control raspburry pi GPIO with self-made application by android studio. The devices are able connect to each other via MQTT, but when I was trying to publish a message (on/off), it doesn't showed up in the raspberry pi terminal. There is no error detected. I have no clue, what I'm missing here. Thank you in advance for any suggestion.
public class MainActivity extends AppCompatActivity {
Switch aswitch;
MqttAndroidClient client;
TextView subText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.2.193:1883",clientId);
//client = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.43.41:1883",clientId);
}
public void Switch(View v){
aswitch = (Switch) findViewById(R.id.simpleSwitch1);
aswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true){
String topic = "rpi/gpio";
String payload = "On";
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes(StandardCharsets.UTF_8);
MqttMessage message = new MqttMessage(encodedPayload);
message.setRetained(true);
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}else{
String topic = "rpi/gpio";
String payload = "Off";
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes(StandardCharsets.UTF_8);
MqttMessage message = new MqttMessage(encodedPayload);
message.setRetained(true);
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
});
}
public void conn(View v){
try {
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Toast.makeText(MainActivity.this,"connected",Toast.LENGTH_LONG).show();
setSubscription();
}
private void setSubscription() {
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Toast.makeText(MainActivity.this,"connection failed",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
}

When i used mqtt client in other activity they show me error

When i used mqtt client in other activity they show me error and when i closed client in OnDestroy and then used client in different activity then it didn't give error but setactioncallback didn't work it give no success and no failure
Mainactivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
login = findViewById(R.id.btn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String clientId = MqttClient.generateClientId();
client =
new MqttAndroidClient(MainActivity.this, "tcp://broker.hivemq.com:1883",
clientId);
try {
MqttConnectOptions options = new MqttConnectOptions();
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Log.d(TAG, "onSuccess");
gotosubscribelist();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.d(TAG, "onFailure");
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
});
}
private void gotosubscribelist()
{
Intent intent = new Intent(this,SubscribelistActivity.class);
intent.putExtra("client", String.valueOf(client));
startActivity(intent);
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
client.unregisterResources();
client.close();
}
subscribe activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subscribelist);
try {
MainActivity.client.connect();
} catch (MqttException e) {
e.printStackTrace();
}
channel = findViewById(R.id.channel);
subscribe = findViewById(R.id.subscribe);
mRec = (RecyclerView) findViewById(R.id.recyclerview);
newlist = new ArrayList<>();
adapter = new ChannelAdapter(this,newlist);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRec.setHasFixedSize(true);
mRec.setLayoutManager(linearLayoutManager);
mRec.setAdapter(adapter);
subscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
subscribe();
}
});
}
private void subscribe()
{
Log.e("hi","1");
final String topic = channel.getText().toString();
int qos = 1;
try {
IMqttToken subToken = MainActivity.client.subscribe(topic, qos);
subToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.e("suc","create");
newlist.add(topic);
}
#Override
public void onFailure(IMqttToken asyncActionToken,
Throwable exception) {
Log.e("e",exception.getMessage());
}
});
adapter.notifyDataSetChanged();
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
MainActivity.client.unregisterResources();
MainActivity.client.close();
}
My problem is if i remove client.unregisterResources and client.close in onDestroy then it show
E/ActivityThread: Activity com.example.mqtt.UI.MainActivity has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection#7ce0751 that was originally bound here
android.app.ServiceConnectionLeaked: Activity com.example.mqtt.UI.MainActivity has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection#7ce0751 that was originally bound here
and when i put client.unregisterResources and client.close in onDestroy then it didn't show error but in the subscribe function it didn't run onsuccess and onfailure, please give some suggestion
channelactivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_channel);
try {
MainActivity.client.connect();
MainActivity.client.isConnected();
} catch (MqttException e) {
e.printStackTrace();
}
message = findViewById(R.id.msg);
publish = findViewById(R.id.publish);
name = getIntent().getExtras().get("currentchannelname").toString();
Rec = (RecyclerView) findViewById(R.id.recyclerview_msg);
newlist = new ArrayList<>();
adapter = new msgAdapter(this,newlist);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
Rec.setHasFixedSize(true);
Rec.setLayoutManager(linearLayoutManager);
Rec.setAdapter(adapter);
getmessage();
publish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
publishmsg();
}
});
}
private void publishmsg()
{
String topic = name;
String payload = message.getText().toString().trim();
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes("UTF-8");
MqttMessage message = new MqttMessage(encodedPayload);
MainActivity.client.publish(topic, message);
} catch (UnsupportedEncodingException | MqttException e) {
e.printStackTrace();
}
}
private void getmessage()
{
MainActivity.client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
newlist.add(message.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
MainActivity.client.unregisterResources();
MainActivity.client.close();
}
Remove
#Override
protected void onDestroy() {
super.onDestroy();
MainActivity.client.unregisterResources();
MainActivity.client.close();
}
from SubscribeActivity

Method not being called from mainactivity on button click

I have created two activities. Activity Main has button and on click on this button i m calling method of another class which is extended to AppCompActivity. The method name is mailconfig as shown below. Confidential Information has deleted from parameters.
public class ButtonActionFrontPage extends AppCompatActivity{
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
}
public void mailconfig(String message) throws EmailException {
String username = "";
String password = "";
String from = "";
String replyto = "";
String mailto = "";
String subject = "";
Email email = new SimpleEmail();
email.setSSLOnConnect(true);
email.isStartTLSEnabled();
email.setHostName("");
email.setSmtpPort(26);
email.setSubject(subject);
email.addReplyTo(replyto);
email.setFrom(from);
email.setAuthenticator(new DefaultAuthenticator(username, password));
email.setMsg(message);
email.addTo(mailto);
email.send();
Toast.makeText(ButtonActionFrontPage.this,"Thanks for submitting ",Toast.LENGTH_SHORT).show();
System.out.println("Sent");
}
}
I a using below code to call above method.
feedbackbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
ButtonActionFrontPage buttonActionFrontPage = new ButtonActionFrontPage();
String message = quickfbet.getText().toString();
buttonActionFrontPage.mailconfig(message);
} catch (EmailException e) {
e.printStackTrace();
}
}
});
What wrong in this code, why not executing.
Java classes are different with respect to Android Activity. As Android Activity has something called life cycle.
If some functionality has to be implemented, you don't even create an Activity. Just a plain Java class is enough.
Activity can be used when there is an user interaction (infact which is not always true, but purely depends on the business logic). Inorder to initiate an Activity, Intent is used. Which will initiate the activity with memory allocation and other related features.
For your case, the initiation of button should be done in onCreate of ButtonActionFrontPage and through click listener as shown below
Button feedbackbtn;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
feedbackbtn=(Button)findViewById(R.id.button_ID);
feedbackbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new PlainJavaClass().mailconfig("msg",ButtonActionFrontPage.class);
}
});
}
For the business logic just use PlainJavaClass with method and context if you have to show any Toast/Dialog/ProgressBar
class PlainJavaClass{
public void mailconfig(String message, Context context) {
Log.v("TAG","mailconfig with message="+message);
//Your logic
Toast.makeText(context,"Thanks for submitting ",Toast.LENGTH_SHORT).show();
}
}
Class would be like this
public class ButtonActionFrontPage {
public void mailconfig(Context context,String message) throws EmailException {
String username = "";
String password = "";
String from = "";
String replyto = "";
String mailto = "";
String subject = "";
Email email = new SimpleEmail();
email.setSSLOnConnect(true);
email.isStartTLSEnabled();
email.setHostName("");
email.setSmtpPort(26);
email.setSubject(subject);
email.addReplyTo(replyto);
email.setFrom(from);
email.setAuthenticator(new DefaultAuthenticator(username, password));
email.setMsg(message);
email.addTo(mailto);
email.send();
Toast.makeText(context,"Thanks for submitting ",Toast.LENGTH_SHORT).show();
System.out.println("Sent");
}
}
And Calling function like this
feedbackbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
ButtonActionFrontPage buttonActionFrontPage = new ButtonActionFrontPage();
String message = quickfbet.getText().toString();
buttonActionFrontPage.mailconfig(getApplicationContext(),message);
} catch (EmailException e) {
e.printStackTrace();
}
}
});
public class ButtonActionFrontPage extends AppCompatActivity{
static ButtonActionFrontPage instance;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
instance = this;
}
public static ButtonActionFrontPage getInstance() {
return instance;
}
#Override
protected void onDestroy() {
super.onDestroy();
instance = null;
}
}
and calling the function:
feedbackbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
ButtonActionFrontPage buttonActionFrontPage = ButtonActionFrontPage.getInstance(); String message = quickfbet.getText().toString();
buttonActionFrontPage.mailconfig(message);
} catch (EmailException e) {
e.printStackTrace();
}
}
});

Stop AsyncTask doInBackground Method in Android

I'm facing an issue with AsyncTask doInBackground method, I don't know how to stop this method from running.
I'm working on an application that has a login screen which retrieves information about the logged user. The problem is when I enter a wrong password or username and then when I re-enter the correct data, my application crashes and I get
"java.lang.IllegalStateException: Cannot execute task: the task has
already been executed"
How can I stop this thread from running? Here is the code:
LoginActivity.java
public class LoginActivity extends Activity implements LoginParser.GetLoginListener{
public LoginParser parser1;
public EditText ETUsername;
public EditText ETPassword;
//private LoginParser lb;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
parser1 = new LoginParser();
ETUsername = (EditText)findViewById(R.id.ET1);
ETPassword = (EditText)findViewById(R.id.ET2);
final Button button = (Button) findViewById(R.id.loginBut);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String UserName = ETUsername.getText().toString();
String Password = ETPassword.getText().toString();
Log.e("LoginAct .. userName: ", UserName);
Log.e("LoginAct .. Password: ", Password);
if (UserName.isEmpty() || Password.isEmpty()) {
new AlertDialog.Builder(LoginActivity.this).setTitle("Warning")
.setMessage("Please Enter your Username and Password")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
else{
parser1.getLoginInfo(UserName, Password);
parser1.setListener(LoginActivity.this);
}
} // end of button on click
} );
}
#Override
public void didReceivedUserInfo(String displayName) {
if(displayName != null) {
new AlertDialog.Builder(LoginActivity.this).setTitle("Welcome").setMessage("Welcome " + displayName)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent (LoginActivity.this, MainActivity.class);
startActivity(in);
}
}).show();
}
else {
new AlertDialog.Builder(LoginActivity.this).setTitle("Warning")
.setMessage("Error in login ID or Password, Please try again later")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
}
LoginParser.java
public class LoginParser extends AsyncTask <Void,Void,String> {
private String requestURL;
public String UserName ;
public String Password ;
public interface GetLoginListener
{
public void didReceivedUserInfo (String displayName);
}
private GetLoginListener listener;
public GetLoginListener getListener() {
return listener;
}
public void setListener(GetLoginListener listener) {
this.listener = listener;
}
public void getLoginInfo(String userName , String password)
{
requestURL = "some link";
this.UserName = userName ;
this.Password = password ;
execute(); // it will call doInBackground in secondary thread
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(requestURL);
HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection();
String jsonString = "LID="+ UserName +"&PWD="+Password+"&Passcode=****";
Log.e("LoginParser","JSONString: " + jsonString);
urlConnection1.setDoOutput(true);
urlConnection1.setRequestMethod("POST");
urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection1.setRequestProperty("charset","utf-8");
PrintWriter out = new PrintWriter(urlConnection1.getOutputStream());
// out.print(this.requestMessage);
out.print(jsonString);
out.close();
int statusCode = urlConnection1.getResponseCode();
Log.d("statusCode", String.valueOf(statusCode));
StringBuilder response = new StringBuilder();
byte[] data = null;
if (statusCode == HttpURLConnection.HTTP_OK)
{
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection1.getInputStream()));
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
data = response.toString().getBytes();
}
else {
data = null;// failed to fetch data
}
String responseString = new String(data);
Log.e("doInBackground", "responseString" + responseString);
JSONObject jsonObject2 = new JSONObject(responseString);
String Status = jsonObject2.getString("Status");
Log.e("Status", Status);
if (Status.equals("s")) {
Log.i("Status:", "Successful");
String displayName = jsonObject2.getString("DisplayName");
return displayName;
}
else {
return null;
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String displayName) {
super.onPostExecute(displayName);
Log.e("onPost: ","onPost");
listener.didReceivedUserInfo(displayName);
}
}
Thank you for your help.
The "can't re-execute task" error can be solved by creating a new instance of the AsyncTask. You can't call execute twice on the same instance, but you can make as many instances as you want.
Stopping the execution won't help that error. The problem isn't that its currently running, the problem is that you need to create a new instance and run that instead.
You can cancel Async task using continuous check of isCancel in your doInBackground method.
protected Object doInBackground(Object... x) {
while (/* condition */) {
// work...
if (isCancelled()) break;
}
return null;
}
Hope this will help you.

Categories

Resources