0

I have created online database consisting of a table with four rows, KEY_ID, KEY_SLOT_NAME, KEY_AVAILABLE_SLOT, and KEY_TOTAL_SLOT.

Each of them has their own rows and assigned a default value and only KEY_AVAILABLE_SLOT will have its values changed.

I've created the JSONFunctions class

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

As from How to connect Android app to MySQL database?

Now I'm stuck with fourth step which is to read the JSON Tag because I don't understand what that is.

Here's a sample code usage back when I was using my offline db for testing :

final TextView parkAvaliableA = (TextView) findViewById(R.id.parkASlot);
        parkAvaliableA.setText("Available Slot : " + SlotA.available_slot);
        Button buttonA = (Button) findViewById(R.id.parkABtn);
        buttonA.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                if(SlotA.available_slot == 0)
                {
                    Toast.makeText(getApplicationContext(), 
                            "Parking slot A is full", 
                            Toast.LENGTH_SHORT).show();
                }
                else
                {
                    SlotA.available_slot -= 1;
                    db.updateSlot(new ParkingSlot());
                }
                //parkAvaliableA.setText("Available Slot : " + SlotA.available_slot);
                Intent myIntent = new Intent(MainMap.this, ParkA.class);

                MainMap.this.startActivity(myIntent);
            }

        });

I need basic update operation for my database so that I can update the KEY_SLOT_AVAILABLE value every button press..

And one OOT question if I may : "Should I write KEY_ in every db column? Or it's just a hassle? I started using KEY_ when I read some online tutorials use KEY_"

Community
  • 1
  • 1
Kevin Murvie
  • 2,592
  • 1
  • 25
  • 43
  • Is HttpClient class working for you? – keshav kowshik May 29 '15 at 04:14
  • I don't really understand that part, sorry, but if you meant that is it working as in no error, yeah, but the function, I can't say because I don't really know.. Is that the part where I should put my address? – Kevin Murvie May 29 '15 at 04:32
  • No Not about that. That class has been deprecated. Your code might not run so asked. – keshav kowshik May 29 '15 at 04:46
  • Ohh I see.. Okay, it is fine here.. I can run, but I just don't know how to connect it with the db in the website, how to connect it? – Kevin Murvie May 29 '15 at 04:51
  • to connect it with db you need to write script and have to run it from your android code. – keshav kowshik May 29 '15 at 04:57
  • `Cursor cursor = db.query(TABLE_PARKING_SLOT, new String[] { KEY_ID, KEY_SLOT_NAME, KEY_TOTAL_SLOT, KEY_AVAILABLE_SLOT }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null); if (cursor != null) cursor.moveToFirst();` This kind of script?? Do you have any tutorial which is newbie friendly for database in Android? – Kevin Murvie May 29 '15 at 05:12
  • Using this you can fetch data from SQlite database, if you need data from server you need to write PHP, Json scripts and then run them. – keshav kowshik May 29 '15 at 05:20
  • This kind of code? `$q ="Select * from KEY_SLOT_NAME"; $result = $conn->query($q); while($row = $result->fetch_assoc()){ $output= $row;` – Kevin Murvie May 29 '15 at 06:08
  • yes this is a script for doing mysql operations you need to connect to database first. – keshav kowshik May 29 '15 at 06:27

1 Answers1

1

You need to write a script as shown below to connect to a MySql Database:

 <?php
    $servername = "Your_Server_Name";
    $username = "Your_UserName";
    $password = "Your_Password";
    $dbname = "Your_DB_Name";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);



   // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

After successful connection to the database you can perform all db operations with the server.

Check the following links you will get an idea:

http://www.w3schools.com/php/php_mysql_create.asp

http://www.tutorialspoint.com/php/create_mysql_database_using_php.htm

Hope this helps.

keshav kowshik
  • 2,354
  • 4
  • 22
  • 45
  • Ah that script! I have this script `$conn = new mysqli($hostname,$username,$password,$db); if($conn->connect_error){ $response[‘success’] =0; $response[‘message’] =”could not connect to the database”; print(json_encode($response)); die(print(json_encode($response))); } $response[success] =1; $response[message] =”successfully connected to the database”; print(json_encode($response)); ?>` I'll try using your script and.. May I have a sample db management using json? Can I still use my usual `db.updateSlot(new ParkingSlot());` ?? – Kevin Murvie May 29 '15 at 16:46
  • which db is it referring to? – keshav kowshik May 29 '15 at 16:56
  • The ParkIT db, in table parking_slot if that's what you mean.. It's the only table created in my db.. `$db = "a1295764_ParkIT";` – Kevin Murvie May 29 '15 at 17:00
  • If it is in your server yes you can use it. But db.update method i doubt you can use it or not. You need to do it the mysql way – keshav kowshik May 29 '15 at 17:01
  • Wait.. MySQL is different from SQLite?! Sorry I'm really new at database, bear with me please.. So, after reading for a bit, I should use PHP in CRUD operations for MySQL? And every code is done in PHP? And also my code in Android will only call the php file from my server? – Kevin Murvie May 29 '15 at 17:10
  • Yes the process is create database in server, use php script as an interface between your server and android, write operations of crud in php script using mysql and then run that script from the code.. – keshav kowshik May 29 '15 at 17:13
  • I see, I found this snippet `query($sql) as $row) { ... ` I would like to only show AVAILABLE_SLOT, but for every Slot from A through D, so I should make 4 php files for each of them?? – Kevin Murvie May 29 '15 at 17:22
  • Hmm, I see.. But I'm still confused about this.. So after writing your code, I should start writing the queries? I have four buttons which get separate Slot.. So it'll be like.. `$sql = 'SELECT * FROM KEY_AVAILABLE_SLOT WHERE KEY_SLOT_NAME = SlotA';` ? – Kevin Murvie May 29 '15 at 17:34
  • Yes.. like that. if my answer helped you please upvote it and accept it as an answer – keshav kowshik May 29 '15 at 17:40
  • What about the rest of the Slots?? Like SlotB and SlotD? Where should I call them in the code?? In each button? I'm still testing out the MySQL..Yes you helped me a lot in understanding MySQL, but I'm still confused in the Android part :( – Kevin Murvie May 29 '15 at 17:47
  • you should write the code in Async Task. see the following link: http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89 – keshav kowshik May 29 '15 at 17:49
  • You're welcomee, so in your androidexample.com, I should write `String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(Name, "UTF-8");` I change that "name" into slota as in local variable? And "Name" into SlotA as in the SLOT_NAME column of my db? If that's right, so I have to write `String slota` through `String slotd`? – Kevin Murvie May 29 '15 at 18:09
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/79156/discussion-between-kevin-murvie-and-keshav1234). – Kevin Murvie May 29 '15 at 18:15
  • Yes you have to change that as per your need. one is the for the key to be accessed in php and other is your acyual variable. the one with quotes in the example is the quotes. The example also tells how you can decode in php – keshav kowshik May 30 '15 at 01:22