将数据发送到JSON以实现数据库连接

时间:2013-11-18 12:44:13

标签: php android mysql database json

我有以下代码,它使用Web服务和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文件:

<?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);

?>

这大部分代码从数据库中检索数据,我需要帮助来反转过程(将数据发送到PHP文件并根据此值选择数据。例如:

1 - 从Android应用程序收到的数据到php文件 2 - PHP文件中从数据库行中选择的内容如下:

"select * from DB_name WHERE ".$valueFromAndroidApp

3 - 从数据库检索数据到PHP文件,然后PHP将结果发送到Android应用程序。

很抱歉有很长的解释,但我需要帮助。

1 个答案:

答案 0 :(得分:2)

我会给你一个标记当前位置的示例代码来自android并将详细信息发送到服务器php文件并在php中创建一个新记录..这里我给了php文件..我假设你知道如何从android解析json。如果不是我也会给你那个..

// 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')");
   .....
   ..

位置,电子邮件,纬度,经度值来自android的