繁体   English   中英

从数据库检索数据

[英]Retrieving data from 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地址,我就会看到正确的结果。 谁能帮助我提供用户名和密码?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM