Android Socket to Server, Server reports "Connection Reset" error - java

am developing an Android Application for Email System, and the application needs to connect server (written by my partner).
My cellphone use wifi generated by my PC, when I try to login,the server just reports the "Connection reset"error for a few times in 10 seconds.
Client Login IP:59.71.68.237 Server host:Iris Time:2015.06.13 at 09:04:36
java.net.SocketException:Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputSteamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at com.mailService.emsp.tempEMSP.run(tempEMSP.java:42)
at java.lang.Thread.run(Thread.java:745)
I debug in Android,and I find out that the code stops after executing
client = new Socket(ServerInfo.sockethost, ServerInfo.socketport);
and the server reports error just after that.
Here is the client code.
public class Login extends Activity {
private Intent intent = null;
private EditText account = null; //Account
private EditText passwpord = null; //password
private Button login = null; // login
private TextView register = null; // register
private String useraccount = null;
private String userpassword = null;
private Dialog m_Dialog = null; // dialog
private Socket client; //client socket
private BufferedReader reader;
private PrintWriter writer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
intent = this.getIntent();
account = (EditText) this.findViewById(R.id.login_account);
passwpord = (EditText) this.findViewById(R.id.login_password);
login = (Button) this.findViewById(R.id.login_button);
register = (TextView) this.findViewById(R.id.login_register);
register.setClickable(true);
//login button event
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
useraccount = account.getText().toString();
userpassword = account.getText().toString();
//judge whether the account is null
if (Regex.isEmpty(useraccount)) {
Toast.makeText(getApplicationContext(), "Please fill in account!",
Toast.LENGTH_SHORT).show();
}
// judge whether the account meets email form
else if (Regex.isEmail(useraccount)) {
Toast.makeText(getApplicationContext(), "account form is wrong!",
Toast.LENGTH_SHORT).show();
}
// judge whether password is null
else if (Regex.isEmpty(userpassword)) {
Toast.makeText(getApplicationContext(), "Please fill in the password!",
Toast.LENGTH_SHORT).show();
} else {
System.out.println("Client:Connecting");
m_Dialog = ProgressDialog.show(Login.this, "Hint", "Login...",true);
// create a new thread
new Thread(new Runnable() {
int flag = 0;
int mark = 0;
// based on the custom protocol
#Override
public void run() {
try {
// create a new socket
System.out.println("new Socket('', 6666);");
//This is where the code stops
client = new Socket(ServerInfo.sockethost, ServerInfo.socketport);
System.out.println("Socket 'client' created.");
String command = null;
System.out.println("new reader.");
// IO reader and writer
reader = new BufferedReader(
new InputStreamReader(client.getInputStream()));
System.out.println("new writer.");
writer = new PrintWriter(client.getOutputStream(), true);
// Client:login
writer.println("login");
while ((command = reader.readLine()) != null) {
StringTokenizer stk = new StringTokenizer(command);
String cmd = stk.nextToken();
System.out.println("cmd:" + cmd);
if (cmd.equals("user")) {
writer.println(useraccount);
System.out
.println("writer.println('useraccount');");
} else if (cmd.equals("pass")) {
writer.println(userpassword);
System.out
.println("writer.println('userpassword');");
} else if (cmd.equals("inexist")) {
writer.println(useraccount);
System.out
.println("inexist, writer.println('username');");
} else if (cmd.equals("error")) {
writer.println(useraccount);
System.out
.println("error, writer.println('username');");
} else if (cmd.equals("loginok")) {
System.out.println("case 'loginok'");
mark = 1;
System.out.println("========mark = "
+ mark);
break;
}
}
System.out.println("Login succeed!,flag=0");
} catch (Exception e) {
flag = 1; // Login fail
e.printStackTrace();
} finally {
try {
if (client != null)
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
m_Handler.post(new Runnable() {
#Override
public void run() {
if (flag == 0) {
ServerInfo.username = useraccount;
ServerInfo.password = userpassword;
intent.setClass(Login.this,
MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("username",
useraccount);
bundle.putString("password",
userpassword);
intent.putExtras(bundle);
startActivity(intent);
Login.this.finish();
System.out
.println("Client: Login succeed!");
Toast.makeText(getApplicationContext(),
"Login succeed!!", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(),
"Login fail!", Toast.LENGTH_SHORT)
.show();
}
}
});
m_Dialog.dismiss();
}
}).start();
}
}
});
}
}
When I execute client code separately from the application, it just works fine!
What is the problem ? Do you have any suggestions ?

Related

How can I send a String through socket from client then get the return from the server?

I am trying to make a simple java android app
I want to send an order from my computer (client) to my android app (server) the the mobile (server) must send the return back to the client (computer)
Client (computer)
public class Main {
public static void main(String[] args) {
Scanner sx = new Scanner(System.in);
String ln = sx.next();
try {
Socket s = new Socket("192.168.2.2", 4040);
s.setSoTimeout(4000);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(ln);
dos.flush();
s.close();
System.out.println("Done....");
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
Server (android app)
public class MainActivity extends Activity {
EditText portfield, ipfield;
LinearLayout player;
SharedPreferences sp;
SharedPreferences.Editor ed;
String myip, myport;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
player = (LinearLayout) findViewById(R.id.player);
portfield = (EditText) findViewById(R.id.portfield);
ipfield = (EditText) findViewById(R.id.ipfield);
sp = getSharedPreferences("okayawalas2423", MODE_PRIVATE);
ed = sp.edit();
myport = sp.getString("myport", null);
myip = sp.getString("myip", null);
runit();
}
public void runit() {
if (myport != null && myip != null) {
final String myport;
final String myip;
startspy();
}
}
public void startspy() {
player.removeAllViews();
Thread th = new Thread(new Runnable() {
public void run() {
eim();
}
});
th.start();
}
public void eim() {
try {
ServerSocket server = new ServerSocket(Integer.parseInt(myport));
say("Server Connected Successfully .... ");
while (true) {
Socket skt = server.accept();
say("The Server Request Has Been Accepted .... ");
DataInputStream dis = new DataInputStream(skt.getInputStream());
String purein = dis.readUTF();
dsay("Data Has Been Sent Right Now To /// and it contains : \n [[[ " + dis.readUTF() + " ]]]");
DataOutputStream dos = new DataOutputStream(skt.getOutputStream());
String outword = doit(purein);
dos.writeUTF(outword);
dos.flush();
dis.close();
dos.close();
skt.close();
}
} catch (Exception e) {
TextView tz = new TextView(this);
tz.setText(e.toString());
player.setGravity(Gravity.CENTER);
player.addView(tz);
}
}
public void stt(View v) {
if (portfield.getText().toString().equals("") || ipfield.getText().toString().equals("")) {
Toast.makeText(this, "Insert All Data !!", Toast.LENGTH_LONG).show();
} else {
ed.putString("myport", portfield.getText().toString());
ed.putString("myip", ipfield.getText().toString());
ed.commit();
startspy();
}
}
public String doit(String p) {
String funRes = "none";
funRes = p;
return funRes;
}
public void say(String s) {
TextView tz = new TextView(this);
tz.setText(s);
player.setGravity(Gravity.CENTER);
player.addView(tz);
}
public void dsay(String s) {
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
}
I type the message on the computer (client) when I press ENTER, I get the "Done..." but the android app gets down!!

Android 23 (Marshmallow) and Higher permission Having a heck of a time

First, Thank you very much for looking at this!
I've been handed an app someone wrote before Marshmallow. I've fixed the Theme and SSL issues that came with Nougat but I'm having a heck of a time with Write to External Storage Permission or something associated. Debug is lacking or I'm not using it properly. This app creates a file onto the device and adds the ssl cert and login info in a folder called My Documents.
When I open the app it say network timeout right away. That message is from LoginActivity.java . I click ok then I get the Android pop up asking to allow permissions. I allow it. After that I put in the username and password and click login. It instantly gives the network timeout message from LoginActivity.java. LoginActivity.java is the Main Activity. If I click ok it's back to the login screen. All permissions are in the Android Manifest as well.
Maybe it's not from permissions but it works fine in version 22. I've worked on this 12 hours today and thought if you guys could help that'd be great. I'm a network engineer dabbling in Java so please excuse my question if it's "ugly".
I tried to find a line by line debug like I've done with phonegap but wasn't successful.
My Apps Main Activity LoginActivity.java and associated activity is LoginScreen.java and shown below.
LoginActivity.java
public class LoginActivity extends Activity {
private String userName = "";
private static final int PERMS_REQUEST_CODE = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blackactivity);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
new SSLHandler().execute();
if(Variables.testing)
{
}
if (hasPermissions()){
// our app has permissions.
try {
attemptLogin();
} catch (Exception e) {
GUI.oneOptionDialog(this, e.toString(), "OK", false);
e.printStackTrace();
}
}
else {
//our app doesn't have permissions, So i m requesting permissions.
requestPerms();
}
}
//Begin Permission Methods
#SuppressLint("WrongConstant")
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
try {
attemptLogin();
} catch (Exception e) {
GUI.oneOptionDialog(this, e.toString(), "OK", false);
e.printStackTrace();
}
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
//End Permission Methods
private void attemptLogin() throws IOException {
String filepath = Variables.fileFolder + "/login.txt";
File tempFile = new File(filepath);
if (!tempFile.exists()) {
startActivity(new Intent(LoginActivity.this, LoginScreen.class));
finish();
}
String username = "";
String passwordHash = "";
String salt = "";
boolean fileExists = false;
BufferedReader reader = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(filepath));
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream);
reader = new BufferedReader(inputStreamReader);
username = reader.readLine();
passwordHash = reader.readLine();
salt = reader.readLine();
reader.close();
userName = username;
fileInputStream.close();
} catch (Exception e) {
startActivity(new Intent(LoginActivity.this, LoginScreen.class));
finish();
}
fileExists = true;
if (fileExists) {
try {
LoginTask login = new LoginTask();
login.execute(username, passwordHash, salt);
} catch (Exception e) {
}
}
}
private class LoginTask extends AsyncTask<String, Void, Boolean> {
Boolean success = false;
Boolean timedOut = false;
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Boolean result) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
}
if (timedOut) {
AlertDialog.Builder builder = new AlertDialog.Builder(
LoginActivity.this);
builder.setMessage("Network Timed Out").setTitle("Notice");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
startActivity(new Intent(LoginActivity.this,
LoginScreen.class));
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
if (result) {
Variables.storeTechName(userName, LoginActivity.this);
Variables.assignTechName();
startActivity(new Intent(LoginActivity.this,
MainActivity.class));
finish();
} else {
startActivity(new Intent(LoginActivity.this,
LoginScreen.class));
finish();
}
}
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(LoginActivity.this,
"Loading...", "Logging you in...");
mProgressDialog.getWindow().setGravity(Gravity.BOTTOM);
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL json = new URL(Variables.urlPrefix + "/Login.svc/input?a="
+ params[0] + "&b=" + params[1] + "&c=" + params[2]);
HttpsURLConnection jc = (HttpsURLConnection) json
.openConnection();
jc.setConnectTimeout(Variables.timeoutTimeLimit);
jc.setSSLSocketFactory(Variables.context.getSocketFactory());
InputStreamReader input = new InputStreamReader(
jc.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
success = jsonResponse.getBoolean("LoginMethodResult");
jc.disconnect();
reader.close();
} catch (Exception e) {
System.out.println(e.toString());
timedOut = true;
}
return success;
}
}
#Override
protected void onPause() {
super.onPause();
}
}
LoginScreen.java
public class LoginScreen extends Activity {
private String userName;
private static final int PERMS_REQUEST_CODE = 123;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginscreen);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (!SSLHandler.loaded) {
new SSLHandler().execute();
}
// Creates login and name files and attempts to log in
Button createButton = (Button) findViewById(R.id.createbutton);
createButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((EditText) findViewById(R.id.usernamefield)).getText()
.toString().isEmpty()
|| ((EditText) findViewById(R.id.passwordfield))
.getText().toString().isEmpty()) {
GUI.oneOptionDialog(LoginScreen.this,
"Missing field entries", "OK", false);
} else {
createLoginFile();
((EditText) findViewById(R.id.usernamefield)).setText("");
((EditText) findViewById(R.id.passwordfield)).setText("");
attemptLogin();
}
}
});
}
#SuppressLint("WrongConstant")
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
createFiles();
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
private void createFiles() {
}
private void attemptLogin() {
String username = "";
String passwordHash = "";
String salt = "";
boolean fileExists = false;
try {
String filepath = Variables.fileFolder + "/login.txt";
FileInputStream fileInputStream = new FileInputStream(new File(
filepath));
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
username = reader.readLine();
passwordHash = reader.readLine();
salt = reader.readLine();
reader.close();
userName = username;
fileInputStream.close();
fileExists = true;
}
catch (Exception e) {
GUI.oneOptionDialog(LoginScreen.this,
"Login file does not exist. Please enter login info.",
"OK", false);
}
if (fileExists) {
try {
LoginTask login = new LoginTask();
login.execute(username, passwordHash, salt);
} catch (Exception e) {
}
}
}
private class LoginTask extends AsyncTask<String, Void, Boolean> {
Boolean timedOut = false;
Boolean success = false;
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Boolean result) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
}
if (timedOut) {
GUI.oneOptionDialog(LoginScreen.this, "Network Timed Out",
"OK", false);
} else {
if (result) {
Variables.storeTechName(userName, LoginScreen.this);
Variables.assignTechName();
startActivity(new Intent(LoginScreen.this,
MainActivity.class));
finish();
} else {
GUI.oneOptionDialog(LoginScreen.this,
"Login Failed. Please try again.", "OK", false);
}
}
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(LoginScreen.this,
"Loading...", "Logging you in...");
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL json = new URL(Variables.urlPrefix + "/Login.svc/input?a="
+ params[0] + "&b=" + params[1] + "&c=" + params[2]);
HttpsURLConnection jc = (HttpsURLConnection) json
.openConnection();
jc.setConnectTimeout(Variables.timeoutTimeLimit);
jc.setSSLSocketFactory(Variables.context.getSocketFactory());
jc.setConnectTimeout(Variables.timeoutTimeLimit);
InputStreamReader input = new InputStreamReader(
jc.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
success = jsonResponse.getBoolean("LoginMethodResult");
jc.disconnect();
reader.close();
} catch (Exception e) {
timedOut = true;
}
return success;
}
}
private void createLoginFile() {
try {
File dir = new File(Variables.fileFolder);
if (!dir.isDirectory()) {
dir.mkdirs();
}
String filepath = Variables.fileFolder + "/Login.txt";
String username = ((EditText) findViewById(R.id.usernamefield))
.getText().toString();
String password = ((EditText) findViewById(R.id.passwordfield))
.getText().toString();
String salt = new RandomString(20).nextString();
String passwordHash = Variables.sha256(password + salt);
PrintWriter writer = new PrintWriter(filepath, "UTF-8");
writer.println(username);
writer.println(passwordHash);
writer.println(salt);
writer.close();
} catch (Exception e) {
GUI.oneOptionDialog(LoginScreen.this, e.toString(), "OK", false);
}
}
#Override
protected void onPause() {
super.onPause();
}
}

Android studio offline login registration

when i am doing offline login my app is crashing...and showing the error
Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
In Online it is working fine no issues but in offline it is crashing not at all giving where the issue is please help me in this
public class MainActivity extends AppCompatActivity {
**// Initializing variables**
EditText login;
EditText password;
String statusRes;
String id;
String projectName;
String loginValue;
String stockPoint;
JSONObject myRespObject = null;
public static final String Passkey = "passKey";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("LOGIN");
setContentView(R.layout.login);
login = (EditText) findViewById(R.id.loginname);
password = (EditText) findViewById(R.id.Password);
final Button saveme = (Button) findViewById(R.id.save);
**SharedPreferences sharedpreferences = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
saveme.setOnClickListener(new Button.OnClickListener() {
public URL url;
public void onClick(android.view.View v) {
if (!CheckNetwork.isInternetAvailable(MainActivity.this){
if (!validate()) {
onLoginFailed();
return;
}
SharedPreferences prefs = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
String loginValue = prefs.getString(AppConstants.LOGIN_VALUE, "");
String Passkey = prefs.getString(AppConstants.PASS_KEY, "");
String Internet = prefs.getString("Internet", "false");
String projectName = prefs.getString(AppConstants.PROJECT_NAME, "");
String stockPoint = prefs.getString(String.valueOf(AppConstants.STOCK_POINT),"");
String id = prefs.getString(AppConstants.ID, "");
Intent profactivity = new Intent(MainActivity.this, View.class);
profactivity.putExtra("Internet", false);
profactivity.putExtra("loginValue", loginValue);
profactivity.putExtra("id", id);
profactivity.putExtra("projectName", projectName);
profactivity.putExtra("stockPoint", stockPoint);
startActivity(profactivity);
**Toast.makeText(MainActivity.this, "Offline Login ", Toast.LENGTH_SHORT).show();
finish();
}
****for the above code, here it is throughing the error**
try {
final String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8");
final String passValue = URLEncoder.encode(password.getText().toString(), "UTF-8");
try {
new Thread(new Runnable() {
**//Thread to stop network calls on the UI thread**
public void run() {
//Request the HTML
ArrayList<String> list = null;
try {
String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8");
String passValue = URLEncoder.encode(password.getText().toString(), "UTF-8");
String ROOT_URL = getResources().getString(R.string.ROOT_URL) + "/api/v1/user/signIn?loginName=" + loginValue + "&password=" + passValue;
Log.i("httpget", "################" + ROOT_URL);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(ROOT_URL);
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
String server_response = EntityUtils.toString(response.getEntity());
myRespObject = new JSONObject(server_response);
//Do something with the response
//Toast.makeText(getBaseContext(),server_response,Toast.LENGTH_LONG).show();
statusRes = myRespObject.getString("status");
JSONObject respObject = myRespObject.getJSONObject("response");
id = respObject.getString("_id");
AppConstants._ID = id;
projectName = respObject.getString("projectName");
Actors actor = new Actors();
list = new ArrayList<>();
JSONArray jsonArray = respObject.getJSONArray("stockPoint");
Intent i = getIntent();
Serializable subject = i.getSerializableExtra("stockPoint");
if (jsonArray != null) {
int len = jsonArray.length();
for (int k = 0; k < len; k++)
list.add(jsonArray.get(k).toString());
}
actor.setStockPoint(list);
AppConstants.STOCK_POINT = stockPoint;
stockPoint = respObject.getString("stockPoint");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
final ArrayList<String> finalList = list;
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
statusRes = myRespObject.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
if (statusRes.equalsIgnoreCase("success")) {
SharedPreferences sharedpreferences = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(AppConstants.LOGIN_VALUE, loginValue);
editor.putString(AppConstants.PASS_KEY, passValue);
editor.putString("Internet", "true");
editor.putString(AppConstants.ID, id);
editor.putString(AppConstants.PROJECT_NAME, projectName);
editor.putString(String.valueOf(AppConstants.STOCK_POINT), String.valueOf(stockPoint));
editor.commit();
**//Here move to next screen or home screen**
Intent profactivity = new Intent(MainActivity.this, View.class); profactivity.putExtra("Internet", true); profactivity.putExtra("loginValue", loginValue); profactivity.putExtra("id", id);
profactivity.putExtra("projectName", projectName);
profactivity.putExtra("stockPoint", finalList);
startActivity(profactivity);
Toast.makeText(MainActivity.this, "Login Successfully", Toast.LENGTH_LONG).show();
finish();
} else if (statusRes.equalsIgnoreCase("failed")) {
if (!validate()) {
onLoginFailed();
return;
}
}
}
});
}
}).start();
//return data;
} catch (Exception e) {
Log.i("httpget", "################Error1 -->" + e.getStackTrace());
**Toast.makeText(getBaseContext(), "ERROR : " + e.getMessage(), Toast.LENGTH_LONG).show();**
}
} catch (UnsupportedEncodingException ex) {
finish();
}
}
});
}
public boolean validate() {
boolean valid = true;
String email = login.getText().toString();
String passwor = password.getText().toString();
if (email.isEmpty() || email.length() < 2 || email.length() > 10) {
login.setError("enter valid username");
valid = false;
} else {
login.setError("Invalid username");
}
if (passwor.isEmpty() || passwor.length() < 2 || passwor.length() > 10) {
password.setError("enter valid password");
valid = false;
} else {
password.setError("Invalid password");
}
return valid;
}
public void onLoginFailed() {
**Toast.makeText(getBaseContext(), "Invalid login", Toast.LENGTH_LONG).show();**
}
}
--------------------------------------------------------------------------------
The error that you have mentioned says you have error on following line.
projectName = respObject.getString("projectName");
"responseObject" is null, hence you are getting NullPointerException.

App connects to the server but can not communicate

I apologize in advance for my bad english
The app is able to connect to the server java, but hangs at the time of the exchange of data.
This is the client android code:
#SuppressLint("NewApi")
public class Connection extends IntentService{
private String tag = "Ciclo eventi";
private String user;
private String pass;
public Connection()
{
super("Connection");
}
public void onCreate(){
super.onCreate();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
public void onStart(Intent intent, int startId){
Log.d(tag, "GetData");
Bundle extras = intent.getExtras();
user = (String) extras.get("User");
pass = (String) extras.get("Password");
Log.d(tag, user);
Log.d(tag, pass);
onHandleIntent(intent);
}
public int onStartCommand(Intent intent, int flags, int startId){
onHandleIntent(intent);
return START_NOT_STICKY;
}
#Override
public void onDestroy()
{
Log.d(tag, "CONNECTION CLOSED");
}
#Override
protected void onHandleIntent(Intent intent) {
Socket s=null;
BufferedReader in=null;
PrintWriter writer=null;
try {
Log.d(tag, "Try to connect");
s = getConnection("192.168.1.103", 5433);
Log.d(tag, "Connection done");
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
writer = new PrintWriter(s.getOutputStream(), true);
writer.println(user);
writer.println(pass);
Log.d(tag, "I've send the credential");
String resp = null;
resp = in.readLine();
Log.d(tag, "Receive the results");
if(resp.equals("done")){
Log.d(tag, "ACCEPT");
/*Intent i=new Intent(this,SecondActivity.class);
startActivity(i);*/
onDestroy();
}
else{
Log.d(tag, "Refused");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected Socket getConnection(String ip, int port) throws IOException {
try {
KeyStore trustStore = KeyStore.getInstance("BKS");
InputStream trustStoreStream = getApplicationContext().getResources().openRawResource(R.raw.server);
trustStore.load(trustStoreStream, "keypass".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
SSLSocketFactory factory = sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket) factory.createSocket(ip, port);
//socket.setEnabledCipherSuites(getCipherSuitesWhiteList(socket.getEnabledCipherSuites()));
return socket;
} catch (GeneralSecurityException e) {
Log.e(this.getClass().toString(), "Exception while creating context: ", e);
throw new IOException("Could not connect to SSL Server", e);
}
}
public static String[] getCipherSuitesWhiteList(String[] cipherSuites) {
List<String> whiteList = new ArrayList<>();
List<String> rejected = new ArrayList<>();
for (String suite : cipherSuites) {
String s = suite.toLowerCase();
if (s.contains("anon") || //reject no anonymous
s.contains("export") || //reject no export
s.contains("null") || //reject no encryption
s.contains("md5") || //reject MD5 (weaknesses)
s.contains("_des") || //reject DES (key size too small)
s.contains("krb5") || //reject Kerberos: unlikely to be used
s.contains("ssl") || //reject ssl (only tls)
s.contains("empty")) { //not sure what this one is
rejected.add(suite);
} else {
whiteList.add(suite);
}
}
return whiteList.toArray(new String[whiteList.size()]);
}}
I need a service because i need a syncronous thread
This is the java server code:
public class SocketThread implements Runnable{
private Socket s1;
private BufferedReader in;
private PrintWriter out;
private String user = "admin";
private String pass = "ciao";
SocketThread(Socket s){
this.s1=s;
}
public void run(){
boolean loginDone = false;
String user1 = null;
String password1 = null;
String lati = null;
String longi = null;
String via = null;
System.out.println("Connected");
try {
in = new BufferedReader(new InputStreamReader(s1.getInputStream()));
out = new PrintWriter(s1.getOutputStream(), true);
user1 = in.readLine();
password1 = in.readLine();
System.out.println("User : "+user1+" Password : "+ password1);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("error on buffer creation");
e.printStackTrace();
}
System.out.println("Access done, wait for check credential");
do{
if(user1.compareTo(user)==0 && password1.compareTo(pass)==0){
loginDone = true;
out.println("done");
}
else{
out.println("noaccess");
}
}while(loginDone == false);
System.out.println("Login done");
try {
System.out.println("Close done");
s1.close();
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread off");
}}
Both the server and client crashes with no message error when exchanging data (both input and output)
The network is ok, the privileges of the android app are .INTERNET, .ACCESS_WIFI_STATE, .ACCESS_NETWORK_STATE
The server works well with a Java Desktop Client.
Thank you very much!
try using Volley
https://developer.android.com/training/volley/index.html
you can also use custom requests with volley.
https://developer.android.com/training/volley/index.html

Android bug in thread

I'm working on an android Quiz app with connection to a server over a socket. On the client side (Android device) I check in a while loop the answers which are given by a server (Java server). The connection and the receiving of the answer all goes good. The problem is that in my class to check for answers there's a bug. To give more information I will include a part of the code here:
public void startClient(){
checkValue = new Thread(new Runnable(){
#Override
public void run() {
try
{
final int PORT = 4444;
final String HOST = "192.168.1.118";
Socket SOCK = new Socket(HOST, PORT);
Log.e("success", "You connected to: " + HOST);
quizClient = new QuizClient(SOCK);
//Send the groupname to the list
PrintWriter OUT = new PrintWriter(SOCK.getOutputStream());
OUT.println(groupName);
OUT.flush();
Thread X = new Thread(quizClient);
X.start();
connected = true;
}
catch(Exception X)
{
Log.e("connection error", "Error: ", X);
}
}
});
checkValue.start();
}
public void testvalue(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
while(true){
if(message != null && !message.matches("")){
Thread.sleep(1000);
Log.e("receive", message);
buffer = message;
message = "";
Message msg = new Message();
String textTochange = buffer;
msg.obj = textTochange;
mHandler.sendMessage(msg);
Thread.sleep(3000);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String text = (String)msg.obj;
//call setText here
//String[] myStringArray = new String[];
value.clear();
String[] items = text.split(";");
for (String item : items)
{
value.add(item);
Log.e("message", item);
//System.out.println("item = " + item);
}
if(value.get(0).equals("1")){
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
question.setText("");
question.setText(value.get(2));
rad1.setText(value.get(3));
rad2.setText(value.get(4));
rad3.setText(value.get(5));
rad4.setText(value.get(6));
questionGroup.setVisibility(View.VISIBLE);
sendAnswer.setVisibility(View.VISIBLE);
} else if (value.get(0).equals("2")){
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
question.setText("");
question.setText(value.get(2));
answer.setVisibility(View.VISIBLE);
sendAnswer.setVisibility(View.VISIBLE);
} else
{
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
question.setText(text);
}
}
};
#Override
protected void onStop()
{
if (connected == true){
try {
quizClient.DISCONNECT();
} catch (IOException e) {
e.printStackTrace();
}
}
if(checkValue != null)
{
checkValue.interrupt();
}
super.onStop();
closeApplication();
}
So I make a new instance of this class (where I actually check the incoming stream of data)
public class QuizClient implements Runnable {
//Globals
Socket SOCK;
Scanner INPUT;
Scanner SEND = new Scanner(System.in);
PrintWriter OUT;
public QuizClient(Socket X)
{
this.SOCK = X;
}
public void run()
{
try
{
try
{
INPUT = new Scanner(SOCK.getInputStream());
OUT = new PrintWriter(SOCK.getOutputStream());
OUT.flush();
CheckStream();
}
finally
{
SOCK.close();
}
}
catch(Exception X)
{
Log.e("error", "error: ", X);
}
}
public void DISCONNECT() throws IOException
{
OUT.println("DISCONNECT");
OUT.flush();
SOCK.close();
}
public void CheckStream()
{
while(true)
{
RECEIVE();
}
}
public void RECEIVE()
{
if(INPUT.hasNext())
{
String MESSAGE = INPUT.nextLine();
if(MESSAGE.contains("#?!"))
{
}
else
{
QuizActivity.message = MESSAGE;
Log.e("test", MESSAGE);
}
}
}
public void SEND(String X)
{
OUT.println(X);
OUT.flush();
}
}
So the bug persist I think in the following class:
public void testvalue(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
while(true){
if(message != null && !message.matches("")){
Thread.sleep(1000);
Log.e("receive", message);
buffer = message;
message = "";
What I do here is make a thread and check if the "message" is not equals at null. The message come from the other class:
public void RECEIVE()
{
if(INPUT.hasNext())
{
String MESSAGE = INPUT.nextLine();
if(MESSAGE.contains("#?!"))
{
}
else
{
QuizActivity.message = MESSAGE;
Now most of the time this works good but there are 2 problems. When I go out of the page it disconnect from the server (works) I go back on the page and connect again to the server but this time I don't get any values on the screen (receiving is okj but for one of the other reason it does not go good in my handler). Also get an indexoutofboundexception after a time:
question.setText(value.get(2));
A second problem occurs some time while the program runs. There are moments that I also don't get a value on my interface while it correctly receive the input.
So my guess is that my solution of the thread to read in the values is not the best way to handle it. So now I ask to people with more experience what I can do to make this work without major problems? You need to know the connection works and I get the value in my QuizClient class. So the problem need to be in my main class.
My oncreate class:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
selectgroep = (Spinner) findViewById(R.id.groepen);
questionGroup = (RadioGroup) findViewById(R.id.QuestionGroup);
sendAnswer = (Button) findViewById(R.id.sendAnswer);
rad1 = (RadioButton) findViewById(R.id.radio0);
rad2 = (RadioButton) findViewById(R.id.radio1);
rad3 = (RadioButton) findViewById(R.id.radio2);
rad4 = (RadioButton) findViewById(R.id.radio3);
answer = (EditText) findViewById(R.id.textanswer);
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
try {
connect();
} catch (InterruptedException e) {
e.printStackTrace();
}
//Code na het drukken op de knop
startserver = (Button) findViewById(R.id.startserver);
startserver.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startClient();
getID();
testvalue();
}
});
sendAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Stuur antwoord door en sluit alles af
questionGroup.setVisibility(View.INVISIBLE);
sendAnswer.setVisibility(View.INVISIBLE);
answer.setVisibility(View.INVISIBLE);
answer.setText("");
rad1.setChecked(true);
rad1.setText("");
rad2.setText("");
rad3.setText("");
rad4.setText("");
question.setText("Wachten op server ... ");
}
});
}
Thank you in advance,
Thomas Thooft

Categories