How do you implement Websocket to your android application - java

So I'm a beginner in developing android application i wanna know how do you implement websocket to my android application so that i can get the data's from our server
I have tried deserialization the data from json to java so that they'll be able to communicate once the connection is established
package com.example.app;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
public class MainActivity extends Activity {
private WebSocketClient mWebSocketClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectWebSocket();
}
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://10.24.204.215:9090");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake handshakedata) {
Log.i("Websocket", "Opened");
mWebSocketClient.send("Hello from" + Build.MANUFACTURER + " " + Build.MODEL );
}
#Override
public void onMessage(String s) {
final String uiview = s;
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = (TextView)findViewById(R.id.uiview);
textView.setText(textView.getText() + "\n" + uiview);
}
});
}
#Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed" + s);
}
#Override
public void onError(Exception e) {
Log.i("Websocket", "Error" + e.getMessage());
}
};
mWebSocketClient.connect();
}
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
public void sendMessage(View view) {
EditText editText = (EditText) findViewById(R.id.edittxt);
String mWebSocketClient = editText.getText().toString();
editText.setText("");
}
}
It wont let me display gather the data's from the WS to display it to my mobile screen.

Related

Connecting to server's websocket on android java

I am struggling to connect to server's websocket on android java.
My main class for websocket on server-side is as below.
#ServerEndpoint("/websocket")
public class WebsocketListener {
#OnOpen
public void handleConnect(Session session) {
System.out.println("Client connect : " + session);
}
#OnMessage
public void handleMessage(Session session, String message) {
System.out.println(session + " : " + message);
String[] tokens = message.split(":::");
if(tokens[0].equals("connect")) {
WebSocketSessionManager.addSession(tokens[1], session);
} else if(tokens[0].equals("alert")) {
WebSocketSessionManager.sendMessage(tokens[1]);
}
}
#OnClose
public void handleDisconnect(Session session) {
System.out.println(session + "과의 연결 종료.");
WebSocketSessionManager.removeSession(session);
}
#OnError
public void handleError(Session session, Throwable throwable) {
throwable.printStackTrace();
WebSocketSessionManager.removeSession(session);
}
}
And below is my android-java code for trying to connect to server's websocket.
package com.example.socketexample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.URI;
public class MainActivity extends AppCompatActivity {
private Button button;
private WebSocketClient webSocketClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
connectToWebSocket();
}
});
}
private void connectToWebSocket() {
Log.i("websocket", "connectToWebSocket() called.");
URI uri;
try {
uri = new URI("ws://10.21.20.24:8080/websocket");
} catch(Exception e){
e.printStackTrace();
return;
}
webSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake handshakedata) {
Log.i("websocket", "connected to server.");
webSocketClient.send("connect:::TESTKEY");
webSocketClient.send("alert:::HI");
}
#Override
public void onMessage(String message) {
Log.i("websocket", message);
}
#Override
public void onClose(int code, String reason, boolean remote) {
Log.i("websocket", "closed.");
}
#Override
public void onError(Exception ex) {
Log.i("websocket" , "error : " + ex.getMessage());
}
};
webSocketClient.connect();
}
}
I saw that websocket uses ws:// protocol, so I set the URI to ws://10.21.20.24, which is the IP address in my wifi.
For server's websocket, I am using the pom.xml dependency below.
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
For android's websocket, I am using the gradle dependency below.
implementation 'org.java-websocket:Java-WebSocket:1.3.0'
Thank you so much in advance. :(
For everyone who is suffering from the same problem that I encountered...
I solved the problem by adding new Draft_17() as the second parameter of new WebSocketClient(). The code is summarized as below.
private void connectToWebSocket() {
Log.i("websocket", "connectToWebSocket() called.");
URI uri;
try {
uri = new URI("ws://10.21.20.24:8080/websocket");
} catch(Exception e){
e.printStackTrace();
return;
}
webSocketClient = new WebSocketClient(uri, new Draft_17()) {
// ...
}
}
However, this issues is from year 2017, and I think I have to find an alternative for Draft_17.
https://github.com/TooTallNate/Java-WebSocket/issues/478
Good luck!

I want to add country code from dropdown

How can I do this, I searched on StackOverflow, but solution is for iphone, not android.
Here is my chat app: https://play.google.com/store/apps/details?id=com.jimmytrivedi.lapitchat
package com.jimmytrivedi.lapitchat;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class PhoneAuthActivity extends AppCompatActivity {
private LinearLayout DialLayout, LockLayout;
private EditText PhoneNumber, code;
private ProgressBar PhoneProgress, CodeProgress;
private Button sendVerification;
private Toolbar PhoneToolbar;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private String number;
private FirebaseAnalytics mFirebaseAnalytics;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private FirebaseAuth mAuth;
private TextView ErrorView;
private int Verify = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_auth);
DialLayout = findViewById(R.id.DialLayout);
LockLayout = findViewById(R.id.LockLayout);
PhoneNumber = findViewById(R.id.PhoneNumber);
code = findViewById(R.id.code);
PhoneProgress = findViewById(R.id.PhoneProgress);
CodeProgress = findViewById(R.id.CodeProgress);
sendVerification = findViewById(R.id.sendVerification);
PhoneToolbar = findViewById(R.id.PhoneToolbar);
ErrorView = findViewById(R.id.ErrorView);
PhoneProgress.setVisibility(View.INVISIBLE);
CodeProgress.setVisibility(View.INVISIBLE);
sendVerification.setEnabled(false);
LockLayout.setVisibility(View.INVISIBLE);
setSupportActionBar(PhoneToolbar);
getSupportActionBar().setTitle("Welcome to Phone Verification");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
mAuth = FirebaseAuth.getInstance();
PhoneNumber.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String text = charSequence.toString();
if (!text.isEmpty()) {
sendVerification.setEnabled(true);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
sendVerification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Verify == 0) {
if (!PhoneNumber.getText().toString().isEmpty()) {
number = PhoneNumber.getText().toString();
PhoneNumber.setEnabled(false);
sendVerification.setEnabled(false);
PhoneProgress.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
PhoneAuthActivity.this,
mCallbacks
);
}
} else {
String VerificationCode = code.getText().toString();
sendVerification.setEnabled(false);
CodeProgress.setVisibility(View.VISIBLE);
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(
mVerificationId,VerificationCode);
signInWithPhoneAuthCredential(credential);
}
}
});
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
PhoneProgress.setVisibility(View.INVISIBLE);
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
ErrorView.setText("There was some error in verification");
ErrorView.setVisibility(View.VISIBLE);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Log.d("wihddiewd", "FirebaseAuthInvalidCredentialsException: " + e);
} else if (e instanceof FirebaseTooManyRequestsException) {
Log.d("wihddiewd", "FirebaseTooManyRequestsException: " + e);
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
Log.d("wihddiewd", "onCodeSent:" + verificationId);
mVerificationId = verificationId;
mResendToken = token;
Verify=1;
PhoneProgress.setVisibility(View.INVISIBLE);
LockLayout.setVisibility(View.VISIBLE);
sendVerification.setEnabled(true);
sendVerification.setText("Verify code");
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(PhoneAuthActivity.this, MainActivity.class));
finish();
} else {
ErrorView.setText("There was some error in logging in");
ErrorView.setVisibility(View.VISIBLE);
Log.w("wihddiewd", "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
}
}
}
});
}
}
I don't know what type of code is necessary and where should I add?
Try this lib:
CountryCodePicker
dependencies {
implementation 'com.hbb20:ccp:2.2.2'
}
In XML
<com.hbb20.CountryCodePicker
android:id="#+id/country_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center|center_vertical"
android:includeFontPadding="false"
android:textColor="#color/text_black"
app:ccp_showNameCode="false"
app:ccp_textSize="#dimen/small_text_size" />
In Activity
CountryCodePicker country_picker = findViewById(R.id.country_picker);
String country_code = country_picker.getSelectedCountryCode();

Retrofit null response

Hello me and my group from university decide to create an app, that a client of a gym can see his/her exercise list and we are using retrofit to get a json. Early this code was working very well, but suddenly stopped to work, and now I'm getting null response and status 200 from callback.
image with the log.d 200 and null response
Sorry for my english.
My JSON
{
"0":{
"id":"1",
"nome":"Fernanda Kondrat",
"peso":"67.4",
"altura":"172",
"imc":"22.8",
"login":"fefe",
"senha":"1234"},
"lista_exercicios":[
{
"id":"1",
"id_aluno":"1",
"nome":"supino reto",
"num_serie":"3",
"num_repeticao":"10"
},
{
"id":"2",
"id_aluno":"1",
"nome":"agachamento hack",
"num_serie":"3",
"num_repeticao":"10"
},
{
"id":"3",
"id_aluno":"1",
"nome":"barra fixa",
"num_serie":"3",
"num_repeticao":"10"
},
{
"id":"4",
"id_aluno":"1",
"nome":"leg press",
"num_serie":"4",
"num_repeticao":"10"
}
]
}
And now my MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.u9.fabapp.virtualgym.APIClient;
import com.u9.fabapp.virtualgym.RespostaLogin;
import com.u9.fabapp.virtualgym.Resposta;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class MainActivity extends AppCompatActivity {
Button btn_login;
EditText edt_login;
EditText edt_senha;
private Callback<RespostaLogin> respostaCallback;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_login = findViewById(R.id.btn_login);
edt_login = findViewById(R.id.edt_Login);
edt_senha= findViewById(R.id.edt_Senha);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Log.d(TAG, "onClick: ");
//Intent i = new Intent(MainActivity.this, ProfileActivity.class);
//startActivity(i);
String login = edt_login.getText().toString();
String senha = edt_senha.getText().toString();
if(TextUtils.isEmpty(login)|| TextUtils.isEmpty(senha)) {
Toast.makeText(MainActivity.this, "Campos vazios", Toast.LENGTH_SHORT).show();
} else {
configurarCallback();
//new APIClient().getRestService().setUsuarioLoginDTO(login, senha, respostaCallback);
new APIClient().getRestService().setUsuarioLoginDTO(login, senha, respostaCallback);
}
}
});
}
private void configurarCallback() {
respostaCallback = new Callback<RespostaLogin>() {
#Override
public void success(RespostaLogin resposta, Response response) {
Log.d(TAG, "Funcionou: "+ response.getStatus());
Log.d(TAG, "Funcionou: " + resposta.getRETORNO());
/*if (resposta.getRETORNO().equals("SUCESSO")){
Intent intent1 = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intent1);
}else{
Toast.makeText(MainActivity.this, resposta.getRETORNO() +" ,Verifique usuário e senha" , Toast.LENGTH_SHORT).show();
}*/
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(MainActivity.this, "Deu Ruim: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
};
}
}
APIClient.java
import com.u9.fabapp.virtualgym.Resposta;
import com.u9.fabapp.virtualgym.RespostaLogin;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.http.GET;
import retrofit.http.Query;
import retrofit.http.Path;
public class APIClient {
private static RestAdapter REST_ADAPTER;
public APIClient(){
createAdapterIfNeeded();
}
private static void createAdapterIfNeeded() {
if(REST_ADAPTER == null){
REST_ADAPTER = new RestAdapter
.Builder()
.setEndpoint("http://golfetto.16mb.com/virtual-fit/home/")
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(new OkClient())
.build();
}
}
public RestServices getRestService(){
return REST_ADAPTER.create(RestServices.class);
}
public interface RestServices{
#GET("/getExercicios.php")
void setUsuarioLoginDTO(
#Query("LOGIN") String login,
#Query("SENHA") String senha,
Callback<RespostaLogin> callbackResposta
);
}
}
In interface "RestService", change at:
#GET("/getExercicios.php")
Modify it as:
#GET("getExercicios.php")
Remove "/" because it is being already being appended.
Thanks and happy coding
The full URL of your service will be
BASE_URL (defined at the time of createing retrofit object) + END_POINT_URL (defined in the interface)
You have added "http://golfetto.16mb.com/virtual-fit/home/" as base URL and in the interface you have define the endpoint as "/getExercicios.php" so the full URL will be
"http://golfetto.16mb.com/virtual-fit/home//getExercicios.php"
which is not a valid URL. So you have to remove '/' from the interface
The interface will be
public interface RestServices{
#GET("getExercicios.php")
void setUsuarioLoginDTO(
#Query("LOGIN") String login,
#Query("SENHA") String senha,
Callback<RespostaLogin> callbackResposta
);
}

I cant login or register to my app

I have a problem with my app. When I want to login or register the ProgressDialog will be show and never cancel. During the app is running it must cancel and "ok" Message must be shown.
Here is my code:
Main
package com.example.server;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class Main extends Activity {
private ImageView login,register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
login=(ImageView) findViewById(R.id.main_login);
register=(ImageView) findViewById(R.id.main_register);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent lo=new Intent(Main.this,login.class);
startActivity(lo);
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent lo=new Intent(Main.this,register.class);
startActivity(lo);
}
});
}
}
login
package com.example.server;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class login extends Activity{
private ImageView login,exit;
private EditText usertext,passtext;
public static String res="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
login=(ImageView) findViewById(R.id.login_login);
exit=(ImageView) findViewById(R.id.login_exit);
usertext=(EditText) findViewById(R.id.usertext);
passtext=(EditText) findViewById(R.id.passtext);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
login(usertext.getText().toString(),passtext.getText().toString());
}
});
exit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
finish();
}
});
}
public void login(String user,String pass){
new loginserver("http://ujo.ir/login,php",user,pass).execute();
final ProgressDialog pd=new ProgressDialog(login.this);
pd.setMessage("Loading...");
pd.show();
final Timer tm=new Timer();
tm.schedule(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if(!res.equals("")){
pd.cancel();
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
res="";
tm.cancel();
}
}
});
}
}, 1, 1000);
}
}
register
package com.example.server;
import java.io.ObjectOutputStream.PutField;
import java.util.Timer;
import java.util.TimerTask;
import com.example.server.R.layout;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class register extends Activity{
public static String res="";
private ImageView register,exit;
private EditText name,family,user,pass,email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
name=(EditText) findViewById(R.id.re_name);
family=(EditText) findViewById(R.id.re_family);
user=(EditText) findViewById(R.id.re_user);
pass=(EditText) findViewById(R.id.re_pass);
email=(EditText) findViewById(R.id.re_email);
register=(ImageView) findViewById(R.id.re_register);
exit=(ImageView) findViewById(R.id.re_exit);
exit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
finish();
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
register1(name.getText().toString(),family.getText().toString(),user.getText().toString(),pass.getText().toString(),email.getText().toString());
}
});
}
public void register1(String name,String family,String user,String pass,String email){
new registerserver("http://ujo.ir/register.php", name, family, user, pass, email).execute();
final ProgressDialog pd=new ProgressDialog(register.this);
pd.setMessage("Loading...");
pd.show();
final Timer tm=new Timer();
tm.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if(!res.equals("")){
pd.cancel();
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
res="";
tm.cancel();
}
}
});
}
}, 1, 1000);
}
}
registerserver
package com.example.server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.os.AsyncTask;
public class registerserver extends AsyncTask{
private String Link="";
private String Name="";
private String Family="";
private String User="";
private String Pass="";
private String Email="";
public registerserver(String link,String name,String family,String user,String pass,String email){
Link=link;
Name=name;
Family=family;
User=user;
Pass=pass;
Email=email;
}
#Override
protected String doInBackground(Object... arg0) {
try{
String data=URLEncoder.encode("name","UTF8")+"="+URLEncoder.encode(Name,"UTF8");
data+="&"+URLEncoder.encode("family","UTF8")+"="+URLEncoder.encode(Family,"UTF8");
data+="&"+URLEncoder.encode("username","UTF8")+"="+URLEncoder.encode(User,"UTF8");
data+="&"+URLEncoder.encode("password","UTF8")+"="+URLEncoder.encode(Pass,"UTF8");
data+="&"+URLEncoder.encode("email","UTF8")+"="+URLEncoder.encode(Email,"UTF8");
data+="&"+URLEncoder.encode("status","UTF8")+"="+URLEncoder.encode("a","UTF8");
URL mylink=new URL(Link);
URLConnection connect=mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr=new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine()) !=null){
sb.append(line);
}
register.res=sb.toString();
}catch(Exception e){
}
return "";
}
}
There are two error.
In loginserver.java , the variable assignment is reversed in constructor
Your code is
public loginserver(String link,String user,String pass){
link=Link;
user=User;
pass=Pass;
}
It should be
public loginserver(String link, String user, String pass) {
Link = link;
User = user;
Pass = pass;
}
It is a typo in your login.java
In your code
new loginserver("http://ujo.ir/login,php",user,pass).execute();
Its login.php not login,php
I changed these two and logged in using the user id and password .
I got the toast message "ok"
If you are making a http connection , it would be good to use
HttpURLConnection instead of URLconnection as it provides extra API to deal with http connections. I have attached the code for loginserver.java
protected String doInBackground(Object... arg0) {
try {
String data=URLEncoder.encode("username","UTF8")+"="+URLEncoder.encode(User,"UTF8");
data+="&"+URLEncoder.encode("password","UTF8")+"="+URLEncoder.encode(Pass,"UTF8");
Log.i("loginserver","loginserver is called"+data);//helped to find the error 1
URL mylink=new URL(Link);
HttpURLConnection connect=(HttpURLConnection) mylink.openConnection();
connect.setDoOutput(true);
connect.setChunkedStreamingMode(0);
OutputStreamWriter wr=new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
Log.i("loginserver","after flush"+connect.getResponseCode());//helped to find the error 2
BufferedReader reader=new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine()) != null){
Log.i("loginserver","we enter while");
sb.append(line);
}
login.res=sb.toString();
Log.i("loginserver","value is" + login.res);
} catch (Exception e) {
}
return "";
}

Web service call from android using DataDroid library not returning data to activity

Below I've listed my activity code, call out to the web service, and the json parsing class I created to parse the web service results. I'm trying to pass a user object back to the activity to determine what they can/can't do, however, I'm not getting past the "after execute" log statement. onRequestFinished never gets called which is where I would have expected it to end up. Any help would be greatly appreciated as there doesn't seem to be much activity with DataDroid...
LoginActivity.java
package com.motosho.ui;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.requestmanager.RequestManager.RequestListener;
import com.motosho.R;
import com.motosho.data.model.User;
import com.motosho.data.requestmanager.RequestFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Intent;
public final class LoginActivity extends DataDroidActivity implements RequestListener,
OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bindViews();
}
protected void onResume() {
super.onResume();
for(int i=0; i < mRequestList.size(); i++) {
Request request = mRequestList.get(i);
if(mRequestManager.isRequestInProgress(request)) {
mRequestManager.addRequestListener(this, request);
setProgressBarIndeterminateVisibility(true);
} else {
mRequestManager.callListenerWithCachedData(this, request);
i--;
mRequestList.remove(request);
}
}
}
protected void onPause() {
super.onPause();
if(!mRequestList.isEmpty()) {
mRequestManager.removeRequestListener(this);
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
private void bindViews() {
((Button) findViewById(R.id.sign_in_button)).setOnClickListener(this);
}
private void callLoginWS(String username, String pin, String eventId) {
Log.i("LOGIN", "in callLoginWS - username=" + username + ", pin=" + pin + ", eventid=" + eventId);
setProgressBarIndeterminateVisibility(true);
Request request = RequestFactory.getLoginRequest(username, pin, eventId);
mRequestManager.execute(request, this);
Log.i("LOGIN", "after execute");
mRequestList.add(request);
}
public void onClick(View view) {
switch(view.getId()) {
case R.id.sign_in_button:
EditText emailText = (EditText) findViewById(R.id.email);
EditText pinText = (EditText) findViewById(R.id.pin);
Log.i("LOGIN","set email and pin text");
callLoginWS(emailText.getText().toString(), pinText.getText().toString(),"9");
break;
}
}
#Override
public void onRequestFinished(Request request, Bundle resultData) {
Log.i("LOGIN", "inside onRequestFinished");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
Log.i("LOGIN", "request found");
mRequestList.remove(request);
Toast toast = Toast.makeText(this, "request finished", Toast.LENGTH_SHORT);
toast.show();
User user = resultData.getParcelable("user");
if(user != null) {
startActivity(new Intent(this, MainActivity.class).putExtras(resultData));
}
}
}
#Override
public void onRequestConnectionError(Request request, int statusCode) {
Log.i("LOGIN", "onRequestConnectionError");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
//show error
Toast toast = Toast.makeText(this, "connection error", Toast.LENGTH_SHORT);
toast.show();
mRequestList.remove(request);
}
}
#Override
public void onRequestDataError(Request request) {
Log.i("LOGIN", "onRequestDataError");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
mRequestList.remove(request);
//show error
Toast toast = Toast.makeText(this, "data error", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onRequestCustomError(Request request, Bundle resultData) {
// Never called
}
public void connectionErrorDialogRetry(Request request) {
Log.i("LOGIN", "connectionErrorDialogRetry");
String username = request.getString("username");
String pin = request.getString("pin");
String eventId = request.getString("eventid");
callLoginWS(username,pin,eventId);
}
}
LoginOperation.java
package com.motosho.data.operation;
import java.util.HashMap;
import android.content.Context;
import android.os.Bundle;
import com.foxykeep.datadroid.exception.ConnectionException;
import com.foxykeep.datadroid.exception.CustomRequestException;
import com.foxykeep.datadroid.exception.DataException;
import com.foxykeep.datadroid.network.NetworkConnection;
import com.foxykeep.datadroid.network.NetworkConnection.ConnectionResult;
import com.foxykeep.datadroid.network.NetworkConnection.Method;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.service.RequestService.Operation;
import com.motosho.config.WSConfig;
import com.motosho.data.factory.LoginJsonFactory;
public final class LoginOperation implements Operation {
#Override
public Bundle execute(Context context, Request request)
throws ConnectionException, DataException, CustomRequestException {
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", request.getString("username"));
params.put("pin", request.getString("pin"));
params.put("eventid", request.getString("eventid"));
NetworkConnection networkConnection = new NetworkConnection(context, WSConfig.WS_LOGIN_URL);
networkConnection.setMethod(Method.POST);
networkConnection.setParameters(params);
ConnectionResult result = networkConnection.execute();
return LoginJsonFactory.parseResult(result.body);
}
}
LoginJsonFactory.java
package com.motosho.data.factory;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.util.Log;
import com.foxykeep.datadroid.exception.DataException;
import com.motosho.config.JSONTag;
import com.motosho.data.model.User;
public final class LoginJsonFactory {
private static final String TAG = LoginJsonFactory.class.getName();
private LoginJsonFactory() { }
#SuppressWarnings("null")
public static Bundle parseResult(String wsResponse) throws DataException {
User user = new User();
try {
JSONObject parser = new JSONObject(wsResponse);
JSONObject jsonRoot = parser.getJSONObject(JSONTag.USER_ELEM);
user.firstName = jsonRoot.getString(JSONTag.USER_ELEM_FIRST_NAME);
user.lastName = jsonRoot.getString(JSONTag.USER_ELEM_LAST_NAME);
user.phoneNumber = jsonRoot.getString(JSONTag.USER_ELEM_PHONE_NUMBER);
user.role = jsonRoot.getString(JSONTag.USER_ELEM_ROLE);
JSONArray jsonPositionsArray = jsonRoot.getJSONArray(JSONTag.USER_ELEM_LIST_POSITIONS);
int size = jsonPositionsArray.length();
List<String> tempPositionsArray = null;
for (int i=0; i < size; i++) {
tempPositionsArray.add(jsonPositionsArray.getString(i));
}
user.positions = tempPositionsArray;
JSONArray jsonCapabilitiesArray = jsonRoot.getJSONArray(JSONTag.USER_ELEM_LIST_CAPABILITIES);
size = jsonCapabilitiesArray.length();
List<String> tempCapabilitiesArray = null;
for(int i=0; i < size; i++) {
tempCapabilitiesArray.add(jsonCapabilitiesArray.getString(i));
}
user.capabilities = tempCapabilitiesArray;
} catch (JSONException e) {
Log.e(TAG, "JSONException", e);
throw new DataException(e);
}
Bundle bundle = new Bundle();
bundle.putParcelable("user", user);
return bundle;
}
}

Categories

Resources