Android:发送数据以存储在MySQL中。

6

已解决:缺少postData()的视图参数,更改以反映此内容。

我需要一些帮助将GPS数据发送到服务器,并使用PHP存储在MySQL数据库中。

这是我的Java文件内部:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

public void postData(View v)
{
    nameValuePairs.add(new BasicNameValuePair("Lat","19.80"));
    nameValuePairs.add(new BasicNameValuePair("Lon","13.22"));

    //http post
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new      
        HttpPost("http://www.xxxxxxxx.com/test.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        Log.i("postData", response.getStatusLine().toString());
    }

    catch(Exception e)
    {
        Log.e("log_tag", "Error in http connection "+e.toString());
    }           
}

我使用的是PHP:

<?php
include 'connect.php'; //Connect

//retrieve the data
$lat = $_POST['lat'];
$lon = $_POST['lon'];

$sql = "INSERT INTO Coords (Lat, Lon) VALUES('$lat', '$lon')";

if (!mysql_query($sql, $sqlCon))
{
    die('Error: ' . mysql_error());
}
else
{
    //echo "1 record added";
}

include 'closeConnection.php';
?>

堆栈跟踪: 项目 - Heat [安卓应用程序]

 02-06 00:37:14.265: ERROR/AndroidRuntime(1607): FATAL EXCEPTION: main
 02-06 00:37:14.265: ERROR/AndroidRuntime(1607): java.lang.IllegalStateException: Could       
 not find a method **postData(View)** in the activity class com.nathanhunston.heat.Main for   
 onClick handler on view class android.widget.Button with id 'dropLocBtn'

你应该检查你的logcat输出并在这里发布堆栈跟踪。 - dave.c
@dave.c发布了跟踪信息,从我立刻能看到的来看,我遇到了一个IllegalStateException,所以可能是虚拟机状态不正确导致的问题... - nhunston
我认为那不是你的日志 logcat 输出。你可以使用 Eclipse 中的视图或独立工具来获取输出。请参考此链接以获取详细信息:http://developer.android.com/guide/developing/debug-tasks.html。 - dave.c
@dave.c 是的,你说得对,当模拟器崩溃时我的logcat也出问题了,我现在会发布日志。 - nhunston
4个回答

5
您的堆栈跟踪的第一行告诉您您正在做什么错误的事情:
02-06 00:37:14.265: ERROR/AndroidRuntime(1607): FATAL EXCEPTION: main
02-06 00:37:14.265: ERROR/AndroidRuntime(1607): java.lang.IllegalStateException: Could not find a method postData(View) in the activity class com.nathanhunston.heat.Main for onClick handler on view class android.widget.Button with id 'dropLocBtn'

那是因为你的 postData() 方法声明中没有 View 参数。

2
@Herly:是啊,有时候我希望从LogCat直接连接到我的大脑。但另一方面,LogCat太喋喋不休了,其他在我脑海中的声音会嫉妒的。 - CommonsWare
我们现在就想要这样做,不是吗。 - nhunston

0
你是否已经在 manifest.xml 文件中添加了 <uses-permission android:name="android.permission.INTERNET"></uses-permission> 权限?

是的,我正在尝试将GPS坐标发送到数据库进行存储,我可以访问位置,但是在向服务器发送任何形式的数据方面,我遇到了很大的问题。 - nhunston
是的,你在清单文件中有那行代码吗?在调试视图下检查Logcat并发布堆栈跟踪。 - techi.services
抱歉我的表述不够清晰,是的,我在清单文件中有这行代码。 - nhunston

0

我认为你应该在一个线程中调用它...如果服务器响应稍微慢了一点,你会收到强制关闭的消息...

你可以查看这篇文章:Android HTTP POST问题


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接