Izzo32
Izzo32

Reputation: 179

Sending Data to JSON for Database Connectivity

I have the following code which selects a data from database using web services and JSON.

MainActivity.java:

public class MainActivity extends Activity {
    RetrievingDataFromDatabase retrievingTask;
    TextView resultView;
    String s;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //StrictMode.enableDefaults();
        retrievingTask = new RetrievingDataFromDatabase();
        retrievingTask.execute((Void) null);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    public void getData(){
        resultView = (TextView) findViewById(R.id.textView1);
        String result = "";
        InputStream isr = null;
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet("http://PHP FILE LINK");
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            isr = entity.getContent();
        }
        catch(Exception e){
            Log.e("log_tag","Error in http connection"+e.toString());
            resultView.setText("Couldnt connect to database");
        }
        //converting to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null){
                sb.append(line + "\n");
            }
            isr.close();
            result = sb.toString();
        }
        catch(Exception e){
            Log.e("log_tag", "Error converting result"+ e.toString());
        }

        //parse data
        try{
            s = "";
            JSONArray jArray = new JSONArray(result);
            for(int i = 0;i<jArray.length();i++){
                JSONObject json = jArray.getJSONObject(i);
                s = s + json.getString("StdId").toString();
            }
            //resultView.setText(s);
        }
        catch(Exception e){
            Log.e("Log_tage", "Error Parsing Data"+e.toString());
        }
    }

    class RetrievingDataFromDatabase extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {
            getData();
            return null;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            resultView.setText(s);
        }
    }
}

JSONParser.java:

    public class JSONParser {
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";

        public JSONParser() {

        }

        public JSONObject getJSONFromUrl(String url) {

            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();           

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            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();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            // return JSON String
            return jObj;

        }

}

PHP File:

<?php

$con = mysql_connect("***","***","***");

if (!$con)
    {
    die('Could not Connect:' . mysql_error());
    }

mysql_select_db("database_name",$con);

$result = mysql_query("SELECT STID FROM database_name");

while($row = mysql_fetch_assoc($result))
    {
       $output[]=$row;
    }

print(json_encode($output));

mysql_close($con);

?>

This bulk of code retrieves data from database, i need help with reversing the process ( sending data to the PHP file and selecting data depending on this value. for example:

1- Data received from the android application to the php file 2- The select from database line in the PHP file will be something like :

"select * from DB_name WHERE ".$valueFromAndroidApp

3- Data retrieved from database to the PHP file then the PHP sends the result to the android application.

Sorry for the long explanation, but please i need help with this.

Upvotes: 2

Views: 1348

Answers (1)

Dehan Wjiesekara
Dehan Wjiesekara

Reputation: 3182

I'll give you a sample code for mark current location from android and send the details to the servers php file and create a new record in php.. here I have given the php file.. I assume you know how to parse json from android. if not I'll give you that also..

// check for required fields
 if (isset($_POST['location']) && isset($_POST['email']) && isset($_POST['lat']) && isset($_POST['longitude'])) {

    $location = $_POST['location'];
    $email = $_POST['email'];
    $lat = $_POST['lat'];
    $longitude = $_POST['longitude'];

    require_once 'config.php';
    // connecting to mysql
    $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
    // selecting database
    mysql_select_db(DB_DATABASE);

   // mysql inserting a new row
   $result = mysql_query("INSERT INTO marked_locations(location, email,lat,longitude) VALUES('$location', '$email', '$lat','$longitude')");
   .....
   ..

location, email, lat, longitude values a come with json from android

Upvotes: 2

Related Questions