如何将android与mysql数据库连接?

时间:2013-01-15 09:39:52

标签: android mysql

我有一个微型项目与mysql.I尝试很多方式连接android与mysql,如

  1. 将其更改为127.0.0.1
  2. 将其更改为ip
  3. 将它们更改为10.0.2.2并在eclipse peference上设置
  4. 我已经有两个星期了,但我做不到。
    我的笔记本是dell vostro 3450 64位

    ** P.S。你介意我问过来自真实主机的网址吗?

    这是我的代码。

    getjson.php

    <?
        $objConnect = mysql_connect("localhost","root","root");
        $objDB = mysql_select_db("mydatabase");
    
        // $_POST["txtKeyword"] = "a"; // for Sample
    
        $strKeyword = $_POST["txtKeyword"];
        $strSQL = "SELECT * FROM customer WHERE 1 AND Name LIKE '%".$strKeyword."%'  ";
    
        $objQuery = mysql_query($strSQL);
        $intNumField = mysql_num_fields($objQuery);
        $resultArray = array();
        while($obResult = mysql_fetch_array($objQuery))
        {
            $arrCol = array();
            for($i=0;$i<$intNumField;$i++)
            {
                $arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
            }
            array_push($resultArray,$arrCol);
        }
    
        mysql_close($objConnect);
    
        echo json_encode($resultArray);
    ?>
    

    activity_main.xml中

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/tableLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    
        <TableRow
          android:id="@+id/tableRow1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" >
    
         <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Search Customer : "
            android:layout_span="1"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    
         <EditText
             android:id="@+id/editText1"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:ems="4" >
    
         </EditText>
    
         <Button
             android:id="@+id/button1"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="OK" />
    
        </TableRow>
    
        <View
            android:layout_height="1dip"
            android:background="#CCCCCC" />
    
      <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0.1">   
    
         <ListView
             android:id="@+id/listView1"
             android:layout_width="match_parent"
             android:layout_height="wrap_content">
         </ListView>
    
        </LinearLayout>
    
        <View
            android:layout_height="1dip"
            android:background="#CCCCCC" />
    
        <LinearLayout
          android:id="@+id/LinearLayout1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:padding="5dip" >
    
            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="By.. ThaiCreate.Com" />
    
        </LinearLayout>
    
    </TableLayout>
    


    activity_column.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1" 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    
        <TextView
        android:id="@+id/ColCustomerID" 
            android:layout_width="0dp"
            android:layout_height="wrap_content" 
            android:layout_weight="0.2"
            android:text="CustomerID"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    
        <TextView
            android:id="@+id/ColName" 
            android:layout_width="0dp"
            android:layout_height="wrap_content" 
            android:layout_weight="1.0"
            android:text="Name"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    
        <TextView
            android:id="@+id/ColEmail"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Email"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    
    </LinearLayout>
    

    MainActivity.java

    package com.myapp;
    
    public class MainActivity extends Activity {
    
    
        @SuppressLint("NewApi")
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Permission StrictMode
            if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }
    
            final Button btn1 = (Button) findViewById(R.id.button1);
            // Perform action on click
            btn1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    SearchData();
                }
            });
    
        }
    
        public void SearchData()
        {
             // listView1
            final ListView lisView1 = (ListView)findViewById(R.id.listView1);   
    
            // editText1
            final EditText inputText = (EditText)findViewById(R.id.editText1); 
    
            /**
             * [{"CustomerID":"C001","Name":"Win Weerachai","Email":"win.weerachai@thaicreate.com" ,"CountryCode":"TH","Budget":"1000000","Used":"600000"},
             * {"CustomerID":"C002","Name":"John Smith","Email":"john.smith@thaicreate.com" ,"CountryCode":"EN","Budget":"2000000","Used":"800000"},
             * {"CustomerID":"C003","Name":"Jame Born","Email":"jame.born@thaicreate.com" ,"CountryCode":"US","Budget":"3000000","Used":"600000"},
             * {"CustomerID":"C004","Name":"Chalee Angel","Email":"chalee.angel@thaicreate.com" ,"CountryCode":"US","Budget":"4000000","Used":"100000"}]
             */
    
            String url = "http://10.0.2.2/android/getJSON.php";
    
            // Paste Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("txtKeyword", inputText.getText().toString()));
    
            try {
                JSONArray data = new JSONArray(getJSONUrl(url,params));
    
                final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
                HashMap<String, String> map;
    
                for(int i = 0; i < data.length(); i++){
                    JSONObject c = data.getJSONObject(i);
    
                    map = new HashMap<String, String>();
                    map.put("CustomerID", c.getString("CustomerID"));
                    map.put("Name", c.getString("Name"));
                    map.put("Email", c.getString("Email"));
                    map.put("CountryCode", c.getString("CountryCode"));
                    map.put("Budget", c.getString("Budget"));
                    map.put("Used", c.getString("Used"));
                    MyArrList.add(map);
    
                }
    
    
                SimpleAdapter sAdap;
                sAdap = new SimpleAdapter(MainActivity.this, MyArrList, R.layout.activity_column,
                        new String[] {"CustomerID", "Name", "Email"}, new int[] {R.id.ColCustomerID, R.id.ColName, R.id.ColEmail});      
                lisView1.setAdapter(sAdap);
    
                final AlertDialog.Builder viewDetail = new AlertDialog.Builder(this);
                // OnClick Item
                lisView1.setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView<?> myAdapter, View myView,
                            int position, long mylng) {
    
                        String strCustomerID = MyArrList.get(position).get("CustomerID")
                                .toString();
                        String sName = MyArrList.get(position).get("Name")
                                .toString();
                        String strEmail = MyArrList.get(position).get("Email")
                                .toString();
                        String strCounryCode = MyArrList.get(position).get("CounryCode")
                                .toString();
                        String strBudget = MyArrList.get(position).get("Budget")
                                .toString();
                        String strUsed = MyArrList.get(position).get("Used")
                                .toString();
    
                        viewDetail.setIcon(android.R.drawable.btn_star_big_on);
                        viewDetail.setTitle("Member Detail");
                        viewDetail.setMessage("MemberID : " + strCustomerID + "\n"
                                + "Name : " + sName + "\n" 
                                + "strEmail : " + strEmail + "\n" 
                                + "strCounryCode : " + strCounryCode + "\n" 
                                + "strBudget : " + strBudget + "\n"
                                + "Used : " + strUsed);
                        viewDetail.setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        // TODO Auto-generated method stub
                                        dialog.dismiss();
                                    }
                                });
                        viewDetail.show();
    
                    }
                });
    
    
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    
        public String getJSONUrl(String url,List<NameValuePair> params) {
            StringBuilder str = new StringBuilder();
            HttpClient client = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
    
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
                HttpResponse response = client.execute(httpPost);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                if (statusCode == 200) { // Download OK
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        str.append(line);
                    }
                } else {
                    Log.e("Log", "Failed to download file..");
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str.toString();
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }
    
    }
    

1 个答案:

答案 0 :(得分:0)

试试这个:

$objConnect = mysql_connect("localhost","root","root");
if (! $objConnect)
{
  die('Could not connect: ' . mysql_error());
}

并检查客户端上的消息,如果它返回任何错误并显示给我们。