如何从在线数据库获取数据
我有一个layout.xml中,当我点击一个按钮,应用程序查找一个在线数据库中的数据。想象一下,在一个数据库上线,看看有多少项目留给网上购物的应用程序。
I have a layout.xml in which when I click a button, the app looks for data on an online database. Imagine an app that goes on a DB online to see how many items are left for online purchases.
现在,我设置互联网连接的检查,我可以通过onClick的类设置一个动作,我用的是HTTPGET,但是,我该如何寻找一个信息数据库联机?是否有此项目,或者参数,使用任何ID?你是怎么设置你的数据库,以便用来让信息可以找到?
Now, I set the check for internet connectivity, I can set an action through the onClick class and I use the HttpGet but, how do I look for an information in a database online? Is there any ID for this item, or parameters to be used? How did you set your database, so as to be used to let information be found?
在此先感谢!
这是一个大的答案,但可以尝试。
That is a large answer but lets try.
首先你必须建立,将数据库数据导出到一个JSON数组的.php
文件。
First of all you have to build a .php
file that will export your database data into a json array.
下面是一个例子:
<?php
try {
$con = new PDO('mysql:host=yourserver(localhost in most cases);dbname=yourdatabasename', 'username', 'password');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
echo $e->getMessage();
die();
}
$query = $con->query('SELECT * FROM tablename');
$data = array();
$data = $query->fetchAll(PDO::FETCH_ASSOC);
$arrayWithData['jsonArrayName'] = $data;
echo json_encode($arrayWithData);
?>
现在,因为你有一个jsonArray你将不得不将其设置为一个字符串的URL,并在你的活动或片段叫它通过AsyncTask的所有数据库数据。
Now since you have a jsonArray with all database data you are going to have to set it as a String URL and call it through AsyncTask in your Activity or Fragment.
另一个例子是这样的:
全局变量:
private String jsonResult;
private String url = "http://yourdomainorlocalhost/get_data_in_json_file.php";
ProgressDialog pDialog;
List<StockList> customList;
String[] justPrices;
而现在到了棘手的部分:
And now comes the tricky part:
AsyncTask的:
public class JsonReadTask extends AsyncTask<String, Void, String> {
public JsonReadTask() {
super();
}
//Create a ProgressDialog so the screen wont freeze while the Task Executes
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListLoaderActivity.this);
pDialog.setTitle(R.string.waiting);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage(getString(R.string.get_stocks));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.setInverseBackgroundForced(true);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
} catch (Exception e) {
Intent intent1 = new Intent(YourActivity.this,
RefreshActivity.class);
startActivity(intent1);
YourActivity.this.finish();
}
return null;
}
//Convert responce to String
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (Exception e) {
Intent intent1 = new Intent(YourActivity.this,
RefreshActivity.class);
startActivity(intent1);
YourActivity.this.finish();
}
return answer;
}
//Method that is being called after data have been downloaded
@Override
protected void onPostExecute(String result) {
ListDrawer();
pDialog.dismiss();
}
}// end async task
// A method to execute task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
task.execute(new String[]{url});
}
//Now that we have gotten the items fetched we can build the ListView
public void ListDrawer() {
customList = new ArrayList<StockList>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("jsonArrayName");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.optString("name");
price = jsonChildNode.optString("price");
price1 = jsonChildNode.optString("price1");
price2 = jsonChildNode.optString("price2");
price3 = jsonChildNode.optString("price3");
price4 = jsonChildNode.optString("price4");
price5 = jsonChildNode.optString("price5");
price6 = jsonChildNode.optString("price6");
price7 = jsonChildNode.optString("price7");
price8 = jsonChildNode.optString("price8");
price9 = jsonChildNode.optString("price9");
price10 = jsonChildNode.optString("price10");
price11 = jsonChildNode.optString("price11");
price12 = jsonChildNode.optString("price12");
price13 = jsonChildNode.optString("price13");
price14 = jsonChildNode.optString("price14");
price15 = jsonChildNode.optString("price15");
image = jsonChildNode.optString("image");
justPrices = new String[]{price1, price2,
price3, price4, price5, price6, price7, price8, price9,
price10, price11, price12, price13, price14, price15};
justPrices = new String[]{"1st Day Value " + price1, "2nd Day Value " + price2, "3rd Day Value " + price3, "4th Day Value " + price4, "5th Day Value " + price5,
"6th Day Value " + price6, "7th Day Value " + price7, "8th Day Value " + price8, "9th Day Value " + price9,
"10th Day Value " + price10, "11th Day Value " + price11, "12th Day Value " + price12, "13th Day Value " + price13, "14th Day Value " + price14, "15th Day Value " + price15};
customList.add(new StockList(name, price, image, justPrices));
}
} catch (Exception e) {
//Handle the main screen if the Internet is too slow and redirect user to refresh the screen
Intent intent1 = new Intent(YourActivity.this,
RefreshActivity.class);
startActivity(intent1);
ListLoaderActivity.this.finish();
}
//I have created a Custom Adapter class that extends ArrayAdapter to build my ListView as i would like
ArrayAdapter adapter = new MyStocksAdapter(YourActivity.this, R.layout.list_item, customList);
adapter.notifyDataSetChanged();
startList.setAdapter(adapter);
}
适配器类:
public class MyStocksAdapter extends ArrayAdapter<StockList> {
public MyStocksAdapter(Context context, int resource, List<StockList> objects) {
super(context, resource, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItems holder;
View stockView = null;
StockList current = null;
if(stockView == null){
LayoutInflater li = LayoutInflater.from(getContext());
stockView = li.inflate(R.layout.list_item, parent, false);
current = getItem(position);
holder = new ViewHolderItems();
holder.stockViewName = (TextView)stockView.findViewById(R.id.stock_name);
holder.stockViewPrice = (TextView)stockView.findViewById(R.id.stock_price);
holder.stockViewImage = (ImageView)stockView.findViewById(R.id.imagestartinglist);
stockView.setTag(holder);
}else{
holder = (ViewHolderItems)stockView.getTag();
}
if(current != null){
holder.stockViewName.setText(current.getStockCurrentName());
holder.stockViewPrice.setText(current.getStockCurrentPrice());
//Using a library to download images and then set them to imageview
Ion.with(holder.stockViewImage).placeholder(R.drawable.ic_chat).error(R.drawable.ic_chat).load(current.getStockImage());
}
return stockView;
}
static class ViewHolderItems {
TextView stockViewName, stockViewPrice;
ImageView stockViewImage;
}
}
ListView中的类每个项目:
The Class for each Item in the ListView:
public class StockList {
private String stockCurrentName;
private String stockCurrentPrice;
private String stockImage;
private String[] restPrices;
public StockList(String stockCurrentName, String stockCurrentPrice, String stockImage, String[] restPrices) {
this.stockCurrentName = stockCurrentName;
this.stockCurrentPrice = stockCurrentPrice;
this.stockImage = stockImage;
this.restPrices = restPrices;
}
public String getStockCurrentName() {
return stockCurrentName;
}
public void setStockCurrentName(String stockCurrentName) {
this.stockCurrentName = stockCurrentName;
}
public String getStockCurrentPrice() {
return stockCurrentPrice;
}
public void setStockCurrentPrice(String stockCurrentPrice) {
this.stockCurrentPrice = stockCurrentPrice;
}
public String getStockImage() {
return stockImage;
}
public void setStockImage(String stockImage) {
this.stockImage = stockImage;
}
public String[] getRestPrices() {
return restPrices;
}
public void setRestPrices(String[] restPrices) {
this.restPrices = restPrices;
}
}
修改,如你所愿。
Modify as you wish.
和布局为每个 list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:descendantFocusability="blocksDescendants"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_gravity="center"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
card_view:cardBackgroundColor="@color/gold"
android:layout_margin="5dp"
card_view:cardCornerRadius="4dp"
android:layout_height="80dp" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:padding="10dp"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imagestartinglist"
android:layout_width="65dp"
android:layout_height="65dp"
android:src="@drawable/ic_chat"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/stock_name"
android:layout_alignBottom="@+id/stock_name"
android:layout_marginLeft="23dp"
android:layout_toRightOf="@+id/imagestartinglist"
android:text="@string/stock_name"
android:textColor="#000"
android:gravity="center_vertical|center_horizontal" />
<TextView
android:id="@+id/stock_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_toRightOf="@+id/textView2"
android:padding="6dp"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000"
android:gravity="center_vertical|center_horizontal" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal">
<TextView
android:id="@+id/fake_name_day"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/stock_name"
android:text="@string/current_price"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#000"
android:gravity="center_vertical|center_horizontal" />
<TextView
android:id="@+id/stock_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/fake_name_day"
android:layout_marginLeft="28dp"
android:textColor="#000"
android:layout_toRightOf="@+id/fake_name_day"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:gravity="center_vertical|center_horizontal" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
希望我帮助给你一个小的想法。
Hope i helped give you a small idea.