I wrote simple android java client , main activity with socketTask and and a handler in mainactivity. and it doesn't working .
I used debuger and found that the problem is in this line :
this.socket = new Socket(IP_ADDRESS, PORT);
I also had this error massage in the studio :
An unexpected packet was received before the handshake
the server is ok and responding to any other program .
Can some one advice what is the problem . I attaching mainactivity and socket task .
thanks a lot .
main activity
package com.example.app24;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
Button btnSend ;
TextView tvFromServer;
EditText etToSend;
String strToSend,strFromServer;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend = (Button) findViewById(R.id.btnSend);
btnSend.setOnClickListener(this);
etToSend = (EditText) findViewById(R.id.etToSend);
tvFromServer = (TextView) findViewById(R.id.tvFromServer);
tvFromServer = (TextView) findViewById(R.id.tvFromServer);
}
#Override
public void onClick(View v)
{
if (v == btnSend)
{
strToSend = etToSend.getText().toString();
new Thread(new Runnable() {
#Override
public void run() {
SocketTask send1 = new SocketTask(strToSend);
strFromServer=send1.sendReceive();
runOnUiThread(new Runnable() {
public void run() {
tvFromServer.setText(strFromServer);
}
});
}
}).start();
}
}
}
'''
SocketTask.
```
package com.example.newproj;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import androidx.annotation.RequiresApi;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class SocketTask
{
//private final static String IP_ADDRESS = "172.19.16.179";
private final static String IP_ADDRESS = "192.168.1.124";
private final static int PORT = 8821; // HTTP port
private final static int PACKET_SIZE = 1024; // standard 1kb packet size
private Socket socket;
private String sendingStr="";
private String receivingStr="";
BufferedReader reader;
public SocketTask(String str1)
{
this.sendingStr = str1;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void send()
{
try {
OutputStreamWriter writer = new OutputStreamWriter(this.socket.getOutputStream(), StandardCharsets.UTF_8); // outputStreamWriter creating
writer.write(this.sendingStr);
writer.flush();
Log.d("Result", "sent");
}
catch (Exception e) {
Log.e("Exception", e.toString());
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void receive() {
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
char[] charBuffer = new char[1024];
StringBuilder stringBuilder = new StringBuilder();
reader.read(charBuffer);
stringBuilder.append(charBuffer);
reader.close();
receivingStr = stringBuilder.toString();
}
catch (IOException e)
{
Log.e("Exception", e.toString());
}
}
public String sendReceive()
{
try {
this.socket = new Socket(IP_ADDRESS, PORT);
send();
receive();
this.socket.close();
} catch (Exception e) {
Log.e("Exception", e.toString());
}
return this.receivingStr;
}
}
```
I am asking here as all other solutions have not worked. I want to read a text file from the web and have this string put into a textview. I am just testing at the moment and the only thing in the text file is the value "223". My app is crashing on start can anyone please help?
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.StringBuilderPrinter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private StringBuilder text = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader reader = null;
try {
URL url = new URL("http://something.uk/pmt/status.txt");
reader = new BufferedReader(
new InputStreamReader(url.openStream()));
String str;
while ((str = reader.readLine()) != null) {
text.append(str);
text.append('\n');
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error reading file.", Toast.LENGTH_LONG).show();
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (MalformedURLException e) {
}
catch (IOException e) {
}
}
TextView output = (TextView) findViewById(R.id.textView);
output.setText((CharSequence) text);
}
}
}
STACKTRACE:
https://pastebin.com/YSCB9RBg
Probably because you are using StringBuilder which is not a CharSequence. Use output.setText(text.toString()); instead of output.setText((CharSequence) text);
TextView.setText() expects a CharSequence as an argument. String is a CharSequence, but StringBuilder is not. To get a String you gave to call StringBuilder.toString()
You should look at the crash though. And post it next time you ask a question on stackoverflow.
The crash log you provided clearly states the reason for crash: android.os.NetworkOnMainThreadException. It means that you are trying to do a network operation on the main thread and the Android OS does not let you. It is a rule since Honeycomb. The solution is to use AsyncTask, for example. Here is an article about network ops and AsyncTask.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.StringBuilderPrinter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private StringBuilder text = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader reader = null;
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://something.uk/pmt/status.txt");
reader = new BufferedReader(
new InputStreamReader(url.openStream()));
String str;
while ((str = reader.readLine()) != null) {
text.append(str);
text.append('\n');
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error reading file.", Toast.LENGTH_LONG).show();
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (MalformedURLException e) {
}
catch (IOException e) {
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
TextView output = (TextView) findViewById(R.id.textView);
output.setText(text.toString());
}
}.execute(null,null,null);
}
}
}
I am trying to run a simple app that extracts html from a page and displays it in the logs.
Here is the Java code:
package com.example.khkr.jsondemo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public class DownloadTask extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... params) {
URL url;
String result = "";
try {
url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data!=-1)
{
char current = (char)data; result+=current;
data = reader.read();
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content",weatherInfo);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
The problem is I don't see any errors in the code , but when I try to run the app, I get the following Logs which never make sense to me. Here are the logs:
https://gist.github.com/khkr/d96396ff6f8e34b3e9a430a805b735a7
I'm trying to call the function getUrlContents(string) inside my seismic_text.java file to my MainActivity.java file. How can I call the function from anywhere in the file? Any information or tip is appreciated. I include my files down below.
This is my MainActivity.java:
package bt.alfaquake;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.NotificationManager;
import android.content.Intent;
import android.view.View;
import android.app.PendingIntent;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.NotificationCompat;
import bt.alfaquake.seismic_text;
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int uniqueID = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
}
}
This is my seismic_text.java:
package bt.alfaquake;
import java.net.*;
import java.io.*;
public class seismic_text {
public static String getUrlContents(String theUrl) {
StringBuilder content = new StringBuilder();
try
{
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
}
You can call seismic_text.getUrlContents(url); but it will cause NetworkOnMainThreadException
Just wrap this call to Simple AsynkTask.
class MyTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
return seismic_text.getUrlContents(url);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// TODO handle result here
}
}
And call it from your code:
new MyTask().execute();
Simply call this in your MainActivty.java:
seismic_text.getUrlContents(url);
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 "";
}