3

我已经看到了很多关于这个的问题/教程,但他们都使用某种预制数据库或使用 JSON。

我已经在我的服务器上创建了一个数据库和一个带有 simlpe 数据的表,该MySQL服务器在我的开发机器上作为服务单独运行。

我想从该表中提取数据并在我的 Andoird 应用程序启动(onCreate)时将其列出在我的 Andoird 应用程序的 ListView(MainActivity)中。

目前我正在使用预先制作的汽车名称列表。

汽车表(在 mydb 数据库中)

id, name, model, year, vin, km,price

MainActivity.java

package com.example.myfirstproject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

public class MainActivity extends Activity implements OnItemClickListener  {

    protected String[] cars =  {"BMW", "Audi", "VW", "Ford", "Subaru"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, cars);
        ListView carsList = (ListView) findViewById(R.id.listCars);
        carsList.setAdapter(adapter);
        ListView list = (ListView) findViewById(R.id.listCars);
        list.setOnItemClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Intent intent = new Intent(this, DetailsActivity.class);
        startActivity(intent);
    }
}
4

1 回答 1

3

由于使用已弃用的 PHP/MySQL 函数会引起强烈反对,我不愿意发布此答案,但这里是:

服务器端(仅供参考,不鼓励查看MySQLi或PDO_MySQL ):mysql_connect

if ($_GET["selectedCompany"] == "true" && $_GET['companyName']) {

    $query = "Your query here";

    mysql_connect($dbserver, $dbusername, $dbpassword) or die(mysql_error());
    mysql_select_db($dbname) or die(mysql_error());

    $result = mysql_query($query) or die(mysql_error());  
    $num = mysql_numrows($result);
    $row = mysql_fetch_assoc($result);

    $i = 0;
    $rows = array();
    while ($i < $num) {

        $survey_lat['survey_lat'] = mysql_result($result, $i, "survey_lat");
        $survey_lng['survey_lng'] = mysql_result($result, $i, "survey_lng");
        $thumbnail = mysql_result($result, $i, "thumbnail");
        $finalImg['thumbnail'] = base64_encode($thumbnail);
        $sign_type['sign_type'] = mysql_result($result, $i, "sign_type");
        $object_lat['object_lat'] = mysql_result($result, $i, "object_lat");
        $object_lng['object_lng'] = mysql_result($result, $i, "object_lng");

        $finalArray = array_push($rows, array_merge($sign_type, $object_lat, $object_lng, $survey_lat, $survey_lng, $finalImg));

        $i++;
    }

    print json_encode($rows);
    mysql_close();
}

要检索的客户端/Android 端AsyncTask(我修改了之前给出的答案以反映 mysql 查询以及如何解析该 JSON 数据):

class MyAsyncTask extends AsyncTask<String, String, Void> {

    private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    InputStream inputStream = null;
    String result = ""; 

    protected void onPreExecute() {
        progressDialog.setMessage("Your progress dialog message...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                MyAsyncTask.this.cancel(true);
            }
        });
    }

    @Override
    protected Void doInBackground(String... params) {

        String url_select = "http://yoururlhere.com/index.php?selectedCompany=true&companyName=examplevalue";

                ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

        try {
            // Set up HTTP post
            // HttpClient is more then less deprecated. Need to change to URLConnection
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url_select);
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // Read content & Log
            inputStream = httpEntity.getContent();
        } catch (UnsupportedEncodingException e1) {
            Log.e("UnsupportedEncodingException", e1.toString());
            e1.printStackTrace();
        } catch (ClientProtocolException e2) {
            Log.e("ClientProtocolException", e2.toString());
            e2.printStackTrace();
        } catch (IllegalStateException e3) {
            Log.e("IllegalStateException", e3.toString());
            e3.printStackTrace();
        } catch (IOException e4) {
            Log.e("IOException", e4.toString());
            e4.printStackTrace();
        }
        // Convert response to string using String Builder
        try {
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
            StringBuilder sBuilder = new StringBuilder();

            String line = null;
            while ((line = bReader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }

            inputStream.close();
            result = sBuilder.toString();

        } catch (Exception e) {
            Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
        }
    } // protected Void doInBackground(String... params)


    protected void onPostExecute(Void v) {

        //parse JSON data
        try{
            JSONArray jArray = new JSONArray(result);

            for(int i=0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);

                String signType = jObject.getString("sign_type");
                double object_lat = jObject.getDouble("object_lat");
                double object_lng = jObject.getDouble("object_lng");
                double survey_lat = jObject.getDouble("survey_lat");
                double survey_lng = jObject.getDouble("survey_lng");
                String thumbnailImg = jObject.getString("thumbnail");
                byte[] encodeByte = Base64.decode(thumbnailImg, Base64.DEFAULT);
                bmImg = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
                bmImg = Bitmap.createBitmap(bmImg);

            } // End for Loop

            this.progressDialog.dismiss();

        } catch (JSONException e) {

            Log.e("JSONException", "Error: " + e.toString());

        } // catch (JSONException e)


    } // protected void onPostExecute(Void v)

} //class MyAsyncTask extends AsyncTask<String, String, Void>
于 2012-11-02T19:26:55.947 回答