如何在线从数据库中获取数据

时间:2015-09-22 21:35:59

标签: android database http

我有一个layout.xml,当我点击一个按钮时,应用程序会在在线数据库中查找数据。想象一下,一个在线数据库上的应用程序可以查看有多少项目可供在线购买。

现在,我设置了互联网连接的检查,我可以通过onClick类设置一个动作,我使用HttpGet,但是,我如何在线查找数据库中的信息?是否有此项目的ID或要使用的参数?你是如何设置数据库的,以便用来发现信息?

提前致谢!

2 个答案:

答案 0 :(得分:0)

如果您正在讨论使用自己的数据库或创建自己的数据库,则可以创建MySQL数据库并为项目编写表格。然后使用SQL查询搜索,过滤,添加和删除表中的项目。

您还可以查看Parse这是一个带有Android SDK的后端服务,它允许您在云中在线存储项目和数据。

答案 1 :(得分:0)

这是一个很大的答案,但我们试试吧。

首先,您必须构建一个.php文件,将您的数据库数据导出到json数组中。

以下是一个例子:

<?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,因此您必须将其设置为String URL并通过Activity或Fragment中的AsyncTask调用它。

另一个例子是:

全局变量:

private String jsonResult;
private String url = "http://yourdomainorlocalhost/get_data_in_json_file.php";
ProgressDialog pDialog;
List<StockList> customList;
String[] justPrices;

现在是棘手的部分:

<强>的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中每个项目的类:

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

根据需要进行修改。

每个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>

希望我能给你一个小小的想法。