What is wrong with this Asynchronus task? - android

the method onPostExecute simply was not executed, I have seen 36 at LogCat but I can not see 13 in LogCAT. I tried to debug it, it seemed that it goes to the first line of the class (package line) after return statement.
private class Client extends AsyncTask<Integer, Void, Integer> {
protected Integer doInBackground(Integer... params) {
Log.e(TAG,10+"");
try {
socket = new Socket(target, port);
//socket.setSoTimeout(3000);
Log.e(TAG,31+"");
oos = new ObjectOutputStream(socket.getOutputStream());
Log.e(TAG,34+"");
ois = new ObjectInputStream(socket.getInputStream());
Log.e(TAG,35+"");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e(TAG,36+"");
return 1;
}
protected void onPostExecute(Integer result) {
Log.e(TAG,13+"");
try {
Log.e(TAG,12+"");
oos.writeUTF(key);
Log.e(TAG,16+"");
if (ois.readInt() == OKAY) {
isConnected = true;
Log.e(TAG,14+"");
}else{
Log.e(TAG,15+"");
isConnected = false;
}
} catch (IOException e) {
e.printStackTrace();
isClosed = true;
}
Log.e(TAG,19+"");
}
}
Number seen in logCat:
10
31
34
35
36
Nothing after that.

Related

How to avoid EOFExeption by read from socket in AsyncTask that repeats in handle?

I need to update data from server every second. I create handle with AsyncTask, that repeats every second. This works, but about a minute it crushes with EOFException by reading from DataInputStream.
Handler
handler.postDelayed( new Runnable() {
#Override
public void run() {
tickListAdapter = new TickListAdapter(TickActivity.this,tickList);
tickListView.setAdapter(tickListAdapter);
AsyncTCPSend tcpSend= new AsyncTCPSend(address,serverPort, line);
tcpSend.execute();
Log.e(TAG,"update");
handler.postDelayed( this, 1000 );
}
},1000 );
AsyncTask
public class AsyncTCPSend extends AsyncTask<Void, Void, Void> {
String address;
int port;
String message;
String response=null;String lineRead = null;
Socket socket;
int count=1;
OutputStream os;
DataInputStream dis;
AsyncTCPSend(String addr, int p, String mes) {
address = addr;
port = p;
message = mes;
}
#Override
protected Void doInBackground(Void... params) {
socket = null;
try {
socket = new Socket(address, port);
os = socket.getOutputStream();
dis = new DataInputStream(socket.getInputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (!isConnect){
if (connect()){
isConnect = true;
Log.e("CLIENT","now is connected");
getTick();
}
}
return null;
}
public boolean connect(){
try {
Log.e("CLIENT","CONNECTED");
String command = "AUTH_START";
byte[] queryBody = null;
queryBody = command.getBytes("UTF-16LE");
byte[] message = new byte[queryBody.length];
for (int i = 0; i < message.length; ++i)
os.write(message,0,message.length);
Log.e(TAG,"AUTH_START");
String srv = null;
srv = function();
if (srv != null){
if (srv.equals("Error")){
Log.e("CLIENT","Error");
return false;
} else {
String auth_answer = "AUTH_ANSWER";
byte[] authBody = auth_answer.getBytes("UTF-16LE");
Log.e(TAG,"AUTH_ANSWER");
os.write(authBody,0,authBody.length);
srv = function();
if (srv.equals("Error")){
Log.e("CLIENT","Error");
return false;
} else {
Log.e(TAG,"AUTH SUCCESS!!!");
return true;
}
}
} else {
return false;
}
}
catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public String getTick(){
String tick = "TICK";
try {
tickBody = tick.getBytes("UTF-16LE");
os.write(tickBody,0,tickBody.length);
String srv = function();
return srv;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
String function(){
String srv = null;
int len = 0;
try {
len = dis.readInt(); //EOFException is here!!!!
byte[] data = new byte[1024];
if (len > 0) {
dis.read(data, 0, data.length);
}
String out = new String(data,"UTF-16");
if (out.indexOf("Done")>0){
if (out.indexOf("STAT")>0 ||out.indexOf("AST")>0){
srv = out;
}
else {
srv = out.substring(out.indexOf("SRV")+9,out.indexOf("SRV")+41);
}
} else {
srv = "Error";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return srv;
}
#Override
protected void onPostExecute(Void result) {
Log.e("CLIENT","onPostExecute");
super.onPostExecute(result);
}
}
}
Anybody know why appear EOFException about a minute? How to avoid?
P.S. To obtain the necessary information from the server, I must first pass authentication
Why this exception occurs?
According to Docs
Signals that an end of file or end of stream has been reached unexpectedly during input.
This exception is mainly used by data input streams to signal end of stream. Note that many other input operations return a special value on end of stream rather than throwing an exception.
look upon this answer
The problem was solved by changing the method. I added two threads for output and input inside AsyncTask

Filelist filelist request.execute() does not work

I want to list all the files that my google accouunts have with my app, i tried the follow piece of code which is actually from the website, but , there's error in the line " FileList fileList = request.execute(); ", it says the method execute() is undefined for the type Drive.Files.List ,i don't know how to fix it.
private void getDriveContents()
{
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
com.google.api.services.drive.Drive.Files f1 = mService.files();
Files.List request = null;
do
{
try
{
request = service.files().list().setQ("trashed=false");
FileList fileList = request.execute();
mResultList.addAll(fileList.getItems());
request.setPageToken(fileList.getNextPageToken());
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
if (request != null)
{
request.setPageToken(null);
}
}
} while (request.getPageToken() !=null && request.getPageToken().length() > 0);
populateListView();
}
});
t.start();
}
I believe your 'request' is of incorrect type. it is supposed to be FileList, not File.List
I wasn't arguing about what you've seen. I was only trying to help since I have similar code running and tested. Here's a snippet from my "class ListDownFromGOODrive extends AsyncTask..."
import com.google.api.services.drive.model.FileList;
...
.... a lot of code here
...
GoogleAccountCredential _crd;
Drive _svc;
FileList _gooLst;
Intent _it;
String _rqst;
...
... a lot of code here
...
#Override protected Integer doInBackground(Void... nothing) {
try {
if (_crd == null)
_crd = GoogleAccountCredential.usingOAuth2(_ctx,Arrays.asList(DriveScopes.DRIVE_FILE));
if (_svc == null)
_svc = new Drive.Builder
(AndroidHttp.newCompatibleTransport(), new GsonFactory(), _crd).build();
if (_crd.getSelectedAccountName() == null) {
_it = _crd.newChooseAccountIntent();
return REQ_EMAIL;
}
_gooLst = _svc.files().list().setMaxResults(MAX_DOWN).setQ(_rqst)
.setFields("items(id,title,description,downloadUrl,thumbnailLink)").execute();
}
catch (UserRecoverableAuthIOException e){ //Log.d("atn", "LD URAIO Except->REQ_AUTH");
try { _it = e.getIntent(); } catch (Exception e1) {return ERROR;}
return REQ_AUTH;
}
catch (IOException e) { return ERROR; }
catch (Exception e) { return ERROR; }
return GOOD;
}
it returns GOOD, ERROR, REQ_AUTH(orization), or REQ_EMAIL(account)

android - LAN socket programming -- getting nullpointer and address-in use exception

i've done an application in which the android application send datas to java desktop swing application as well as send datas from desktop to android using TCP socket programming through wifi.
Th application is a Hotel Kitchen order booking system
The problem describes that Dine_Tables class contains buttons which represents each tables in a hotel, on clicking table1 button for example it starts the BackgroundServers Asyntask which runs a server for receiving desktop application datas also it takes the activity from Dinein_Tables.java to Food_Customizer.java.
In Food_Customizer.java on clicking submit button it starts ServersendAsyncAction Asyntask which sends some datas to desktop swing application.
The desktop application after processing sends some datas to android application, The server that runs in the android application on receiving the datas goes again from Food_Customizer.java to Dinein_Tables.java activity in the BackgroundServers Asyntask onPostExecute method.
The problem is that when i do this process a two or three times the application stop due to address-in use and Null-Pointer exception at socket = serverSocket.accept(); in the BackgroundServers Asyntask.
Can anyone please tell me some solution for this problem
Dinein_Tables.java
public class Dinein_Tables extends Activity {
:
:
table1.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
new Handler().postDelayed(new Runnable() {
public void run() {
Food_Customizer.BackgroundServers ob = new Food_Customizer().new BackgroundServers(contexts);
ob.execute("");
Intent toAnotherActivity = new Intent(v.getContext(), Food_Customizer.class);
startActivity(toAnotherActivity);
finish();
}
}, 100L);
}
});
}
Food_Customizer.java
public class Food_Customizer extends Activity {
:
:
submit= (Button)findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pd = ProgressDialog.show(contexts, "Sending to Server...","Please Wait...", true, false);
new ServersendAsyncAction().execute();
}
});
:
:
/****************************** AsyncTask ********************************************************/
private class ServersendAsyncAction extends AsyncTask<String, Void, String> {
/****************************** AsyncTask doInBackground() ACTION ********************************/
protected String doInBackground(String... args) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
boolean flag = true;
while (flag) /******** If data is send flag turn to be false *******/
{
try {
socket = new Socket("192.168.1.74", 4444);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(datastosend);
flag = false;
} catch (UnknownHostException e) {
flag = true;
e.printStackTrace();
} catch (IOException e) {
flag = true;
e.printStackTrace();
}
/******** CLOSING SOCKET *****************/
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/******** CLOSING DATAOUTPUTSTREAM *******/
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/******** CLOSING DATAINPUTSTREAM ********/
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
/******** returns what you want to pass to the onPostExecute() *******/
}
/****************************** AsyncTask onPostExecute() ACTION *********************************/
protected void onPostExecute(String result) {
}
/********************* ENDING OF ASYN TASK CLASS ServersendAsyncAction ***************************/
}
public Context con;
public static ServerSocket serverSocket = null;
public class BackgroundServers extends AsyncTask<String, Void, String> {
public BackgroundServers(Context context) {
con=context;
}
/****************************** AsyncTask doInBackground() ACTION ********************************/
protected String doInBackground(String... args) {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(9999);
System.out.println("Listening :9999");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
String incoming_message=(dataInputStream.readUTF());
incoming_message=incoming_message.replace("/", "");
String recdatas[]=incoming_message.split("#");
if(recdatas[0].equalsIgnoreCase("success"))
{
DatabaseConnection dbs=new DatabaseConnection(con);
int status=dbs.update("UPDATE hotel_pub_tables SET status='occupied' WHERE tableno='"+recdatas[1]+"'");
if(status>0)
{
tabelstatus=1;
//msg.obj="Table status changed!!!";
System.out.println("Table status changed!!!");
if (true) {
System.out.println("entered 222");
System.out.println(tabelstatus);
if(tabelstatus==1)
{
System.out.println(tabelstatus);
Food_Customizer.pd.dismiss();
System.out.println("success");
}
else if(tabelstatus==2)
{
Food_Customizer.pd.dismiss();
Intent intent = new Intent(Food_Customizer.this, Dinein_Tables.class);
startActivity(intent);
finish();
}
}
}
else
tabelstatus=2;
dbs.close();
}
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
/******** returns what you want to pass to the onPostExecute() *******/
}
/****************************** AsyncTask onPostExecute() ACTION *********************************/
#Override
protected void onPostExecute(String result) {
System.out.println("eneterd on posttttttttttttttt");
con.startActivity(new Intent(con, Dinein_Tables.class));
finish();
}
}
}
/********************* ENDING OF ASYN TASK CLASS BackgroundServers ***************************/
}
Well it's obvious that you setup your server on port 9999:
serverSocket = new ServerSocket(9999);
But you connect with the server on port 4444:
socket = new Socket("192.168.1.74", 4444);
Make sure you connect to the correct port-number otherwise it wont work. Hope this helps.

How to create asyncTask to prevent networkOnMainThreadException

I'm new to android application development. I tried to develop an android server client chat
for my first project. This is the code for the client side. When the client press btnJoin,
it will connect to the server and send a string. I've read many example and many of them
looks like this. I got a networkOnMainThreadException. How do I make an asyncTask to prevent
this problem? Any help would be much appreciated.
btnJoin = (Button) findViewById(R.id.buttonJoin);
btnJoin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.4", 9092);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF("Hello server!");
txtIP.append(dataInputStream.readUTF() + "\n");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
Change your code as:
btnJoin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view){
new LongOperation().execute("");
}
}
private class LongOperation extends AsyncTask<String, Void, String> {
Socket socket = null;
String strresult="";
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
#Override
protected String doInBackground(String... params) {
try {
socket = new Socket("192.168.1.4", 9092);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF("Hello server!");
strresult.append(dataInputStream.readUTF() + "\n");
// txtIP.append(dataInputStream.readUTF() + "\n");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return strresult;
}
#Override
protected void onPostExecute(String result) {
TextView txtIP= (TextView) findViewById(R.id.txtIP);
// txtIP.append(result + "\n");
txtIP.setText(result + "\n");
}
#Override
protected void onPreExecute() {
}
}
Use AsyncTask like this :
First have it nested in your class, it should look similar to :
private class Communicator extends AsyncTask<Void, Void, Boolean> {
String tmp;
String err;
#Override
protected Boolean doInBackground() {
try {
socket = new Socket("192.168.1.4", 9092);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF("Hello server!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(Boolean result) {
txtIP.append(dataInputStream.readUTF() + "\n");
}
}
When you have AsyncTask,you can start it like this :
...
#Override
public void onClick(View v) {
Communicator c=new Communicator();
c.execute();
}
....
try to implement this code in your app
private class LongOperation extends AsyncTask<Object, Integer, Object> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Object doInBackground(Object... params) {
//do hard work here
return params;
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
}
}
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)
Here is an example of subclassing:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Once created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);
for more details refer below links...
http://www.vogella.com/articles/AndroidPerformance/article.html
http://developer.android.com/reference/android/os/AsyncTask.html

Android TCP client

I'm currently working on a tcp client in Android.
I want to connect my android device to a tcp server on my computer and receive the data once every 2 seconds. The problem is that I'm getting force close on my application because of the while loop that I've implemented in the tcp client.
I've tried writing in different ways the loop that will make the tcp client checking the server socket, but with no success. How can make a loop that will check the server socket without getting the force close?
Here's my code that I'm currently using:
public class Connection implements Runnable {
#Override
public void run() {
try {
sk=new Socket(server,port);
viewsurface.setText("connected");
flag = true;
} catch (UnknownHostException e) {
viewsurface.setText("failed 1 socket");
flag = false;
} catch (IOException e) {
viewsurface.setText("failed 2 socket");
flag = false;
}
while (flag == true){
try {
checkin = sk.getInputStream();
checkint = checkin.available();
if (checkint > 0){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(sk.getInputStream()));
received = in.readLine();
viewsurface.setText(received);
} catch (IOException e) {
viewsurface.setText("failed to receive");
}
}
Thread.sleep(2000);
} catch (IOException e) {
viewsurface.setText("checkin failed");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
You need to paste the exception that you are getting to cause the force close, before anyone can provide decent help.
But some suggestions that might solve the problem.
Most likely to be the problem, viewText.setText can only be called from the UI thread. There's quite a few ways to handle this. You can use AsyncTask or if you have an Activity reference you can use runOnUIThread and pass in a runnable that calls setText.
Move checkin = sk.getInputStream(); to before the loop. There's no reason to get the strem every cycle through the loop.
Do not create the BufferedReader every cycle through the loop. Move it before the loop
.sleep(2000) does not guarantee exactly 2 seconds.
I'm having some code formatting issues so I apologize.
private class DownloadFilesTask extends AsyncTask<Void, String, Void> {
protected Long doInBackground(Void... nothing) {
try {
sk=new Socket(server,port);
publishProgress("connected");
flag = true;
} catch (UnknownHostException e) {
publishProgress("failed 1 socket");
flag = false;
} catch (IOException e) {
publishProgress("failed 2 socket");
flag = false;
}
while (flag == true){
try {
checkin = sk.getInputStream();
checkint = checkin.available();
if (checkint > 0){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(sk.getInputStream()));
received = in.readLine();
publishProgress(received);
} catch (IOException e) {
publishProgress("failed to receive");
}
}
Thread.sleep(2000);
} catch (IOException e) {
updateProgress(
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
protected void onProgressUpdate(String... progress) {
viewsurface.setText(progress[0]);
}
protected void onPostExecute(Void result) {
//nothing
}
}

Categories

Resources