I want to show a progress bar in my activity which contains code to test server connection using socket. I want my progress bar to be visible only when sending data to server. As soon as i got reply from server, the progress should be dismissed and shows Alert box with message "Server busy". but in my screen the progress bar is visible after getting reply from server.Here is my code .
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mProgress = (ProgressBar) findViewById(R.id.progressBar1);
mProgress.setProgress(0);
checkdb();
}
private void checkdb() {
String message = "";
try {
serverIpAddress = InetAddress.getByName("192.168.1.133");
Log.d("TCP", "C: Connecting...");
socketObject = new Socket(serverIpAddress, 8221);
String str = "hi";
try {
Log.d("TCP", "C: Sending: '" + str + "'");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socketObject.getOutputStream())), true);
out.println(str);
inputStream = socketObject.getInputStream();
inputDataStream = new DataInputStream(inputStream);
message = inputDataStream.readUTF();
Log.d("TCP", "C: Reply: '" + message + "'");
}
catch(IOException e)
{
Log.e("TCP", "S: Error", e);
}catch (Exception e) {
Log.e("TCP", "S: Error", e);
}
finally {
socketObject.close();
Log.e("TCP", "S: Error");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: UnknownHostException", e);
e.printStackTrace();
}
catch(IOException e)
{
Log.e("TCP", "S: Error:", e);
//Code to show Alert box with message "IOException"
}
}
so what should be done to have my progress bar to be visible before i get reply from server. If i get reply, the progress bar should be dismissed.
Any one please help me...
Here is how I have implemented progressbar while authenticating a user using AsyncTask. See if this can help you
private class LoginTask extends AsyncTask<String, Integer, Boolean>{
private final ProgressDialog dialog = new ProgressDialog(LoginActivity.this);
public LoginTask(LoginActivity activity) {
}
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait..");
this.dialog.setIndeterminate(true) ;
this.dialog.setCancelable(false);
this.dialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
try {
Thread.sleep(5000); //Execute long running task
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Boolean result) {
if (this.dialog.isShowing()) { this.dialog.dismiss(); }
LoginActivity.this.processAuthenticationResult(result.booleanValue());
}
}
And called this from my LoginActivity as below
new LoginTask(LoginActivity.this).execute(new String[]{userName, password});
Just use mProgress.setVisibility(View.GONE) or mProgress.setVisibility(View.VISIBLE) to hide and show your widget.
To avoid that your main user activity gets blocked you need to do the connection part in a separate thread and use a Handler to update it. The code would be sth like:
In the connection thread to inform the UI activity...
mHandler.obtainMessage(Main_screen.MESSAGE_PGROGRESS_CHANGE_UPDATE, state, -1)
.sendToTarget();
In the UI activity:
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
"-> "
+ Thread.currentThread().getStackTrace()[2]
.getMethodName());
switch (msg.what) {
case MESSAGE_PGROGRESS_CHANGE_UPDATE:
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
" MESSAGE_PGROGRESS_CHANGE_UPDATE: " + msg.arg1);
// do your update of progressbar or whatever here
break;
case MESSAGE_PGROGRESS_CHANGE_SYNCHRINIZATION:
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
" MESSAGE_PGROGRESS_CHANGE_SYNCHRINIZATION: " + msg.arg1);
// do your update of progressbar or whatever here
break;
HI
You can use AsynTask for doing severcommunication in background and display the result to screen. I hope this code helps you.
public class PlasmaViewReDirectionTask extends
AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// showDialog("Fetching Video Url........");
favDialog = new Dialog(PlasmaView.this,
android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
favDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
favDialog.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
favDialog.setContentView(R.layout.busypopup);
loadMessage = (TextView) favDialog
.findViewById(R.id.loadingmessgetext);
loadMessage.setText("Communicating with server........");
favDialog.setCancelable(false);
try {
favDialog.show();
} catch (Exception e) {
// TODO Auto-generated catch block
logger.info("Dialog " + e.getMessage());
}
}
#Override
protected String doInBackground(Void... params) {
String message = "";
try {
serverIpAddress = InetAddress.getByName("192.168.1.133");
Log.d("TCP", "C: Connecting...");
socketObject = new Socket(serverIpAddress, 8221);
String str = "hi";
try {
Log.d("TCP", "C: Sending: '" + str + "'");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socketObject.getOutputStream())), true);
out.println(str);
inputStream = socketObject.getInputStream();
inputDataStream = new DataInputStream(inputStream);
message = inputDataStream.readUTF();
Log.d("TCP", "C: Reply: '" + message + "'");
}
catch(IOException e)
{
Log.e("TCP", "S: Error", e);
}catch (Exception e) {
Log.e("TCP", "S: Error", e);
}
finally {
socketObject.close();
Log.e("TCP", "S: Error");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: UnknownHostException", e);
e.printStackTrace();
}
catch(IOException e)
{
Log.e("TCP", "S: Error:", e);
//Code to show Alert box with message "IOException"
}
return message;
}
#Override
protected void onPostExecute(String result) {
try {
if (favDialog.isShowing()) {
favDialog.dismiss();
favDialog = null;
}
} catch (Exception e1) {
}
Toast.makeText(YourScreen.this, result, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
}
Related
I am trying to create a very-very simple server-client application in Android.
The server is running on my pc, it was written in python. (just a simple while (true) loop which receives a string and responses with an other string.)
The problem is in the Android client. So i tried to create a singleton class in a separate thread, which:
create the socket
connect to the socket
is reachable from other activites
write to socket
read from socket
I try to write and read from an other asynctask.
It is working until i try to write to the socket again. (1 write is ok, any other attempts are failed.) I do not get any exception, i checked if the socket closed or the writer null, etc. The message just not wrote to the socket.
What's wrong with this solution? :/
Could you please help me?
Here is the thread:
public class ConnectThread extends Thread
{
// singleton Part
private static class ThreadHolder {
static final ConnectThread instance = new ConnectThread();
}
public static synchronized ConnectThread getInstance(){
if(ThreadHolder.instance == null)
Log.d("mytag", "NEW INSTANCE CREATED");
// return (ThreadHolder.instance == null) ? ThreadHolder.instance = new ConnectThread() : ThreadHolder.instance;
return ThreadHolder.instance;
}
private ConnectThread(){
}
// implementation part
private Socket mSocket;
private BufferedWriter socketWriter;
private BufferedReader socketReader;
public Socket getSocket() {
return mSocket;
}
public void WriteToSocket(String msg)
{
try{
if(!(mSocket.isClosed()))
{
Log.d("mytag", "Writing to socket");
if(socketWriter == null)
Log.d("mytag", "Writer closed - in write to socket");
socketWriter.write(msg);
socketWriter.flush();
}else
Log.d("mytag", "CANT write to socket");
}catch(IOException e)
{
e.printStackTrace();
Log.d("mytag", e.toString());
}
}
public String ReadFromSocket()
{
try
{
if(!(mSocket.isClosed())) {
Log.d("mytag", "Reading from socket");
if(socketReader == null)
{
Log.d("mytag", "Reader closed - in read from socket");
}
return socketReader.readLine();
}else
{
Log.d("mytag", "CANT from socket");
return null;
}
}catch (IOException e)
{
e.printStackTrace();
return null;
}
}
#Override
public void run() {
try
{
mSocket = new Socket();
mSocket.setKeepAlive(true);
try
{
mSocket.setTcpNoDelay(true);
}
catch (SocketException e)
{
}
mSocket.connect(new InetSocketAddress("192.168.0.128", 8888), 2000);
if(!(mSocket.isClosed()))
{
Log.d("mytag", "SOCKET IS RUNNING");
socketWriter = new BufferedWriter(new OutputStreamWriter(this.mSocket.getOutputStream()));
socketReader = new BufferedReader(new InputStreamReader(this.mSocket.getInputStream()));
if(socketWriter == null)
{
Log.d("mytag", "WRITER NOT CREATED");
}else
Log.d("mytag", "WRITER READY");
if(socketReader == null)
{
Log.d("mytag", "READER NOT CREATED");
}else
Log.d("mytag", "READER READY");
}
}catch (IOException e)
{
e.printStackTrace();
}
}
}
And here are the attempts to read, write:
#Override
protected Void doInBackground(Void... params)
{
PrintDebugMsg("do in background");
//--------------------------------------------------------------------------------------
changeProgressMsg(progressDialog, "Checking network availability...");
//progressDialog.setTitle("Checking network availability...");
//check network:
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(parentContext.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if(netInfo != null && netInfo.isConnected())
{
networkAvail = true;
response += "| Network available |";
}
PrintDebugMsg("do in background 2");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
changeStatusImg(imgvNetworkStatus, networkAvail?R.drawable.online:R.drawable.offline);
//--------------------------------------------------------------------------------------
changeProgressMsg(progressDialog, "Pinging server");
//progressDialog.setTitle("Pinging server...");
//check server status
try {
PrintDebugMsg("do in background 3");
if(!(ConnectThread.getInstance().getSocket().isClosed()))
{
ConnectThread.getInstance().WriteToSocket(PING_FROM_DROID);
String line = "";
line = ConnectThread.getInstance().ReadFromSocket();
if(line.equals(PING_ACK))
{
serverAvail = true;
response += " | pinged |";
PrintDebugMsg("do in background 4", true);
}
}
else{
response += " | NOT pinged |";
PrintDebugMsg("do in background 5", true);
throw new UnknownHostException();
}
PrintDebugMsg("do in background 6", true);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response += " | UnknownHostException: " + e.toString() + " - during server check |";
PrintDebugMsg("do in background 7", true);
} finally{
PrintDebugMsg("do in background 9", true);
if(ConnectThread.getInstance().getSocket() != null){
}
}
PrintDebugMsg("do in background 10", true);
if(serverAvail)
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
changeStatusImg(imgvServerStatus, serverAvail?R.drawable.online:R.drawable.offline);
//--------------------------------------------------------------------------------------
changeProgressMsg(progressDialog, "Connectiong to server...");
//connect to server:
try {
PrintDebugMsg("do in background 11",true);
//socket = new Socket(dstAddress, dstPort);
//socket = ConnectThread.getInstance().getSocket();
PrintDebugMsg("do in background 12",true);
if(!(ConnectThread.getInstance().getSocket().isClosed())) {
PrintDebugMsg("do in background 13",true);
PrintDebugMsg("do in background 14",true);
PrintDebugMsg("do in background 15",true);
ConnectThread.getInstance().WriteToSocket(CONN_REQ_FROM_DROID);
String line = "";
line = ConnectThread.getInstance().ReadFromSocket();
PrintDebugMsg("conn line = " + line, true);
if(line != null && line.equals(CONN_ACK))
{
connected = true;
response += "| connected |";
PrintDebugMsg("do in background 12");
}
}else
{
response += "| NOT connected |";
PrintDebugMsg("do in background 13");
throw new UnknownHostException();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response += " | UnknownHostException: " + e.toString() + " - during connecting |";
}finally{
PrintDebugMsg("connection finished");
}
if(connected) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
changeStatusImg(imgvConnectionStatus, connected?R.drawable.online:R.drawable.offline);
//--------------------------------------------------------------------------
------------
return null;
}
The "util" functions:
private void PrintDebugMsg(String msg, boolean b)
{
if(b)
Log.d("mytag", msg);
}
private void changeProgressMsg(final ProgressDialog dialog,final String value){
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.setMessage(value);
}
});
}
private void changeStatusImg(final ImageView imgView, final int imgId){
runOnUiThread(new Runnable() {
#Override
public void run() {
imgView.setImageResource(imgId);
}
});
}
Sever.java
public class Server {
public static void main(String[] args) {
new Server().startServer();
}
public void startServer() {
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);
Runnable serverTask = new Runnable() {
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(8000);
System.out.println("Waiting for clients to connect...");
while (true) {
Socket clientSocket = serverSocket.accept();
clientProcessingPool.submit(new ClientTask(clientSocket));
}
} catch (IOException e) {
System.err.println("Unable to process client request");
e.printStackTrace();
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
}
private class ClientTask implements Runnable {
private final Socket clientSocket;
private ClientTask(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
System.out.println("Got a client !");
// Do whatever required to process the client's request
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I have the following code, and all works fine when I can connect to the server:
public void getXMLData()
{
if (skipUpdate)
{
skipUpdate=false;
return;
}
skipUpdate=true;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int SERVERPORT=0;
try {
SERVERPORT = Integer.parseInt(prefs.getString("pref_key_port_1","Port"));
} catch (NumberFormatException e) {
txtStatus.setText("Invalid Port Number");
return;
}
String SERVERHOST = prefs.getString("pref_key_host_1","127.0.0.1");
String PASSWORD = prefs.getString("pref_key_pass_1", "password");
try {
XMLFetcherTask myXMLFetcherTask = new XMLFetcherTask(SERVERHOST,SERVERPORT,PASSWORD);
myXMLFetcherTask.execute();
} catch (Exception e) {
txtStatus.setText("Error "+e.getMessage());
return;
}
skipUpdate=false;
}
public class XMLFetcherTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String password="";
XMLFetcherTask(String addr, int port, String pass){
dstAddress = addr;
dstPort = port;
password=pass;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(password);
response="";
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (response.toLowerCase().indexOf("</response>")<0)
{
response+=input.readLine();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtStatus.setText("UnknownHostException: " + e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtStatus.setText("IOException: " + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtStatus.setText("Exception: " + e.getMessage());
} finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//txtStatus.setText("Exception Finally: " + e.getMessage());
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if( !(response.substring(0,5).equalsIgnoreCase("<resp") || response.substring(0,5).equalsIgnoreCase("<?xml")) ) //!response.substring(0,5).equalsIgnoreCase("<?xml") ||
{
txtStatus.setText("Server response doesn't look XML, please check password: '"+response.substring(0,5)+"'");
} else {
lastXMLData=response;
txtStatus.setText("Resp Len: " + response.length());
skipUpdate=false;
updateFragmentListeners();
}
super.onPostExecute(result);
}
}
Now, when I get UnknownHostException, the app force close with following stack trace:
07-29 15:52:08.754 1525-1538/android.process.acore V/BackupServiceBinder﹕ doBackup() invoked
07-29 15:52:08.766 1525-1538/android.process.acore E/DictionaryBackupAgent﹕ Couldn't read from the cursor
07-29 16:29:55.178 1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:71)
at android.os.Binder.execTransact(Binder.java:446)
07-29 16:29:55.178 1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:64)
at android.os.Binder.execTransact(Binder.java:446)
07-29 16:29:55.178 1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:57)
at android.os.Binder.execTransact(Binder.java:446)
I have no idea why this happen...
I tried to comment hte txtStatus.setText as normally it's not supposed to work from another thread, but no change.
Tested on android emulator with framework 22 and on my phone with framework 21.
Any idea would be welcome
Ok I manage to make it work using threads instead, here's final code:
public void getXMLData()
{
if (skipUpdate)
{
skipUpdate=false;
return;
}
skipUpdate=true;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int SERVERPORT=0;
try {
SERVERPORT = Integer.parseInt(prefs.getString("pref_key_port_1","Port"));
} catch (NumberFormatException e) {
txtStatus.setText("Invalid Port Number");
return;
}
String SERVERHOST = prefs.getString("pref_key_host_1","127.0.0.1");
String PASSWORD = prefs.getString("pref_key_pass_1", "password");
try {
// XMLFetcherTask myXMLFetcherTask = new XMLFetcherTask(SERVERHOST,SERVERPORT,PASSWORD);
// myXMLFetcherTask.execute();
XMLFetcherTask XMLFetcherTaskThread = new XMLFetcherTask();
XMLFetcherTaskThread.dstAddress=SERVERHOST;
XMLFetcherTaskThread.dstPort=SERVERPORT;
XMLFetcherTaskThread.password=PASSWORD;
Thread cThread = new Thread(XMLFetcherTaskThread);
cThread.start();
} catch (Exception e) {
txtStatus.setText("Error "+e.getMessage());
return;
}
skipUpdate=false;
}
public class XMLFetcherTask implements Runnable {
String dstAddress;
int dstPort;
String response = "";
String password="";
private void setStatusFromThread(final String status)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
setStatus(status);
}
});
}
private void updateListenersThread()
{
runOnUiThread(new Runnable() {
#Override
public void run() {
updateFragmentListeners();
}
});
}
public void run() {
Socket socket = null;
//BufferedReader input = null;
//PrintWriter out = null;
try {
socket = new Socket(dstAddress, dstPort);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(password);
response="";
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (response.toLowerCase().indexOf("</response>") < 0) {
response+=input.readLine();
}
if( !(response.substring(0,5).equalsIgnoreCase("<resp") || response.substring(0,5).equalsIgnoreCase("<?xml")) ) //!response.substring(0,5).equalsIgnoreCase("<?xml") ||
{
setStatusFromThread("Server response doesn't look XML, please check password: '" + response.substring(0, 5) + "'");
} else {
lastXMLData=response;
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
setStatusFromThread("Last update: " + ft.format(dNow));
skipUpdate=false;
updateListenersThread();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
setStatusFromThread("UnknownHostException: " + e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
setStatusFromThread("IOException: " + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
setStatusFromThread("Exception: " + e.getMessage());
} finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//txtStatus.setText("Exception Finally: " + e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
}
}
I am developing one Android Application in which I have to send location data on server and getting job data as a response in this way all communication is build but i am stuck of my mind on one thing when i trying to read the response from server the no any output and no any response is coming so please help me out of this stuck. Below is my code. Thanks in advance.
public static class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String s;
String red;
String loc;
String msg;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
InputStream is=null;
BufferedReader br=null;
public MyClientTask(String addr, int port,String msg){
dstAddress = addr;
dstPort = port;
loc=msg;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket(dstAddress, dstPort);
socket.setKeepAlive(true);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
is=socket.getInputStream();
socket.setSoTimeout(60*1000);
dataInputStream = new DataInputStream(is);
Log.i("socket connect","socket OK");
dataOutputStream.writeUTF(loc);
while (dataInputStream == null)
{
////this part is not working
Log.i("DEV", "sleep "+is.available());
android.os.SystemClock.sleep(100);
}
br=new BufferedReader(new InputStreamReader(dataInputStream));
String st = null;
while(socket.isConnected()){
st = br.readLine();
}
Log.w("server response", "says Server = " + st);
Dbase db2=new Dbase(mcontext);
db2.addresponse(new info(st));
Log.w("second time server response", "says 2ndTime Server = " + st);
} catch (UnknownHostException e) {
Log.e("at exception", "at thread unknownHost " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.e("io exception", "at thread IO " + e.getMessage());
e.printStackTrace();
}
finally{
Log.i("on finally block", "finally");
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
Log.e("io eception", "at thread dataoutput IO " + e.getMessage());
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
Log.e("data input exception", "at thread datainput IO " + e.getMessage());
e.printStackTrace();
}
}
if (socket != null){
try {
Log.i("socket", "socket closed");
socket.close();
} catch (IOException e) {
Log.e("socket exception", "at thread finally IO " + e.getMessage());
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//displayProgressBar("Downloading...");
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
You use InputStream.available method incorrectly. This method will not try to retrieve data. Actually most implementations of this method always return 0. See Inputstream available reference.
I recommend you just remove available checks and let readLine block as needed. The same goes for BufferedReader.ready - generally this does not show that you will get any data when attempting to read so this call is also not useful.
I'm working on file sharing using Asmack and XMPP. I am able to send file but not able to receive file on another device. I did so much of Research and Development, found so many ways tried all of them but haven't got success. Seems I am making any small mistake, tried a lot but haven't got solution for my problem. The code I used for sending file is:
d.findViewById(R.id.btnsendphoto).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!filepath.equals("")) {
configureProviderManager(connection);
FileTransferNegotiator.IBB_ONLY = true;
FileTransferNegotiator.setServiceEnabled(
connection, true);
mFileTransferManager = new FileTransferManager(
connection);
String to = connection.getRoster()
.getPresence("cac6ba9dc9c6ac67#pc")
.getFrom();
final OutgoingFileTransfer transfer = mFileTransferManager
.createOutgoingFileTransfer(to);
File file = new File(filepath);
try {
configureProviderManager(connection);
transfer.sendFile(file, "test_file");
} catch (XMPPException e) {
e.printStackTrace();
}
new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
}
#Override
protected Void doInBackground(
Void... params) {
while (!transfer.isDone()) {
if (transfer.getStatus().equals(
"Error")) {
Log.d("file transfer",
"ERROR!!! "
+ transfer
.getError());
} else if (transfer.getStatus()
.equals("Cancelled")
|| transfer.getStatus()
.equals("Refused")) {
Log.d("file transfer",
"Cancelled!!! "
+ transfer
.getError());
}
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
};
protected void onPostExecute(Void result) {
if (transfer.getStatus().equals(
"Refused")
|| transfer.getStatus().equals(
"Error")
|| transfer.getStatus().equals(
"Cancelled")) {
Log.i("file transfer",
"refused cancelled error "
+ transfer
.getError());
} else {
Log.i("file transfer", "Success: "
+ transfer.getFileName());
messages.add("file sent");
setListAdapter();
}
};
}.execute();
}
d.dismiss();
}
});
I am able to send file. I got this message file sent on sending side, here configureProviderManager is this
and I have tried many ways that I got on Google but I would like to mention one of those here
First is:
public void ReceiveFile() {
System.out.println("in ReceiveFile");
Thread thread = new Thread() {
public void run() {
System.out.println("in Thread");
configureProviderManager(connection);
// Create the file transfer manager
final FileTransferManager managerListner = new FileTransferManager(
connection);
FileTransferNegotiator.setServiceEnabled(connection, true);
Log.i("File transfere manager", "created");
// Create the listener
managerListner
.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(
final FileTransferRequest request) {
Log.i("Recieve File",
"new file transfere request");
Log.i("file request",
"from" + request.getRequestor());
IncomingFileTransfer transfer = request
.accept();
Log.i("Recieve File alert dialog", "accepted");
try {
transfer.recieveFile(new File("/sdcard/"
+ request.getFileName()));
while (!transfer.isDone()
|| (transfer.getProgress() < 1)) {
Thread.sleep(1000);
Log.i("Recieve File alert dialog",
"still receiving : "
+ (transfer
.getProgress())
+ " status "
+ transfer.getStatus());
if (transfer.getStatus().equals(
Status.error)) {
// Log.i("Error file",
// transfer.getError().getMessage());
Log.i("Recieve File alert dialog",
"cancelling still receiving : "
+ (transfer
.getProgress())
+ " status "
+ transfer
.getStatus());
transfer.cancel();
break;
}
}
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
};
thread.start();
}
Debugging this code
I am not even getting this log new file transfer request. Kindly please tell what mistake I am making and how can I correct this.
I am sending image using Socket Server and Client. It gived me dialog "App not responding" i think beacuse converting this bitmap was making in UiThread. So i tried to change it but i am still getting this message "App is not responding". It's happening when i am sending big imaes +500kb.
Here is my code for Server:
public class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
while (true) {
Socket socket = serverSocket.accept();
count++;
// Here where i am doing my code i think is not doing in UiThread..
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run()
{
// Firstly i was doing my code here...
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My code for client:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try
{
//I am sending my image here...
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
}
So please help my . Why still i am getting not responding dialog?
The ANR error code happens when you block the UI thread more than 5 seconds. If you need to do background work don't use the main thread. Receive the data in a separate thread and post only the result to the UI thread.