【问题标题】:Sending Data to JSON for Database Connectivity将数据发送到 JSON 以进行数据库连接
【发布时间】:2013-12-01 14:57:46
【问题描述】:

我有以下代码,它使用 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 database 行将类似于:

"select * from DB_name WHERE ".$valueFromAndroidApp

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

抱歉,解释太长了,但我需要帮助。

【问题讨论】:

  • 你好,你能把问题描述的更清楚一点吗?还要添加有关您所拥有的或问题所在的代码。现在看来你有一种方法,想要做相反的事情。不够清楚
  • 问题已编辑,请检查

标签: php android mysql database json


【解决方案1】:

我会给你一个示例代码,用于从 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 的 json

【讨论】:

  • 感谢@Dehan 的回复,但我有一个问题,$_POST['location'] 是来自 android 应用程序的值?
  • 对不起@Dehan,我刚刚看到代码后的最后一行,非常感谢,我会试试看,希望它能工作:)
猜你喜欢
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多