I have a problem because when I have my server offline the Android application tries to connect with the server and it crashes.
I think the solution can be to put an exception inside doInBackground into catch or check in onCreate if the server is offline or online with some function.
What is the best way to do this?
Thanks
You can try this
#Override
protected String doInBackground(String... strings) {
try {
menuString = getStringFromURL(strings[0]);
} catch (Exception e) {
Toast.makeText(this,"Error Connecting to server",Toast.LENGTH_SHORT).show();
return null;
}
return menuString;
}
Related
When I connect to MySQL in android:
code show as below
protected static void connMysql(){
Connection conn = null;
PreparedStatement pstm = null;
ResultSet res = null;
String openurl_mysql="jdbc:mysql://10.15.26.21:3306/etrack_user&autoReconnect=true&failOverReadOnly=false";
try {
java.sql.Driver.class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(openurl_mysql,"etrack","_etrack_mysql_");
pstm = conn.prepareStatement("select count(*) as count from et_patrol_task");
res = pstm.executeQuery();
while(res.next()){
int count = res.getInt("count");
System.out.println("return success=============="+count);
}
res.close();
pstm.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
When I run the program,I get the following problem:enter image description here
Has anyone encountered a similar problem or solved it?
You can't access a MySQL DB from Android natively.Actually you may be able to use JDBC, but it is not recommended.
JDBC is infrequently used on Android, and I certainly would not recommend it.
IMHO, JDBC is designed for high-bandwidth, low-latency, highly-reliable network connections (e.g., desktop to database server, Web application server to database server). Mobile devices offer little of these, and none of them consistently.
I made android application that connects to remote server and send some data.
Remote server is Windows application.
Connection method:
private void ConnectToMonitor() {
try {
s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This works perfectly if server is online. Application is sending data and server is receiving. But if server is offline android app. is blocked. My question is how to handle this? How to continue with application and avoid error even the server is down?
Remember to call this outside the UIThread.
Follow this tutorial. In android all connections need to be managed outside the UIThread, in the tutorial I linked you will find easy ways to post your results back to the UI (handlers, asynctasks...)
Of course we don't know if the problem is about the thread with just the given code, but it is the most usual error.
First remember to set the socket timeout :
mSocket.setSoTimeout(timeout); //in milliseconds
You can however specify different timeout for connection and for all other I/O operations through the socket:
private void connectToMonitor() {
try {
socket = new Socket();
InetAddress[] iNetAddress = InetAddress.getAllByName(SERVER_ADDRESS);
SocketAddress address = new InetSocketAddress(iNetAddress[0], TCP_SERVER_PORT);
socket.setSoTimeout(10000); //timeout for all other I/O operations, 10s for example
socket.connect(address, 20000); //timeout for attempting connection, 20 s
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Second, in Android, you should perform any network I/O in separate threads!
As an example, using regular Java Threads :
String threadName = getClass().getName() + "::connect";
new Thread(new Runnable() {
#Override
public void run() {
connectToMonitor();
}
}, threadName).start();
You can set A timeout for the socket. Use Socket.setSoTimeout method
socket.setSoTimeout(timesinmilis);
by using this your socket will throw a socket timout exception. You can catch that and do what you want
Im having some trouble reading/writing to a tcp server for which im building an app. In a recent thread I was suggested to use a service instead but this is a project for school which suggested asyncTask so I might aswell go for that.
So the classes ive got are my activity class and async, nothing interesting is going on in activity but sending a string which is working so ill get on with the async one.
class ServerTask extends AsyncTask<Void, Void, Void>{
public static String ip = "10.0.2.2";
public static int port = 2002;
Socket socket;
public DataInputStream dis;
public DataOutputStream dos;
public String message;
#Override
protected Void doInBackground(Void... params) {
try {
socket = new Socket(ip, port);
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
} catch (Exception e) {
Log.i("AsyncTank", "Cannot create Socket");
}
while(socket.isConnected()){
read();
}
}
}
return null;
}
public void write(String message) {
try {
if (socket.isConnected()){
dos.writeUTF(message);
dos.flush();
} else {
Log.i("AsynkTask", "Socket appears to be closed");
}
} catch (Exception e) {
Log.i("AsynkTask", "Writing failed");
}
}
public String read() {
try {
if (socket.isConnected()) {
message = dis.readLine();
} else {
Log.i("AsyncTask", "Cannot read");
}
} catch (Exception e) {
Log.i("AsyncTask", "Cannot read from stream");
}
return message;
}
}
Things I do know, the server DOES get the messages but it doesnt update until I restart the server which leads me to believe that im not pushing a new line or something which makes it all appear as one line after its closed. This however might aswell be the server for which im not reponsible so ill have to read up in that.
The read part however does not want to work, im not sure on how to call the method to have it constantly listen and react to the servers sockt? I tried make a thread just before the return in doInBackGround but then the application starts works for a couple of seconds the force closes due to lack of memory? Do I need a thread to keep constantly listen?
The whole point of this as you might guess is to make a chat so the read method is eventually supposed to update a textView in my activity class. The send method is "working" but not as it should though this might be as I said earlier the server doing some funky buisness.
Another one, is it even possible to have the read as a method like I have or does something have to react when the server sends data and then call the method?
Edit
I have now moved the read part, or atleast some of it to doInBackGround so its now
dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
message = dis.readLine();
Log.i("AsynkTask", "Read : "+message+" this is doInBackGround!");
This along with a change to simply hardcode a printline in the server made me read that line in the client so im guessing its working realtively good for now.
How is it looking? Is it utter crap this code and should be done some other way? Got my functionality but never bad to learn to do it better so to speak :).
You should do both your writing and reading to the Socket in an AsyncTask's doInBackground() method, as both take time and could block the main (UI) thread. I don't know how you are calling your write() method above but you might also want to take a look at this question that might be related.
I am working with Android Facebook SDK and wanted to get a friends list. I have created an "AsyncTask" for doing such a thing. I am pasting my doInBackgroundMethod here.
#Override
protected String doInBackground(String... url) {
String jsonResponse;
try {
jsonResponse = Factory.getFacebook().request(Utils.LOGGEDIN_USER_FRIENDS);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return jsonResponse;
}
Utils Code
public static final String LOGGEDIN_USER_FRIENDS = "me/friends";
The problem I am running in to is that it is returning an empty jsonResponse for the first time the application runs. When I open my app the second time I am getting the JsonResponse. But for the first time however I am getting empty jsonResponse.
Can any one help me out in this regard.
Well it was easy... It was messed up by creating a String variable in a Factory. Later on, the same day I saw that, and called the AsyncTask built in method get which provides the result in the same thread.
I want to implement a feature that will ping an address of web service and if it returns true then the application will run through web services otherwise it will use the database of the device (sqlite).
I wrote the code,
public boolean lookfunc()
{
String name1=name;
boolean reachable=false;
try {
InetAddress address = InetAddress.getByName("192.168.1.56");
reachable = address.isReachable(3000);
System.out.println("address.isReachable(3000)"+reachable);
}
catch (UnknownHostException e){
System.err.println("Unable to lookup ");
}
catch (IOException e){
System.err.println("Unable to reach ");
}
catch(Exception e1){System.out.println("Exception raised");}
return reachable;
}
The address 192.168.1.56 is pinging in command prompt but here in code it always return false.
And web service url is : http://192.168.1.56:8080/WIP/services/ConnectionDAO?wsdl, here also this throwing UnknownHostException.
I don't see a point in pinging. Try to download from the web service, and use the database if that fails.