从数据库中检索数据

时间:2012-01-01 17:27:54

标签: android sql database

我正在尝试从数据库中检索数据,而我正在使用我在博客上找到的代码并进行了一些更改。

这是我的php文件:

<?php

  mysql_connect("host","username","password");

  mysql_select_db("peopledata");

  $q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");

  while($e=mysql_fetch_assoc($q))

          $output[]=$e;

       print(json_encode($output));

mysql_close();?>

我创建了以下数据库:

      CREATE TABLE people (

  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,

  name VARCHAR( 100 ) NOT NULL ,

  sex BOOL NOT NULL DEFAULT '1',

  birthyear INT NOT NULL

  )

这是我的Android Java应用程序中的代码:

public class SnowReportActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    setImageClickListener();

}

private void setImageClickListener() {
    ImageView map_image=(ImageView)findViewById(R.id.map_icon);
    map_image.setOnTouchListener(new ImageView.OnTouchListener() {
    //OnTouchListener listener = new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if(!(event.getAction() == MotionEvent.ACTION_DOWN))
                return false; //If the touch event was not putting the finger down on the screen, return false(Actions may be move, up, and so on)
            final float x = event.getX();
            final float y = event.getY();
            //System.out.println("Coordinates of button pressed are: X is %d"+x+" and Y is %d"+ y);
            if(x and y in some range)
                DoFirst();
            //... and so on...
            //In the end, you must return a boolean saying whether you "consumed" the event - if you handled the event or not.
           return true;
        }

});

}
@SuppressWarnings("null")
private void DoFirst() {
    Log.d("SnowReportApp","Do first thing");
    setContentView(R.layout.parnassos);
    String result = "";
    InputStream is = null;
    StringBuilder sb=null;
    //the year data to send
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("year","1980"));

    //http post
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://example/httpdocs/getAllPeopleBornAfter.php");
            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);
            sb = new StringBuilder();
            String line = null;
            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);
            for(int i=0;i<jArray.length();i++){
                    JSONObject 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")
                    );
            }

    }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }

} }

数据库是在我的网页的服务器上创建的。我没有给出网址,但我写了example.com。问题是在我的logcat中我看到了整个网站的html代码和一个额外的警告:

  

解析数据时出错org.json.JSONException:JSONArray文本必须以

的字符2处的'['开头

当我的服务器在我的网站上时,我得到了我的整个HTML代码,因为我没有在我的代码上提供我的服务器所需的用户名和密码。 httppost仅将URL作为参数。如果我的服务器在我的本地机器上,那么只需给出机器的IP地址,我就会看到正确的结果。任何人都可以帮我提供如何提供用户名和密码吗?

1 个答案:

答案 0 :(得分:0)

您获得的错误意味着您在JSONArray jArray = new JSONArray(result);中获得的JSON字符串,结果字符串不是有效的Json arrray。请检查结果对象中的内容