开发者

Android connectivity with MySQL

I am developing a final year project where I need to connect Android emulator with MySQL database in order to retrieve values. Java file:

public class connectivity extends Activity {
    /** Called when the activity is first created. */
    TextView txt;
    public static final String KEY_121 = "http://10.0.2.2/mysqlcon.php";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LinearLayout rootLayout = new LinearLayout(getApplicationContext());
        txt = new TextView(getApplicationContext());
        rootLayout.addView(txt);
        setContentView(rootLayout);
        // Set the text and call the connect function.
        txt.setText("Connecting...");
        // call the method to run the data retreival
        txt.setText(getServerData(KEY_121));
    }

    private String getServerData(String returnString) {
        InputStream is = null;
        String result = null;
        // the year data to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("year", "1970"));
        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(KEY_121);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }
        // convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
      开发者_高级运维      StringBuilder sb = new StringBuilder();
            String line = "0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        // parse json data
        try {
            JSONArray jArray = new JSONArray(result);
            JSONObject json_data = null;
            for (int i = 0; i < jArray.length(); i++) {
                json_data = jArray.getJSONObject(i);
                Log.i("log_tag", "id: " + json_data.getInt("id") + ", name: " + json_data.getString("name") + ", sex: " + json_data.getInt("sex") + ", birthyear: " + json_data.getInt("birthyear"));
                // Get an output to the screen
                returnString += "\n\t" + jArray.getJSONObject(i);
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return returnString;
    }
}

I have also given an internet permission in my Android manifest file. But after running the application I get the following error in logcat:

ERROR PARSING DATA org.json.JSONException:A JSONArraytext must start with '[' at character 0

I think this goes to show that a null value is being returned. Please help me out as this is my final year project. I have spent hours trying to find the solutions but it has been of no use.

I am currently using Android 2.2. The wamp server is on the localhost so I am using the address 10.0.2.2 which is a special alias to localhost (127.0.0.1). Any help will be really appreciated.

Here is the PHP code:

<?php
mysql_connect("127.0.0.1","root","chetan");
mysql_select_db("db1");
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output,JSON_FORCE_OBJECT));
mysql_close();


This is actually an issue I've run into before. The problem is your server isn't outputting valid JSON. It's missing some of the markup. I suggest you print the raw text of the response to Logcat and examine it. Perhaps even pass it into a JSON validator. That will also help you figure out if it is returning an empty value. If it's returning an empty value, then you'll need to debug your server...not your client...

Additionally, try visiting the php page from your browser and letting it simply display the JSON response. This will allow you to see what's being written by the server and help you determine where the problem really is. Just be aware, because the server is expecting a POST the easiest way to test this would probably to be to create a simple html form to POST the test data to that page. Without doing that, getting a browser to do a POST on it's own can be a pain.


do u need to use connection to php??? if not you can directly connect to mysql db to retrieve the result:

// Assume function to be :
public String customerData() {  
    String customerInfo = ""; //To store result
    try {
       Class.forName("com.mysql.jdbc.Driver"); 
       Connection con =
             DriverManager.getConnection(
                 "jdbc:mysql://10.0.2.2:3306/retailer","root","pswrd");
       PreparedStatement statement = con.prepareStatement("SELECT * FROM customers");
       ResultSet result = statement.executeQuery();
       while(result.next()) {
          customerInfo = customerInfo + result.getString("name") + "&" + 
                result.getString("C_ID") + "&" + result.getString("address") + 
                "&" + result.getString("email"); 
          // Here "&"s are added to the return string. This is help to split the
          // string in Android application
       } 
    } catch(Exception exc) {
       System.out.println(exc.getMessage());
    }
    return customerInfo;
}

But to your project library include Connector jar file for Mysql.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜