gpt4 book ai didi

android - 如何从MySQL数据库中获取数据并在ListView中列出

转载 作者:太空狗 更新时间:2023-10-29 12:49:58 24 4
gpt4 key购买 nike

我看过很多关于此的问题/教程,但它们要么使用某种预制数据库,要么使用 JSON。

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

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

目前我使用的是预制的汽车名称列表。

Cars 表(在 mydb 数据库中)

id, name, model, year, vin, >公里, 价格

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

最佳答案

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

服务器端(仅供引用,查看 MySQLi or 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 检索(我修改了之前给出的答案以反射(reflect) 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>

关于android - 如何从MySQL数据库中获取数据并在ListView中列出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13201006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com