从我的数据库android中检索数据?

Posted

技术标签:

【中文标题】从我的数据库android中检索数据?【英文标题】:Retrieving data back from my database android? 【发布时间】:2015-07-04 17:18:40 【问题描述】:

我的应用程序是一个简单的跟踪系统,其中每个用户的位置都会更新到服务器上,当需要帮助时,它会发回给定范围(大约)内所有人的手机号码。 该应用程序可以完美地定期将位置更新到服务器,并使用一种近似方法来查找一定范围内的人我现在面临的问题是将查询的号码列表发送回设备。我已经尝试了一些教程,但没有运气,应用程序不断崩溃。 这是我的代码,我将数据与 php 代码一起发送。如果有人帮我弄清楚如何从服务器接收回号码。

private void serverConnection() 
    // TODO Auto-generated method stub


    GPSTracker gps1 = new GPSTracker(MainActivity.this);
    double latitude = gps1.getLatitude();
    double longitude = gps1.getLongtitude();
    Toast.makeText(getApplicationContext(),"Your Location is -\nLat:"+latitude+"\nLon:"+longitude,Toast.LENGTH_LONG).show();
    String lat = String.valueOf(latitude);
    String log = String.valueOf(longitude);

    String svdNum;

    RegistrationActivity gsm = new RegistrationActivity();
    SharedPreferences sharedData = getSharedPreferences(gsm.filename,0);
    svdNum = sharedData.getString("Mobile Number", "No Number Registered");


    List<NameValuePair>  nameValuePairs = new ArrayList<NameValuePair>(1);

    nameValuePairs.add(new BasicNameValuePair("Lat",lat));
    nameValuePairs.add(new BasicNameValuePair("Long",log));
    nameValuePairs.add(new BasicNameValuePair("Number",svdNum));

    try
        if(distress == 0)
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://10.0.2.2/tech/serverConnection.php");
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        else
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://10.0.2.2/tech/serverConnection2.php");
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        
    
    catch(ClientProtocolException e)
        Log.e("ClientProtocol", "Log_tag");
        e.printStackTrace();
    
    catch(IOException e)
        Log.e("Log_tag", "IOException");
        e.printStackTrace();
    

php代码

<?php
$conn = mysql_connect(localhost, 'root', '');
mysql_select_db('finalyearproject');
if(! $conn )

  die('Could not connect: ' . mysql_error());


$Number=$_POST['Number'];
$LatitudeS=$_POST['Lat'];
$LongitudeS=$_POST['Long'];

$Latitude = floatval($LatitudeS);
$Longitude = floatval($LongitudeS);

$sql = "INSERT INTO app_backup(Number,Latitude, Longitude) VALUES('$Number', '$Latitude', '$Longitude') ON DUPLICATE KEY UPDATE Latitude=VALUES(Latitude), Longitude=VALUES(Longitude)";


$sql = "UPDATE app_backup SET Lat_diff=Latitude-$Latitude ,Long_diff=Longitude-$Longitude";

$query= mysql_query("SELECT Number FROM app_backup WHERE Lat_diff <= 30 AND Long_diff <=30 AND Long_diff <> 0 AND Lat_diff <> 0 AND Long_diff >= -30 AND Lat_diff >= -30"); 


$column = array();

while ( $row = mysql_fetch_array($query, MYSQL_ASSOC) ) 
  $column[] = $row['Number'];


echo json_encode(column);


$retval = mysql_query( $sql, $conn );
if(! $retval )

  die('Could not enter data: ' . mysql_error());

echo "Entered data successfully\n";
mysql_close($conn);

?>

在此先感谢您。

编辑: 应用程序不断崩溃的代码块

HttpEntity entity2 = response.getEntity();
                InputStream nums = entity2.getContent();
                try
                BufferedReader reader = new BufferedReader(new InputStreamReader(nums,"iso-8859-1") );
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null)
                    sb.append(line + "\n");
                     
            nums.close();
            res = sb.toString(); 
            
            catch(IOException e)
                Log.e("Log_tag", "IOException");
                e.printStackTrace();
            

Json 循环

try
    JSONArray jarray = new JSONArray(res); 
    JSONObject json_data = null;
    for(int i=0; i < jarray.length(); i++)
    
        json_data = jarray.getJSONObject(i);
    
catch(JSONException e)
    Log.e("error parsing data", "Log_tag");
    e.printStackTrace();

添加这两个块后,logcat 说“关闭 VM”,应用程序崩溃了。我不太确定我的方法在检索方面是否正确。

【问题讨论】:

您说“应用不断崩溃”,但没有说在哪里如何崩溃。你能详细说明一下吗? 我已经编辑了有关应用程序崩溃的问题。 @WaiHaLee 【参考方案1】:

要以 JSON 格式向您的应用程序发送数据,您必须发送标头并在最后发送带有 json_encode 的 JSON。另一个陷阱是 PHP 文件的编码(必须是没有 BOM 的 UTF-8),否则会损坏 json。

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');//*/
echo json_encode(column);

但是要完成这项工作,有 Simple JSON for PHP 轻量库,它使您能够随意“伪造”您的 JSON 并在单个命令中发送它(包括标头)。

你的情况是这样的:

// At the beginning
$Json = new json();

// Add the data
while ( $row = mysql_fetch_array($query, MYSQL_ASSOC) ) 
  $Json->addContent(new arrayJson("data",$row));

$Json->addContent(new propertyJson('message', 'Success'));

// At the end, send the json
json_send($Json)

在JAVA部分:

要获取 JSON,您应该创建一个类似 here 的方法

public String getJSON(String url, int timeout) 
    HttpURLConnection c = null;
    try 
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) 
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) 
                    sb.append(line+"\n");
                
                br.close();
                return sb.toString();
        

     catch (MalformedURLException ex) 
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
     catch (IOException ex) 
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
     finally 
       if (c != null) 
          try 
              c.disconnect();
           catch (Exception ex) 
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
          
       
    
    return null;

您应该使用Google GSON 将JSON 转换为Data Java 对象,如*** 所示。

import java.util.List;
import com.google.gson.Gson;

public class Test 

    public static void main(String... args) throws Exception 
        String json = 
            ""
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : ["
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : ["
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "]" 
                + "]"
            + "";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    



class Data 
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle()  return title; 
    public Long getId()  return id; 
    public Boolean getChildren()  return children; 
    public List<Data> getGroups()  return groups; 

    public void setTitle(String title)  this.title = title; 
    public void setId(Long id)  this.id = id; 
    public void setChildren(Boolean children)  this.children = children; 
    public void setGroups(List<Data> groups)  this.groups = groups; 

    public String toString() 
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    

希望对你有帮助

【讨论】:

以上是关于从我的数据库android中检索数据?的主要内容,如果未能解决你的问题,请参考以下文章

我无法从我的数据库中检索图像

通过 Android 3g 连接到服务器并从 phpmyadmin 检索数据

如何使用从我的 SQLite 数据库中检索到的数据填充 tkinter 下拉框?

从我的表单中的字段中保存数据并通过在我的主视图控制器中列出主键来检索它们?

从 SQLite 数据库加载的数据未保存在模型类 ArrayList android 中

检索联系人数据 Android 时出现 RuntimeException