I need to make a mysql connection and get some data back. I can do this in Java using this code
try{
String username;
String password;
username = tf.getText();
password = tf2.getText();
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://188.181.248.30:3306/test","simon","123");
int counter = 0;
try{
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM KUNDER");
// System.out.println("NAVN: " + "\t" + "KREDIT: ");
while (res.next() && counter ==0) {
String i = res.getString("NAVN");
String s = res.getString("KREDIT");
System.out.println(i + "\t\t" + s);
if(username.equals(i)){
//stf3.setText("login true");
// System.out.println("username og navn passer sammen et sted");
if(password.equals(s)){
tf3.setText("login true1");
// System.out.println("pass og navn passer sammen");
counter=10;
}else{
tf3.setText("login fail");
counter =10;
}
}else{
//tf3.setText("login fail");
}
}
con.close();
}
catch (SQLException s){
tf3.setText("sql fail");
System.out.println("SQL code does not execute.");
}
But when I try to do this in Android, I get an error when trying to launch the app saying:
[2011-03-06 00:30:04 - sqlLite] Conversion to Dalvik format failed with error 1
I don't know what to do right now. I been reading around the net, but can't find anything I can get working.
Do not access MySQL from Android via JDBC. Wrap your MySQL database in a Web service, and access the Web service from Android.
You might also want to read: Why is the paradigm of "Direct Database Connection" not welcomed by Android Platform?
Related
I am using Unity for the first time.
I am making a app to work on Android platform.
I made a script to add to one button. The interface has a text input field to add names of a group. After writing some name and hit one button (adicionar), it should add the name in a text field (named textoGrupo). It would also enabled a second button (named seguinte), that would be disabled since the begining of the script execution. I also have another text field (textoElementoRepetido) that should have text only if the name written is repeated.
It works fine when I tested it in Unity. But when I test it on my Android device it does nothing of what's on the script.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Data;
using Mono.Data.SqliteClient;
using TMPro;
using System.IO;
public class grupo : MonoBehaviour
{
List<string> elementos = new List<string>();
private IDbConnection connection;
private IDbCommand command;
string dbFile;
int idGrupo = 0;
public TMP_InputField input;
public TMP_Text textoGrupo;
public TMP_Text textoElementoRepetido;
public Button seguinte;
// Start is called before the first frame update
IEnumerator Start()
{
// Ligação à base de dados
string filepath = Application.persistentDataPath + "/TVdatabase.db";
if (!File.Exists(filepath))
{
// if it doesn't ->
// open StreamingAssets directory and load the db ->
WWW loadDB = new WWW("jar:file://" + Application.dataPath + "!/assets/TVdatabase.db"); // this is the path to your StreamingAssets in android
while (!loadDB.isDone)
{
yield return new WaitForSeconds(30);
} // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
// then save to Application.persistentDataPath
File.WriteAllBytes(filepath, loadDB.bytes);
}
//open db connection
connection = new SqliteConnection("URI=file:" + filepath);
seguinte.interactable = false;
}
public void AdicionaElemento( )
{
if (input.text != null && input.text != "")
{
string sql;
//se ainda não existirem elementos no grupo, é criado na base de dados um grupo e o seu id é guardado
if (elementos.Count == 0)
{
command = connection.CreateCommand();
connection.Open();
sql = "INSERT INTO Grupo(idAvatar) VALUES(1);";
command.CommandText = sql;
command.ExecuteNonQuery();
sql = "SELECT MAX(idGrupo) FROM GRUPO;";
command.CommandText = sql;
IDataReader reader = command.ExecuteReader();
while (reader.Read())
{
idGrupo = reader.GetInt32(0);
}
connection.Close();
}
string elemento = input.text.ToString();
if (!elementos.Contains(item: elemento))
{
textoElementoRepetido.text = "";
command = connection.CreateCommand();
connection.Open();
sql = "INSERT INTO Elemento(nomeElemento, idGrupo) VALUES('" + elemento + "', " + idGrupo + ");";
command.CommandText = sql;
command.ExecuteNonQuery();
connection.Close();
if (elementos.Count == 0)
{
textoGrupo.text += elemento;
}
else
{
textoGrupo.text += ", " + elemento;
}
elementos.Add(elemento);
seguinte.interactable = true;
input.text = "";
}
else
{
textoElementoRepetido.text = "Essa pessoa já faz parte do teu grupo!";
}
}
else{
seguinte.interactable = false;
}
}
// Update is called once per frame
void Update()
{
}
}
I hope I wrote enough to understand the purpose of this screen. Here is what I attached to the button adicionar.
If first tried it on the onClick() event. Didn't work. So I tried it on a trigger. Same result.
I have no idea why this works on unity editor but not on my Android device.
When I click the button adicionar with nothing on text input field the script is working. So my guess is the real problem is teh connection with the database.
I missed some steps when making the database connection. I was following this. But it still does not work.
My database file is named TVbatabase.db
I solved it. So I followed the same link that is in my question (this one). I had error, didn't know why. So I downloaded the package in that post. I realised that I did not have all the necessary plugins. I did not know they where necessary. After I imported them it worked.
I'm learning Javamail these days following this website:
http://www.tutorialspoint.com/javamail_api/
I test the sending & added some extra stuff because it was on Android & it worked!
But things have changed completely when I tried to follow receiving email Tutorial which makes me wonder..
Is it possible to make this code :
https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm
works on android but using XML interface?!
You can use the following code:
public static void receiveEmail(String pop3Host, String storeType, user, String password) {
try {
//1) get the session object
Properties properties = new Properties();
properties.put("mail.pop3.host", pop3Host);
Session emailSession = Session.getDefaultInstance(properties);
//2) create the POP3 store object and connect with the pop server
POP3Store emailStore = (POP3Store) emailSession.getStore(storeType);
emailStore.connect(user, password);
//3) create the folder object and open it
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
//4) retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
//5) close the store and folder objects
emailFolder.close(false);
emailStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
call your method passing some parameters:
String host = "pop.gmail.com";//change accordingly
String mailStoreType = "pop3";
String username= "example#gmail.com";
String password= "xxxxx";//change accordingly
receiveEmail(host, mailStoreType, username, password);
Source: Steps for receiving the email using JavaMail API
I'm new and am trying to connect an android application to my oracle db. My current code is throwing the error:
android.os.NetworkOnMainThreadException ...
My connection code is as follows:
public class ConnectOra {
public String driver, url, ip, bd, usr, pass;
public Connection conexion;
public ConnectOra(String ip, String bd, String usr, String pass) {
driver = "oracle.jdbc.driver.OracleDriver";
this.bd = bd;
this.usr = usr;
this.pass = pass;
url = new String("jdbc:oracle:thin:#" + ip + ":1521:" + bd);
try {
Class.forName(driver).newInstance();
conexion = DriverManager.getConnection(url, usr, pass);
// revisan el log para ver que tira....
System.out.println("Conexion a Base de Datos " + bd + " Exitosa");
} catch (Exception exc) {
System.out.println("Error al tratar de abrir la base de Datos "
+ bd + " : " + exc + "ricardo");
}
}
public Connection getConexion() {
return conexion;
}
public Connection CerrarConexion() throws SQLException {
conexion.close();
conexion = null;
return conexion;
}
Well as the error suggests, you cannot do a network connection on the main thread... So put it in a separate thread.
You have to use another thread for network tasks.
I recommend you use AsyncTask.
U should implement AsyncTask and add: to your android mainfest.
Anyway, it's a really bad practice in termns of security made a direct connection from any local client to a remote DB, that model extinguished for very good reasons years ago, in this case, in Android, if u have the apk file, u can decompress it and then decompile the java source files for get the db credentials and gain complete access to the db.
I have a web-service in .NET it's inserting and retrieving data's from database as object's..
I'll copy some part of web-service here..
[WebMethod(Description = "This is used to insert details into sql server")]
public string InsertDetails(DataTable myDetails, string STR1)
{
try
{
foreach (DataRow row in myDetails.Rows)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.InsertQry";
cmd.Parameters.Add(new SqlParameter("#P_no", row["POD_Number"].ToString()));
cmd.Parameters.Add(new SqlParameter("#P_id", STR1));
cmd.Parameters.Add(new SqlParameter("#P_author", Convert.ToInt64(row["P_author"])));
//opening the connection
cmd.Connection = sqlCon;
sqlCon.Open();
int retValue = cmd.ExecuteNonQuery();
sqlCon.Close();
if (retValue == 0)
return "false";
}
return "true";
}
catch (Exception ex)
{
ErrorLogger(ex);
return "false";
}
}
//-----------------------------------------------------------------------------------
[WebMethod(Description = "This is used to get details from sql server")]
public DataSet GetDetails(string STR1)
{
DataSet ds = new DataSet();
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.SelectQryFromDB";
//opening the connection
cmd.Connection = sqlCon;
sqlCon.Open();
ds.DataSetName = "myTbl";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds,"myTbl");
sqlCon.Close();
return ds;
}
catch (Exception ex)
{
ErrorLogger(ex);
ds.DataSetName = "Error";
return ds;
}
}
//----------------------------
Any-one Help me by providing me the details how can i send those data's and retrieve data's in Android..This is my first application so i don't know much??
Please Provide me details so that i can insert and get data's using web-service??
I heard of kSOAP2 and i'm trying to accomplish this by using kSOAP2..
Working in Ksoap can be challenging sometimes. You first need to make sure your webservice is working fine and is giving you the proper result.
If that's done then you can consume the same from Android using ksoap library.
Here are few links that will help solve your problem:
1) How to call a local web service from Android mobile application will help you understand how you need to make a Ksoap call.
2) Inserting data into remote database from Android via ksoap
3) Returning data from server to Android
I want to get first and last name of a google account using gdata library. I have the auth token(I take it from android device - send it to my java servlet- then should add an insert into a mysql db with first, last, display name and provider_uid(provider_uid is the form of https://www.google.com/accounts/o8/id?id=AItOawmyn...)).
I used Contacts feed like this(without success):
public String tryGoogleAuthentication(String auth_token){
ContactsService contactsService = new ContactsService("...");
contactsService.setUserToken(auth_token);
//contactsService.setAuthSubToken(auth_token);
ContactFeed feed = null;
try {
feed = contactsService.getFeed(new URL("https://www.google.com/m8/feeds/contacts/" + "someEmail#gmail.com" + "/full?max-results=10000"), ContactFeed.class);
} catch (IOException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
} catch (ServiceException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
} catch (NullPointerException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
}
if (feed == null)
return "";
String externalId = feed.getId();
Person person = feed.getAuthors().get(0);
String email = person.getEmail();
String name = person.getName();
String nameLang = person.getNameLang();
String extensionLocalName = person.getExtensionLocalName();
String uri = person.getUri();
System.out.println("externalId: " + externalId);
System.out.println("email: " + email);
System.out.println("name: " + name);
System.out.println("nameLang: " + nameLang);
System.out.println("extension local name: " + extensionLocalName);
System.out.println("URI: " + uri);
System.out.println(feed.getSelf().getEntries().get(0).getTitle().getPlainText());
return CONST.STATUS_OK;
}
Also,
System.out.println("ID: " + feed.getSelf().getEntries().get(0).getId());
will output:
ID: http://www.google.com/m8/feeds/contacts/someEmail%40gmail.com/base/c....
but I want something like this:
https://www.google.com/accounts/o8/id?id=AItOawmyn...
I need this to insert into an existing data base.
Please note that I want the info only for the account, not for it's contacts.
Thanks,
Alex
Please see this answer from google groups for resolution. The problem is that I cannot access user profile with the auth_token taken from the android because it's a Client Login token, and Client Login does not have a scope for accessing user's profile. I integrated OAUTH login in android like this and with the token returned, I can access user's profile.
Alex.