I make a android application connect to server by using "com.mysql.jdbc.Driver".
I make a class for creating a connection as a AsyncTask.
public class MySqlConnection extends AsyncTask<Integer, Integer, Connection>{
protected void onPreExecute() {
//
}
protected Connection doInBackground(Integer... integers) {
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://"+ip+"/"+db_name+"?user="+username+"&password="+password);
return con;
}
protected void onPostExecute(Connection connection) {
delegate.setConnection(connection);
}
}
This class is called in OnCreate().
protected void onCreate(Bundle savedInstanceState) {
MySqlConnection sqlConnection = new MySqlConnection(MainActivity.this,utils.getConnection(),ip, dbname, user, password, new ConnectionResult() {
#Override
public void setConnection(Connection con) {
//set to static connection.
}
}
sqlConnection.execute(1);
}
It can work if a device can connect to server as initial.
But if I try to turn off Wifi, it cannot to re-connect by itself.
Client must restart the application for make it call OnCreate() again.
How to make it re-connection to server all the time?
Related
I have some trouble with my Android app when it connect with other application, I use TCP protocol to communication between them. In my Android app, I try to receive message from other application and then I use Line Chart to visualize that data. At the first time, I connect my Android app with that application, It still receive message and still visualize in Line chart but when I turn off WIFI and turn it on and try to reconnect it but my Android app do not receive anymore.
This is my receive code :
private static class ReceiveMessage extends AsyncTask<Void, Void, Void> {
private String mess;
private IMessageListener listener;
private static ReceiveMessage _instance;
public static ReceiveMessage getInstance() {
if (_instance==null) {
_instance = new ReceiveMessage();
_instance.execute();
}
return _instance;
}
public void subscribe(IMessageListener listener) {
this.listener = listener;
}
#Override
protected Void doInBackground(Void... voids) {
do {
try {
inputStreamReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
mess = bufferedReader.readLine();
listener.messageReceived(mess);
} catch(IOException e){
e.printStackTrace();
}
}while(socket.isConnected());
return null;
}
}
Thank for your help.
i'm trying to connect my android app to mysql database with JDBC , but i keep getting this exception when i test the app in a real device and i really can't figure it out
i have tried to create a new user in XAMPP and granting all privileges to the user , but none of that worked out
could somebody help me with that please, i'm really blocked ?
My activity code :
public class SuccessActivity extends AppCompatActivity {
public static final String url="jdbc:mysql://192.148.2.114:3306/gtransport";
public static final String user="root";
public static final String pass="a123";
TextView EmailShow;
TextView Etat;
String EmailHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_success);
EmailShow = (TextView)findViewById(R.id.email_textview);
Etat=(TextView)findViewById(R.id.etat_textview);
Intent intent = getIntent();
EmailHolder = intent.getStringExtra(MainActivity.USER_NAME);
EmailShow.setText(EmailHolder);
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void,Void,Void>{
private String V_etat="";
#Override
protected Void doInBackground(Void... voids) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con= DriverManager.getConnection(url,user,pass);
String sql="select * from Chauffeur where email=?";
PreparedStatement stmt=con.prepareStatement(sql);
stmt.setString(1,EmailHolder);
ResultSet rs=stmt.executeQuery();
while(rs.next()) {
V_etat = (rs.getString("nom"));
}
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Etat.setText(V_etat);
super.onPostExecute(aVoid);
}
}
}
here's my users table in xampp :
i resolved my problem !
i figured out that when i was creating the user i typed the password by myself,and at the same time i forgot and clicked on "generate password button" which generates an automatic password for u .
so anyone who is facing similar problem pay attention to that while creating a new user !
I don't know what happen with my source code about Socket in Android, when I use method
.isConnected()
My app always force close. And here my source code
public class MyActivity extends Activity {
private String IP;
private int PORT;
private Socket socket;
private PrintWriter printWriter;
private TextView text;
private EditText fieldIp;
private EditText fieldPort;
private Button connect;
private FrameLayout frameIP;
private String message;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
frameIP = (FrameLayout)findViewById(R.id.frameIP);
connect = (Button)findViewById(R.id.connect);
fieldIp = (EditText)findViewById(R.id.ip);
fieldPort = (EditText)findViewById(R.id.port);
text = (TextView)findViewById(R.id.keterangan);
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IP = fieldIp.getText().toString();
PORT = Integer.parseInt(fieldPort.getText().toString());
SocketConnect socketConnect = new SocketConnect(IP,PORT);
socketConnect.execute();
}
});
}
private class SocketConnect extends AsyncTask<Void, Void, Boolean> {
String ip;
int port;
public SocketConnect(String a, int b){
this.ip = a;
this.port = b;
}
#Override
protected Boolean doInBackground(Void... params) {
try {
socket = new Socket();
socket.connect(new InetSocketAddress(ip,port));
if(socket.isConnected())
{
text.setText("Connected!");
}
else
{
text.setText("Failed to connect!");
}
} catch (IOException e) {
Log.e("MyActivity",e.getMessage());
}
finally {
startActivity(new Intent(getApplicationContext(),ListViewText.class));
}
return null;
}
}
}
And I use this in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
I hope you can help me guys :(
Change the doInBackground method as follows...
#Override
protected Boolean doInBackground(Void... params) {
boolean success = true;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(ip, port));
} catch (Exception e) {
success = false;
Log.e("MyActivity", e.getMessage());
}
return success;
}
Then add an onPostExecute method...
#Override
protected void onPostExecute(boolean result) {
if(result) {
text.setText("Connected!");
startActivity(new Intent(MyActivity.this, ListViewText.class));
}
else {
text.setText("Failed to connect!");
}
}
First thing you are calling UI operation outside of UI thread (that is why AsyncTask was created, to handle background job only in doInBackground) So problem about displaying text un TextView is solved...
But more important thing:
Never open Socket in AsyncTask. On Android developer site you can find following:
If you need to keep threads running for long periods of time, it is
highly recommended you use the various APIs provided by the
java.util.concurrent package such as Executor, ThreadPoolExecutor and
FutureTask.)
And that is exactly what you want to do. So use Service, Thread or those mentioned above instead.
I'm using asynctask to make connection between client (runnning on my android device) and server(running on my pc). When i launch the app i have to click on button to connect them, and my server pc program should show me in console device if client is connected but doesn't appear; my android client doesn't connect to my pc server.
Android client:
public class MainActivity extends ActionBarActivity {
Button send;
EditText txt;
TextView testo;
String response = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send = (Button) findViewById(R.id.send);
//txt = (EditText) findViewById(R.id.editText);
testo = (TextView) findViewById(R.id.textView1);
}
class AddStringTask extends AsyncTask<Void, String, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... unused) {
try {
Socket socketClient = new Socket("10.10.0.151",4321); //ipaddress of my pc server
} catch (UnknownHostException e) {
e.printStackTrace();
response = e.toString();
} catch (IOException e) {
e.printStackTrace();
response = e.toString();
}
testo.setText(response);
return (null);
}
#SuppressWarnings("unchecked")
#Override
protected void onProgressUpdate(String... item) {
}
#Override
protected void onPostExecute(Void unused) {
testo.setText(response);
}
}
public void buttonClick(View v){
new AddStringTask().execute();
}
}
Pc server:
public class Server {
public static Socket connection;
public static void main(String[] args) throws IOException {
System.out.println("Starting server on port number: 4321...");
ServerSocket server = new ServerSocket(4321);
while(true){
System.out.println("Waiting for clients...");
connection = server.accept();
System.out.println("Connected to: "+connection.getInetAddress().getHostAddress());
connection.close();
}
}
}
In my AndroidManifest.xml i've just added
<uses-permission android:name="android.permission.INTERNET"/>
If i launch client from pc in my server console i see the device connected but on android doesn't work..why?
Thanks
It's most likely the ip in the android side is wrong. use a private ip eg: 192.168.1.x. theese types of ip require you be on the same network. i think what you're trying to do is access the server from outside of the network and that requires port fkrwarding.
I'm trying to develop an android app with remote access functions. I have been searching similar posts about how remote desktop is made and what is the most efficient method, but i haven't found too mutch information about this.
Now i'm trying to send screenshots and display each one on a ImageView. It works, but the ImageView doesn't get refreshed until the app has ended. I tried to use postInvalidate() and invalidate() on an AsyncTask, but it didn't work.
I'd also like to know if there is a better way (or even different ways) to develop a remote desktop app. I wanna do it by myself, so i don't want to use any app as TeamViewer or similar.
Thanks for the help. Here is my code:
Client
public class MainActivity extends Activity {
static Button boton;
static byte[] imagen;
static ImageView imagenVista;
static Bitmap bmp;
static Socket clientSocket;
static OutputStream os;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boton = (Button)findViewById(R.id.button1);
boton.setOnClickListener(evento);
imagenVista = (ImageView)findViewById(R.id.imageView1);
}
private OnClickListener evento = new OnClickListener() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onClick(View v) {
if (boton.getText().equals("Start")){
boton.setText("Stop");
try{
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
while(true){
Socket clientSocket= new Socket();
InetSocketAddress addr=new InetSocketAddress("10.209.0.93", 5555);
clientSocket.connect(addr);
OutputStream os=clientSocket.getOutputStream();
os.write("capture".getBytes());
ObjectInputStream entrada = new ObjectInputStream(clientSocket.getInputStream());
construyendo_img(entrada)
new TareaSegundoPlano().doInBackground(entrada);
entrada.close();
os.flush();
clientSocket.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
else{
boton.setText("Start");
}
}
};
public void construyendo_img(ObjectInputStream entrada)throws IOException, ClassNotFoundException{
byte[] bytes_img = (byte[]) entrada.readObject();
ByteArrayInputStream entrada_img = new ByteArrayInputStream(bytes_img);
bmp = BitmapFactory.decodeByteArray(bytes_img, 0, bytes_img.length);
imagenVista.setImageBitmap(bmp);
}
public class TareaSegundoPlano extends AsyncTask<Void, ObjectInputStream, Void>{
protected void onPreExecute(){}
protected Void doInBackground(ObjectInputStream... params) {
imagenVista.invalidate();
return null;
}
protected void onProgressUpdate(Void... values) {}
protected void onPostExecute(Void result){}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
}
}