loading

Hello everyone

Because app's are being used almost everywhere, I decided to make my own tutorial on how to make an app and connect to a MySQL database hosted on a raspberry pi.

For exchanging the data between the server and the client, I'm going to use JSON.

Step 1: Parts

For this instructables you'll need several things.

  • An android phone or the emulator from android studio
  • A raspberry pi (I tried B and 2B)
  • An internet connection with port 80 forwarded to the IP of your Raspberry Pi (How to forward port 80?)
    you can do it without forwarding, but then it's only going to work inside your network
  • A computer (I'm running windows 8.1. But ,as mentioned in the comments, you can also use mac or linux)

Step 2: Software for the Computers

For this instructables you'll need android studio from Google.

Step 3: Software Raspberry Pi

I'm assuming you already have a running Raspberry Pi with raspbian. Otherwise: How to set up a raspbian?.

For the Raspberry Pi you'll also need software. As server I'm using:

  • Apache 2
  • PHP
  • MySQL
  • PHPMyadmin (Not needed but recommended)

To install apache 2, PHP and MySQL I used this tutorial.
To install PHPmyadmin I used this tutorial.

Step 4: Creating the Database Using Phpmyadmin

First open a web-browser and go to:
IP_RPi/phpmyadmin

Login to phpmyadmin
Click Databases
Create new database: Parts
Press create.

Open the database Parts.
Create new table Parts with 3 fields.
Press Start

First column:

column: ID
Type: INT
Auto increment: v

Second column:
column: Name
Type: VARCHAR
Length: 30

Third column:
column: part_nr
Type: INT

Press Save

Step 5: Server Side Scripting

On the Raspberry Pi we'll need 4 files. You need to place them in the www directory of your raspberry pi:

UPDATE: On raspbian Jessie, you have to put them in /var/www/html

The db_config file is used for storing the username, password and database name
The db_connect file is used to connect to the database specified in the db_config file.
The db_create file is used to create a row in the table in the connected database.
The db_view file is used to get all data stored in the database.

Step 6: Writing an App (Layout)

In this step I'll explain how to make a simple app using android studio.
Here we will make the layout of the app and in the next step I'll explain how to make the app working and how to communicate with the raspberry pi server.

So first start Android Studio.

Give your app a name and choose the directory to place it. Press Next.
Choose which devices you would like to support. I'm using phones starting from android 4.0.3.
After that you need to choose the activity. Choose: "Blank Activity".
Let the last screen as it is.

After all these steps, you get an example "hello world" app.

In activity_main.xml remove the textview element at the right bar.

In values/strings.xml remove:

Hello world!

Go back to main_activity.xml

Drag a linear layout (vertical) to the top left corner of the screen.

Drag 2 text fields to the screen. The first one plaintext and the other one Number.

At the right scroll down untill you see "id".
Change this for the first one to Name and for the second one to part_nr.

At the right scroll down untill you see "hint".
Change this for the first one to Name and for the second one to Part Number.

Now drag a button onto the screen and change "text" to Send.

Now is the layout done.

You can test the app by connecting your phone to your computer and compiling the app.(The green arrow a the top)
This will take a while.

It should look something like the last image.

Up to the coding of the app.

Step 7: Writing an App (Java Code)

For making an app work, you don't only need a layout. You also need the code running in the background.
The language we are going to use is Java, because all android apps are written in Java. So lets start coding.

First of all, you need to download the attached file.
This file is a library so you can easily use JSON.

Place this file in:
directiory/app_name/app/src/main/java/company/app_name/JSONParser.java

For me it's:
C:/Users/Laurens1/Desktop/instructables/Instructables/app/src/main/java/Laurens_wuyts/Instructables/JSONParser.java

After that you can open JSONParser in android studio. You now need to change the first line to:
package company.app_name;

Ok now we can start writing the main code.
Open the file MainActivity.java

First make a new Progress-dialog. This is used to display when the code is executing and you need to wait.

Place this in the main class.
private ProgressDialog pDialog;

Then we need a JSONparser object to send the data. So place this line under the previous line:
JSONParser jsonParser = new JSONParser();

Now we need two EditText items, so we can extrude the inserted text. This goes under the JSONParser.
EditText editText;
EditText editText2;

We move on to the oncreate function. Here we need to link the EditTexts from above with the real edittexts in the layout. You do it like this:
editText = (EditText) findViewById(R.id.Name);
editText2 = (EditText) findViewById(R.id.part_nr);

At the end we need to create a new class for connecting to the server and sending the previous typed info.
This is the class Create_part:

class Create_Part extends AsyncTask {

@Override protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Sending part to the database..."); //Set the message for the loading window
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show(); //Place the loading message on the screen
}

@Override protected String doInBackground(String... args) {

String String_name = editText.getText().toString(); //Get the inserted text from the editText files
String Int_Part = editText2.getText().toString();

List params = new ArrayList<>();
params.add(new BasicNameValuePair("Name", String_name)); //Add the parameters to an array
params.add(new BasicNameValuePair("part_nr", Int_Part));

// Do the HTTP POST Request with the JSON parameters
// Change "RaspberryPi_IP to your home IP address or Noip service

JSONObject json = jsonParser.makeHttpRequest("RaspberryPi_IP/db_create.php", "POST", params);

try {

int success = json.getInt("success");

if(success == 1){

Intent i = new Intent(getApplicationContext(), ConfirmActivity.class);
// Open a new activity to confirm it was sent. We're going to create it later.
startActivity(i);
finish();

}

} catch (JSONException e) {

e.printStackTrace();

}

return null;

}

protected void onPostExecute(String file_url){

pDialog.dismiss(); // Close the loading window when ready

}

}

Now you can make a new function called Send. In this function you call Create_Part. Like so:

public void Send(View view) {

new Create_Part().execute();

}

In the activity_main.xml you now change the onclick action of the button on the right to:
Send

Ok your almost done, now you only need to make a new activity like you see in the image.

Change the activity name to: ConfirmActivity

Click Finish

Now go again to strings.xml and change the "hello_world" string from Hello World! to The part was created.

Now it should be done.

Rebuild the app and test it on your phone!

Step 8: Resume

In this instructables we saw how to make a basic android app and connect it to a php mysql server.

I'm going to make a video for this tutorial, but now I don't have time for it.

If you have questions/remarks please share them and I will see if I can answer them.

Thank you very much for following this instructables.

Laurens Wuyts

P.S. Please be kind, it's my first instructables.

<p>hello sir,</p><p>I am trying to make same project as yours. so do I need to install android studio on raspberrypi? or i can install it on my window desktop?</p>
<p>on your window desktop</p>
<p>gradle doesn't find R.menu.menu_confirm and R.id.action_settings , do you know why ?</p>
<p>hi lauren, may i ask. i read the title &quot;Raspberry Pi Android App communication&quot; so does it means an app in a smartphone can connect to our own built database using r-pi ? based on my understanding an app such as whatsapp can store its chat on our own database. please reply. im interested to this project as my final year project.</p>
<p>Hello,</p><p>This instuctables covers how to connect an <strong>own written</strong> android app with a database stored on you raspberry pi.</p><p>An app which is already written can't connect to it.</p><p>Laurens</p>
<p>In this example you need internet in the raspberry to connect database with android, don't you? </p><p>It is possible comunicate both directly over wifi? As a P2P connection or something like that. </p>
<p>how i communicate android and raspberry over wifi?</p>
<p>Hello, I also need to do this. Do u find something about that ? </p><p>I just find this</p><p> <a href="https://www.raspberrypi.org/forums/viewtopic.php?f=36&t=49420" rel="nofollow">https://www.raspberrypi.org/forums/viewtopic.php?f...</a></p><p>But maybe u have something better.</p>
<p>Hello! When I want to run a script that includes SQL query, I'm getting an error report: &quot;The website is unable to handle this request, (Error 500)&quot;. <br>Is somebody knows the issue?</p>
<p>hello author,</p><p>the app is successfully run, but whenever i click on send button it shows me below error :-</p><p>E/WindowManager: android.view.WindowLeaked: Activity com.relinns.project_pi.MainActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{3b8108f V.E...... R......D 0,0-684,232} that was originally added here</p>
<p>thank you so much </p><p>can i have your email please ?</p><p>i want to ask you some questions , our graduation project are using raspberry with android and we need some help if you can .</p><p>my email : rawan-balubaid@hotmail.com </p>
<p>Thank you, as a novice i appreciated the whole lot of work to do, but i learned a lot. Maybe sharing my pitfalls could help somebody:</p><p>1) In the db_config.php make sure you write &quot;root&quot; as user, the actual password for your database, and &quot;Parts&quot; as database name</p><p>2) to remove a lot of errors in android studio add this to your gradle:</p><pre>android {<br> useLibrary 'org.apache.http.legacy'}</pre><p>3) to make the app connect to network add to AndroidMainfest.xml the permission:</p><pre>&lt;manifestxlmns:android...&gt;<br> ...<br> &lt;uses-permissionandroid:name=&quot;android.permission.INTERNET&quot;/&gt;<br> &lt;application ...<br>&lt;/manifest&gt;</pre>
<p>You helped me a lot! Thank you very much!<br>I just don't understand what I have to type in the fileds of the app. Can you tell me please?</p>
<p>Thank you very much for your inscrutable, could you please upload video demonstration for this, or send me via mail, my email: info.dilhant@gmail.com </p>
<p>I got many errors. Please help!</p>
<p>I've just been starting with this project and ran into the same issue. It looks like the apache HTML client is deprecated in the most recent version of the android SDK. </p><p>if you find the file gradle.build in your project file you can add this this line...</p><p>useLibrary 'org.apache.http.legacy'</p><p>in </p><p>android{</p><p>}</p><p>more information is available at: </p><p><a href="http://stackoverflow.com/questions/32153318/httpclient-wont-import-in-android-studio" rel="nofollow">http://stackoverflow.com/questions/32153318/httpcl...</a></p><p>note this is quite a dirty work around and really the code should be reworked to accomodate the new changes. If I get a bit more comfortable with all of this I may have a go. </p>
<p>what are the complexity of this projects and please suggest some references.</p><p>how to present this project and what should be the output?</p>
<p>Hello, I just want to ask is it possible to create an android app, like a calculator type and then when the user inputs the correct combination of numbers and hit the enter button, it will send High to raspberry pi through internet connection only? If it's possible, can you help me how to do it? Thanks!</p>
<p>Hey,</p><p>does this work for live update made on the rpi? i want to send some live data from my gpio pins to an android app. </p><p>thnx<br></p>
<p>Hi sir. I have a project but and it's my first time to use Raspi. Is it possible to make an android app that can notify me if someone push a digital push button on a raspi?</p>
Ok so as a novice I have a question. Are you aware of a way to use the RasPi3 and control it with and Android Bluetooth app? <br>I have a very long story why I need this but it seems you may know the answer why I can't find the answer. It involves using the RasPi as a media center. Then dedicating a tablet to be the one paired device that controls it. Still use wifi to load media, just limit simple controls to Bluetooth.<br>Do you think it's doable?
<p>I think it's doable.</p><p>I have an app, which can communicate with a HC-05 module over Bluetooth.<br>I think that if you configure the on-board Bluetooth using rfcomm, you should be able to use the same app (back end communication). Or you could use a HC-05 module to the GPIO pins.</p><p>If you want the app, you can send me a private message with your email address and I'll mail it to you.</p><p>After you received the data, you would need some kind of code/software to change the data to your controls.</p><p>Laurens</p>
Thanks Laurens. How do I contact you with a private message? <br>(Instructibles rookie)
Click on my name and press the 'private message' button.<br><br>Laurens
<p>we have to communicate raspbeery pi with android.</p><p>which protocol should we use?</p>
<p>It depends. Do you want to communicate over internet or bluetooth.</p><p>As you're commenting here, I assume you want to communicate over internet.</p><p>There are different methods to do this, but I think it easiest to use a webserver on the raspberry pi and use POST/GET requests to send your data.</p><p>Laurens</p>
<p>bluetooth sir?,, pls really need help to interface it offline</p>
<p>we want to communicate with android<br>our supervisor told us to search on protocol<br>which is being used to communicate between android and raspberry pi</p>
<p>The protocol I used in this instructables is HTTP.</p><p>In this protocol you have 2 types: UDP and TCP, I used TCP.</p><p>Laurens</p>
<p>ok<br>UDP or TCP also works if we communicate these two over wifi?</p>
<p>Yes, this protocol is a standard for internet communication, so WiFi, ethernet, ethernet over USB, etc.</p><p>Laurens</p>
<p>thank u soo much man</p>
<p>You have done a great job. I am new to Android Studio. I am getting this error that I should use the gettext method in the UI thread. Moreover, I am using android sdk 23. The packages org.apache.http have been deprecated but I have followed a link and added android {useLibrary org.apache.http.legacy} in build.gradle file which has fixed many errors. I'll be waiting for your reply. Thanks in advance.</p>
<p>I'm glad you liked it.</p><p>Have a look <a href="http://stackoverflow.com/a/32012172/4523898">here</a>. There is a suggestion that should work.</p><p>PS. I'm working on an updated instructables, which solves the deprecated issue.</p><p>Laurens</p>
<p>But there is another problem when I enter http://192.168.xx.xx/db_create.php I get an error that the requested url is not found on the server. Although I have checked that the files are located in the www folder of my Raspberry pi .</p>
<p>Can you access the index page?</p><p>Can you look in /var/log/apache2/error.log and see if you can locate the error?</p><p>Laurens</p>
<p>Yes I can access phpmyadmin/index.php . Here is the error in error.log</p>
Got it I think I have to move the files in the html folder isn't it?
<p>Yes, that's true, that's because you are running Raspbian Jessie and I was running raspbian Wheezy.</p><p>Laurens</p>
<p>Hello! I have another question. What changes would I have to make in application in order to GET data from server in app instead of POST it?</p>
Thank you Laurens. Your timely responses are appreciable.
<p>Thank you once again that issue is solved :)</p>
<p>Hey Laurens,</p><p>very impressive project you got here. i would to ask you what JSON library did you use, because i found several libraries in the link you referred to in the beginning of the tutorial</p><p>thanks </p>
<p>Oh never mind, i thought downloadable items were images. thanks </p>
<p>Why this error:</p><p>Error:Execution failed for task ':app:processDebugResources'.</p><p>&gt; com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Users\hoda\AppData\Local\Android\Sdk\build-tools\23.0.3\aapt.exe'' finished with non-zero exit value 1</p>
<p>Where are you getting these error's? When you build the app, or when you run the app?</p><p>The theme error is because the theme you want to use is not available.</p><p>The other one, I can't say from the top of my head.</p><p>Laurens</p>
<p>Why this Error:</p><p>Error: Error retrieving parent for item: No resource found that matches the given name 'Theme.Leanback'.</p>
<p>Nice Bro (y) </p>
<p>Thanks! I'm glad you liked it.</p><p>Laurens</p>
<p>Hey Laurens, I tried the instructables. It was nice and to the point. However, like many other users who have mentioned it, my android app &quot;unfortunately stopped&quot; too. Can you help me with this? <br>the screenshots of the logcat is -<br></p>

About This Instructable

198,133views

895favorites

License:

Bio: twitter: @Laurens_Wuyts
More by Laurens-Wuyts:How to Use the Beelink SEA I Media Player Minimalistic Led Clock Control Raspberry pi GPIO using an app 
Add instructable to: