Android JDBC : Some issues with using MySql JDBC in Eclipse - java

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.

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

How to use user input to open api JSON [duplicate]

This question already has answers here:
What arguments are passed into AsyncTask<arg1, arg2, arg3>?
(5 answers)
Closed 3 years ago.
I am working on an Android app in which I am making a weather app. The application opens api data from a JSON and displays this information. More specifically it takes the user input of a city or zip code and adds this info to the URL for the API and then executes the URL.
MainActivity.java
package com.shanehampcsci3660.weather;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
//import static com.shanehampcsci3660.weather.GetJsonData.*;
public class MainActivity extends AppCompatActivity
{
public static TextView tempTV, jsonTV;
public EditText cityORZipET;
private Button getWeather;
public String zip, cityOrZip;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempTV = (TextView) findViewById(R.id.tempTV);
jsonTV = (TextView) findViewById(R.id.jsonFeedTV);
cityORZipET = (EditText) findViewById(R.id.cityORZipET);
getWeather = (Button) findViewById(R.id.getWeatherButton);
//cityOrZip = cityORZipET.getText().toString();
getWeather.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
GetJsonData getJsonData = new GetJsonData();
//getJsonData.execute();
cityOrZip = cityORZipET.getText().toString();
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=x");
jsonTV.setText(cityOrZip);
/*if(cityOrZip.equals(""))
{
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=x");
}
else
{
zip = "30528";
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + zip + "&appid=x");
}*/
}
});
}
}
GetJsonData.java
package com.shanehampcsci3660.weather;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class GetJsonData extends AsyncTask<Void, Void, Void>
{
public String data= "", line = "", name = "";
double temp, minTemp, maxTemp;
#Override
protected Void doInBackground(Void... voids)
{
try
{
URL url = new URL("https://api.openweathermap.org/data/2.5/weather?q=30528&appid=id");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while(line != null)
{
line = bufferedReader.readLine();
data = data + line;
}
JSONObject jsonObject = new JSONObject(data);
JSONObject main = jsonObject.getJSONObject("main");
name = jsonObject.getString("name");
temp = main.getDouble("temp");
minTemp = main.getDouble("min_temp");
maxTemp = main.getDouble("max_temp");
/*JSONObject jsonObject = new JSONObject(result);
JSONObject jsonData = new JSONObject(jsonObject.getString("main"));
String weatherInfo = jsonObject.getString("weather");
JSONArray jsonArray = new JSONArray(weatherInfo);
String description, icon, iconURI;
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonData1 = jsonArray.getJSONObject(i);
description = jsonData1.getString("description");
MainActivityController.description.setText(description);
icon = jsonData1.getString("icon");
iconURI = "http://openweathermap.org/img/w/" + icon + ".png";
Picasso.get().load(iconURI).into(MainActivityController.conditionImageView);
}*/
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
//MainActivity.jsonTV.setText(data);
MainActivity.tempTV.setText("City:\t" + name + "\tTemp:\t" + temp);
Log.d("Json Feed", name + "Temp: " + temp);
}
public static void execute(String s) {
}
}
My issue is that no matter where I put...
if(cityOrZip.equals(""))
{
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityOrZip +"&appid=id");
}
else
{
zip = "30528";
getJsonData.execute("https://api.openweathermap.org/data/2.5/weather?q=" + zip + "&appid=id");
}
...It will only show the data of the default Url opened in GetJsonData.java. My question is what am I doing wrong and what should I correct in order to make my app work with the user input like it should.
you are calling an GetJsonData.execute with the url that contains the client data, but it has no code in it. Looking at your current code the zip that the client inputs does not get stored into the worker class.
This is because you always use the same URL in GetJsonData class. According to question What arguments are passed into AsyncTask? your class declaration should look like:
public class GetJsonData extends AsyncTask<String, Void, YourPojo> {
#Override
protected YourPojo doInBackground(String... urls)
{
try
{
URL url = new URL(urls[0]);
...
} catch (Exception e) {
handle(e);
}
}
}
where YourPojo is a class you need to create to store all properties you need to read from JSON payload:
class YourPojo {
private String data;
private String line;
private String name;
private double temp;
private double minTemp
private double maxTemp;
// getters, setters
}

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 Application working on emulator but not on device

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

Categories