Android Question My first my Sql program , having problems connecting to database

hookshy

Well-Known Member
Licensed User
Longtime User
I have set up a mysql data base with this credentials

server
mysql.hostinger.ro

database
u348082479_sql

user
u348082479_hs

pass
m63hunter


created a table that looks in php my admin like this
id nume
1 Gabi
2 Alexandra

Here is the code i am using toghether with MSMysql ver 1.06 and javaobject
I have an error : Null pointer exception in sub MySQL_QueryResult(data As List, meta As Map)

Is the code correct ?
Is the database availlable for reading ? Thank you for your advice

B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
   Dim db As MySQL
    Private lv1 As ListView
    Private lbl1 As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
 
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Layout1")

    'db.Initialize("sql","host.com","dbuser","dbpassword","database")
    db.Initialize("MySQL","mysql.hostinger.ro","u348082479_hs","m63hunter","u348082479_hs")
 
End Sub

Sub Activity_Resume
    Log("Activity_Resume()")
    'db.ListTablesAsync
    'db.queryasync("select * from ufo_trainer LIMIT 0,1 ;")
    db.QueryASync("Select * FROM `newsfeed` LIMIT 0,1;","")'login is the task id

 
 
 
'    Dim batch As List 
'    batch.Initialize
'    For i=1 To 100
'        batch.Add("INSERT INTO b4alog SET log_value='Test"&i&"', log_time="&DateTime.Now&";")
'    Next
 
    'db.ExecuteBatchASync(batch)
    'db.ExecuteASync("INSERT INTO b4alog SET log_value='only one query', log_time="&DateTime.Now&";","") 
 
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub

Sub MySQL_ExecResult(meta As Map)
    Log(meta) 
End Sub
Sub MySQL_BatchResult(batch As Map)
    Log(batch) 
End Sub
Sub MySQL_QueryResult(data As List, meta As Map)

ToastMessageShow("test",True)

'lv1.AddTwoLines("text1","text")



    Dim m As Map = meta
'    Log("MySQL_QueryResult("&meta&")")
'ToastMessageShow(meta.Get("RecordCount") & " rows retrieved in " & meta.Get("ms") & " milliseconds", True)
 
'
'    Dim sb As StringBuilder
'    sb.Initialize
' 
For i=0 To data.Size-1
 
'Log("r:"&data.Get(i))

Dim COL As Map
COL=data.Get(i)

lv1.AddTwoLines(COL.Get("id"),COL.Get("nume"))

Next
 
 


End Sub
Sub MySQL_ListTables(tables As List, ms As Long)
    Log("MySQL_ListTables("&ms&"ms)")
    For i=0 To tables.Size-1
        'Log("Table "&tables.Get(i))
    Next
End Sub

Sub DisableStrictMode
   Dim jo As JavaObject
   jo.InitializeStatic("android.os.Build.VERSION")
   If jo.GetField("SDK_INT") > 9 Then
     Dim policy As JavaObject
     policy = policy.InitializeNewInstance("android.os.StrictMode.ThreadPolicy.Builder", Null)
     policy = policy.RunMethodJO("permitAll", Null).RunMethodJO("build", Null)
     Dim sm As JavaObject
     sm.InitializeStatic("android.os.StrictMode").RunMethod("setThreadPolicy", Array(policy))
   End If
End Sub
 
Last edited:

DonManfred

Expert
Licensed User
Longtime User
Is the database availlable for reading ?
i tried to connect to this database from here but with no success.

Are you sure the database is accessible from outside?
 
Upvote 0

hookshy

Well-Known Member
Licensed User
Longtime User
I am not sure ..and do not understand , I will try to find out more on how to make it availlable

I found a section that makes the database availlable from outside and it asks for the ip of the device that will connect to the database ....!

But it is stupid ...how the hell I am going to build an app for 1000 users that has to connect to this database ?

please advise
 
Last edited:
Upvote 0

apiwatcomscith

Member
Licensed User
Longtime User
i think your host is not allow to connect form out side.
most host database allow connect only localhost

first step try to connect mysql to your pc.
 
Upvote 0

KMatle

Expert
Licensed User
Longtime User
Take a simple php script (with a connect Statement). Providers often have examples how to connect (otherwise see the examples here).

So it is: your app -> www -> your Sever -> php -> local host -> MySql -> Database

By the way it is VERY INSECURE to store the credentials inside the app. With a php script you just call the script with paramaters. All other data can't be seen by others. Her you can check if a device/a user is authorized. Nice and easy.
 
Upvote 0

hookshy

Well-Known Member
Licensed User
Longtime User
Her you can check if a device/a user is authorized. Nice and easy.

It seems that there is something that is very hard to understand since i do not know how database works....
I need the app to allow all users to read or modify the database ..my information is not something that is intended to be broken by somebody

I receive some stange questions by the host service like : Do you want to connect with php myadmin or by a script ...
What the hell phpmyadmin does not work toghether with any other lib that modify the database !
 
Upvote 0

KMatle

Expert
Licensed User
Longtime User
It seems that there is something that is very hard to understand since i do not know how database works....
I need the app to allow all users to read or modify the database ..my information is not something that is intended to be broken by somebody

I receive some stange questions by the host service like : Do you want to connect with php myadmin or by a script ...
What the hell phpmyadmin does not work toghether with any other lib that modify the database !

There must be a tutorial from the hoster how to connect to a database. Are you able to post the link to it. We will try to help then.

A direct connect to the database is not supported

PS: Of course you must secure the db (or do you want me to kill the db by inserting 1 billion rows :) )
 
Last edited:
Upvote 0

hookshy

Well-Known Member
Licensed User
Longtime User
PS: Of course you must secure the db (or do you want me to kill the db by inserting 1 billion rows

I decide how insets rows in the database and how reads the database thanks to b4a and sql lib

I got an answer from provider and is something that I will not live with :
The say : sory we can not allow anybody to have access to MySQl shared

https://cpanel.hostinger.ro/
I am blind .... I got used to libs here from you guys ...I do not know php and will be very hard to do it otherwise

So ...the conclusion is that their MySQL services are just for using a database from personal pc ? :mad:
 
Upvote 0

mangojack

Expert
Licensed User
Longtime User
Can you suggest other services I could use to start working and test the mysql ?

I signed up with Host Papa to trial / test mysql ... https://www.hostpapa.com

Following @KMatle MYSQL examples it was a fairly easy to achieve what your attempting to do .. even learning some basic php along the way.
I am happy with their service although I'm only using basic stuff presently.
for a free service I did try FreeHosting. Com for a while .. but downtime and speed was dreadful.
 
Upvote 0

KMatle

Expert
Licensed User
Longtime User
I will open a free account the next days on hostinger.de and will Report how you can use it.

But... Many providers don't allow you to directly connect to a database (only "from the inside" via php). Relax. Php is very easy. Wait a few days 'till I try what you can do.
 
Upvote 0

KMatle

Expert
Licensed User
Longtime User
Just created an account. It's like all the other providers. I have created a webspace "myname.esy.es"

Here's a working(!) php example (from my tutorials). The table is called "persons" and has 2 culumns (name & age).

Just copy that script to a file "persons.php", add the credentials, create a folder "persons" in "public_html" and upload persons.php to the folder "persons" (all done via "Dashboard" -> Files)

Open a browser and type:

B4X:
http://yoursitename.esy.es/persons/persons.php?action=GetPersons

Same is done by using httputils. See my tutorials (signature).

I tried this with hostinger. No problem.

B4X:
<?php

$host = "mysql.hostinger.de";
$user = "";
$pw = "";
$db = "";

$con = mysqli_connect($host,$user,$pw) or die(mysqli_error());
mysqli_select_db($con,$db) or die(mysqli_error());
mysqli_query($con,"SET CHARACTER SET utf8");
mysqli_query($con,"SET NAMES 'utf8'");

$action = $_GET["action"];
switch ($action)

{
    case "CountPersons":
        $q = mysqli_query($con,"SELECT * FROM persons");
        $count = mysqli_num_rows($q);
        print json_encode($count);
    break;
   
    Case "GetPersons":
        $q = mysqli_query($con,"SELECT name, age FROM persons ORDER BY name");
        $rows = array();
        while($r = mysqli_fetch_assoc($q))
        {
            $rows[] = $r;
        }
        print json_encode($rows);
    break;
   
    case "InsertNewPerson":
        $name = $_GET["name"];
        $age = $_GET["age"];
        $q = mysqli_query($con,"INSERT INTO persons (name, age) VALUES ('$name', $age)");
        print json_encode("Inserted");
    break;
   
    default:
        print "Wrong function!";
       
}

?>
 
Upvote 0

hookshy

Well-Known Member
Licensed User
Longtime User
Just created an account. It's like all the other providers. I have created a webspace "myname.esy.es"

Here's a working(!) php example (from my tutorials). The table is called "persons" and has 2 culumns (name & age).

Just copy that script to a file "persons.php", add the credentials, create a folder "persons" in "public_html" and upload persons.php to the folder "persons" (all done via "Dashboard" -> Files)

Open a browser and type:


I will take a look ...
I did not imagine that I would have to start learning php ... hopeing I will stay focus to b4a:rolleyes:

thanks
 
Upvote 0

milanjo

Member
Licensed User
Longtime User
It's much better to use http utils and sends only data to the php. Php language is quite easy you can learn it from reading of some source codes, w3school, php.net. Another option is if you can buy public ip (your router will be accessible from outside - anywhere from the internet) you can put some server - raspberry pi is good solution it quite cheap and you can host very big databases on it. On your own server you can setup everything as you want and your data is located in your home. You will learn many things if you choose that options. Than you can setup your mysql server to be accessible from outside and use mysql library in your app.
 
Upvote 0
Top