Android Application working on emulator but not on device - java

I created an Android Application that connects to a local MySQL database to retrieve some sample data through JDBC.
When i run the application with the emulator,it works fine and loads the data.
When I run the application from my device,it freezes on loading the data,without errors from the logcat.
Here's the code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
Button bottone;
boolean connected = false;
private TextView nome1;
private TextView cognome1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottone = (Button)findViewById(R.id.button1);
bottone.setOnClickListener(this);
nome1 = (TextView) findViewById(R.id.text_name);
cognome1 = (TextView) findViewById(R.id.text_surname);
}
class ConnectAsync extends AsyncTask<String, Void, String> {
private String name;
private String surname;
private ProgressDialog myProgress;
#Override
protected void onPreExecute()
{
super.onPreExecute();
myProgress = ProgressDialog.show(MainActivity.this, "Wait", "Loading..");
}
#Override
protected String doInBackground(String... urls) {
String url = "jdbc:mysql://192.168.56.1/prova";
String user = "myuser";
String password = "mypsw";
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url,user,password);
} catch (ClassNotFoundException e) {
System.out.println("Driver non caricato");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Errore con url e credenziali!");
}
if(connection!= null)
{System.out.println("Connessione riuscita!");
connected = true;}
ResultSet rs = null;
try {
Statement stmt = connection.createStatement();
String sql = "SELECT NOME,COGNOME FROM amici";
rs = stmt.executeQuery(sql);
if(!rs.next())
{System.out.println("Vuota");}
else
{
do{
name = rs.getString("NOME");
surname = rs.getString("COGNOME");
}while(rs.next());}
} catch (SQLException e) {
System.out.println("Query error");
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(connected)
return "Connessione riuscita";
else return "Connessione non riuscita";
}
#Override
protected void onPostExecute(String result)
{ myProgress.dismiss();
if(result.equals("Connessione riuscita"))
{Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
nome1.setText(name);
cognome1.setText(surname);}
else
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
}
public void connectToDB(View view)
{
ConnectAsync task = new ConnectAsync();
task.execute();}
#Override
public void onClick(View v) {
connectToDB(v);
}
}
The IP address i used in the JDBC string is the one i got typing "ipconfig" in windows cmd (IPv4).
The app simply shows a progress dialog until the connection is up,and then retrieves the data from the database putting it into two textviews.
As i said,when i try to connect using the Android Emulator it connects and runs fine,but when i run the application on my Device the application freezes at getting connection (progress dialog keeps loading) and no errors are given in the logcat.
I checked the minimum SDK required,and it matches with my phone Android version.
I think it's something related to the way MySQL database handles the connection requests from the emulator and from the device...any help is appreciated,thanks.
P.S: MySQL configuration file (my.ini) has the following parameters:
....
[mysqld]
bind-address= *
# skip-networking
...
...
wait_timeout = 30
interactive_timeout = 30
connect_timeout = 30

Related

Cannot get Android Studio to connect to a MySQL database

I cannot get my Android app (basic just tutorial style app) to connect to my MySQL database. I can get a basic IntelliJ IDEA program with essentially the same code to connect and display a list of names, but my android app just throws com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure.
When I look at the server logs in MySQL Workbench, the result is Access denied for user '(myname)'#'localhost' (using password: NO).
The weird thing is that when I check the log after I connect using my java program on IntelliJ, the logs show the same thing, several reconnect attempts, then Aborted connection 458 to db: 'mydb' user: 'root' host: 'localhost' (Got an error reading communication packets), then the same Access denied... message, but the names DO print out to the terminal in the IntelliJ app.
I created a user of my username on my Mac account I am using and nothing really matters. Same message. Any idea where I should go?
Here is the Android Studio Code:
package com.addydevelopments.sqlllllll;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
TextView text, errorText;
Button show;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView2);
errorText = (TextView) findViewById(R.id.textView3);
show = (Button) findViewById(R.id.button);
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Task().execute();
}
});
}
public class Task extends AsyncTask<Void, Void, Void> {
String records="", error="";
String url = "jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT";
String user = "root";
String password = "student";
#Override
protected Void doInBackground(Void... voids) {
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try{
Connection conn = DriverManager.getConnection(url, user, password);
Statement stat = conn.createStatement();
String sql = "SELECT * from mydb.fruit";
ResultSet rs = stat.executeQuery(sql);
while(rs.next()){
records += rs.getString("name") + "/n";
}
}
catch(Exception e){
error = e.toString();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
text.setText(records);
if(error != ""){
errorText.setText(error);
}
super.onPostExecute(aVoid);
}
}
}
And here is the IntelliJ IDEA version:
package com.addydevelopments.Dahls;
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=GMT";
String user = "root";
String password = "student";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
Connection myConn = DriverManager.getConnection(url, user, password);
Statement myState = myConn.createStatement();
String sql = "SELECT * from mydb.fruit";
ResultSet rs = myState.executeQuery(sql);
while (rs.next()){
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Your code connects to a local sql server. There is not one running on your Android phone whilst I assume there is one running on your computer. You can use httpurlconnection to talk to your external web server and use php/sql on the server side. Just a note if the server doesn’t have a valid ssl certificate it may not work.
https://developer.android.com/reference/java/net/HttpURLConnection

I'm trying to create Log in using localhost

I want to create an survey application, but it stuck on if (con == null) {z = "Please check your internet connection"; i have searched on google, and i am a newbie in java, i know this means that the application is not yet connected to the connection but i don't know where i did wrong
this is Connectionclass.java for connecting to the localhost
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
#SuppressLint("NewAPI")
public Connection Conn() {
String kelas = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://10.0.2.2:3306/kartu_tani";
String uname = "";
String password = "";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
try {
Class.forName(kelas).newInstance();
connection = DriverManager.getConnection(url, uname, password);
} catch (ClassNotFoundException e) {
Log.e("ERROR", e.getMessage());
} catch (SQLException e) {
Log.e("ERROR", e.getMessage());
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
return connection;
}
}
and this is the login page
import androidx.appcompat.app.AppCompatActivity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telecom.Call;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.e_survey.Background;
import com.example.e_survey.ConnectionClass;
import com.example.e_survey.Model.ProfilDesa;
import com.example.e_survey.R;
import com.example.e_survey.Util.Constant;
import com.example.e_survey.Util.SharedPreferenceCustom;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import static com.bumptech.glide.request.Request.*;
public class LoginActivity extends AppCompatActivity {
Button btnLogin;
SharedPreferenceCustom sharedPreferenceCustom;
EditText etUsername,etPassword;
ConnectionClass connectionClass;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etUsername = findViewById(R.id.et_username);
etPassword = findViewById(R.id.et_password);
btnLogin = findViewById(R.id.btnLogin);
connectionClass = new ConnectionClass();
progressDialog = new ProgressDialog(this);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLogin doLogin = new doLogin();
doLogin.execute("");
}
});
/*sharedPreferenceCustom = SharedPreferenceCustom.getInstance(this);
initProgresDialog();
initFindView();*/
}
/*private void initProgresDialog() {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please Wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
}*/
private class doLogin extends AsyncTask<String, String, String> {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String z = "";
boolean isSuccess = false;
String un, pw;
#Override
protected void onPreExecute() {
progressDialog.setMessage("Please Wait");
progressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
if (username.trim().equals("")) {
z = "Masukkan Username Anda!";
} else if (password.trim().equals("")) {
z = "Masukkan Password Anda!";
} else {
try {
ConnectionClass db = new ConnectionClass();
Connection con = db.Conn();
if (con == null) {
z = "Please check your internet connection";
} else {
String query = "select * from userlogin where username = '"+ username +"' and password = '"+ password +"'";
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery(query);
while (rs.next()) {
un = rs.getString(1);
pw = rs.getString(2);
if (un.equals(username) && pw.equals(password)) {
isSuccess = true;
z = "Login Successfull";
} else {
isSuccess = false;
}
}
}
} catch (Exception e) {
isSuccess = false;
z = "Exception" + e;
}
}
return z;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(getBaseContext(), "" + z, Toast.LENGTH_LONG).show();
if (isSuccess) {
Intent intent = new Intent(LoginActivity.this, ProfilDesaActivity.class);
startActivity(intent);
}
progressDialog.hide();
}
}
}
thank you

Android studio connecting to remote database

I am trying to get an Android Studio app to connect to a remote server hosted on "hostbuddy". Here is the code (when sending data the error is "Connection goes wrong 2") making me guess there is something wrong with the DB_URL. I tried changing the url in many ways, none worked. If it would help I could also post the logcat.
EDIT : I fixed it, i forgot to add the module for the connector for MySQl, works like a charm now ^_^
package com.example.battl.qr2;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
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 org.w3c.dom.Text;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Register extends AppCompatActivity {
TextView textView;
Button button;
EditText editText;
private static final String DB_URL= "jdbc:mysql://mysql6002.site4now.net/db_a37d85_mydb:3306";
private static final String USER = "X";
private static final String PASS = "X";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
textView=(TextView) findViewById(R.id.textView);
editText=(EditText) findViewById(R.id.editText);
}
public void btnConn(View view)
{
Send objsend = new Send();
objsend.execute("");
}
private class Send extends AsyncTask<String,String,String>
{
String msg = "";
String text = editText.getText().toString();
#Override
protected void onPreExecute() {textView.setText("Please Wait Inserting");}
#Override
protected String doInBackground(String... strings)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
if(conn == null) {
msg="Connection goes wrong";
} else {
String query = "INSERT INTO ex (col1) VALUES ('"+text+"') ";
Statement stmt = conn.createStatement();
stmt.executeUpdate(query);
msg = "Inserted successfully";
}
conn.close();
}
catch (Exception e)
{
msg="Connection goes wrong 2";
e.printStackTrace();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {textView.setText(msg);}
}
}

Android app can't insert data into MySQL DB

I'm fairly new to Android coding and I'm trying to create app that inserts some info into my MySQL DB. I've found a lot of tutorials and tips on web and created lite app to try procedures. Everything compiles OK, app runs and it seems to send data successfully. But in fact, no data appears in my table.
Here's my PHP code android_add.php:
<?php
$con = mysqli_connect(localhost, user, psswd, name); //those works
mysqli_set_charset($con, "utf8"); //working with special symbols
$name = $_POST['name']; //get name & author from App
$author = $_POST['author'];
$sql = "insert into kniha_test (k_autor_pr,k_nazev) values ('$name','$address')";
if(mysqli_query($con,$sql)){
echo 'success';
} else {
echo 'failure';
}
mysqli_close($con);
?>
And here's my MainActivity.java:
import android.content.ContentValues;
import android.os.AsyncTask;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText editTextName;
private EditText editTextAuthor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAuthor = (EditText) findViewById(R.id.editTextAuthor);
}
public void insert (View view){
String name = editTextName.getText().toString();
String author = editTextAuthor.getText().toString();
insertToDatabase(name,author);
}
protected void insertToDatabase(String name, String author){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
String name;
String author;
public void saveNameAut(String name, String author){
this.name = name;
this.author = author;
name = editTextName.getText().toString();
author = editTextAuthor.getText().toString();
}
#Override
protected String doInBackground(String... params){
String paramName = params[0];
String paramAuthor = params[1];
ContentValues values = new ContentValues();
values.put("name", this.name);
values.put("author", this.author);
String addUrl = "http://glaserproject.com/knihovna_kyber/android/android_add.php";
try {URL url = new URL(addUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
System.out.println("Response Code: " + conn.getResponseCode());
} catch (IOException e){};
return "Succes";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, author);
}
}
As I said, I'm just beginner, so there may be something really stupid, but I can't figure out what. And there can be some trash lines from different tries. PHP code should be OK, I'm using practically the same to insert from HTML, so I'm guessing, there is problem in my Java code.
I will be really thankful for advices/responses.
Thanks!
PS: Response code I'm getting is 200.
You are sending null values through AsyncTask
Have you printed the values that you are sending through
try this
protected void insertToDatabase(String name, String author){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
String cName=name;
String cAuthor=author;
#Override
protected String doInBackground(String... params){
ContentValues values = new ContentValues();
values.put("name", cName);
values.put("author", cAuthor);
String addUrl = "http://glaserproject.com/knihovna_kyber/android/android_add.php";
try {URL url = new URL(addUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
System.out.println("Response Code: " + conn.getResponseCode());
} catch (IOException e){};
return "Succes";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, author);
}
try again and let me know if it solves your problems....

Android JDBC : Some issues with using MySql JDBC in Eclipse

I am using Eclipse in Windows and i want to connect to a MySql DB.
I know i should use JDBC. But i don't know how to use it!
I have downloaded both msi and zip file from JDBC download page.
In the zip file, a file with this name exsits : mysql-connector-java-5.1.30-bin.jar
What should i do with this?
I mean where i copy/import (in a folder or in eclipse) this file?
Note that i have this code:
import android.os.Bundle;
import android.app.Activity;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class LearningActivity extends Activity {
private static final String url = "jdbc:mysql://cool/app";
private static final String user = "user";
private static final String pass = "password";
private Button button;
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)this.findViewById(R.id.button1);
tv = (TextView)this.findViewById(R.id.textView1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Connect();
}
});
}
public void Connect() {
Connect task = new Connect();
task.execute();
}
private class Connect extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, pass);
String result = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from users");
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next()) {
result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
result += rsmd.getColumnName(3) + ": " + rs.getString(3) + "\n";
}
tv.setText(result);
}
catch(Exception e) {
e.printStackTrace();
tv.setText(e.toString());
}
return response;
}
#Override
protected void onPostExecute(String result) {
tv.setText(result);
}
}
}
But I get this error : ClassNotFoundException : com.mysql.jdbc.Driver
An offline discussion with #Ali revealed that he was using an old version of the ADT that does not create the libs folder as shown in the folder hierarchy on the android developers web site
Manually creating this folder solved the problem for him.
Note: The name of the folder is libs with a "s" at the end. It is easy to miss that and create lib instead.
I place these in a lib directory inside my eclipse project, then add the jar to my build path.

Categories