[英]Posting Data from Android app to PHP page
我一直在看其他几篇文章,并试图提出一种将数据从我的android应用程序发布到我们网站上的php页面的方法。 基本上,这是一个域检查功能,我希望用户能够在应用程序中键入一个域名,然后当他们单击“立即检查”时,他们会进入网页并显示结果。 我现在不担心在应用程序中显示结果。
这是我到目前为止的代码:
public class Domain_check extends Activity {
public void onCreate(Bundle savedInstanceState) {
postData();
}
public void postData() {
EditText domainText = (EditText) findViewById(R.id.hosting_link);
if (domainText.length()>0)
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://www.oursite.com/domainchecker.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id",domainText.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
else
{
// display message if text fields are empty
Toast.makeText(getBaseContext(),"Please enter a domain name",Toast.LENGTH_SHORT).show();
}
}
现在,当我单击按钮进行检查时(运行此活动),我得到一个nullPointerError。
我对Java还是很陌生,因此这可能是一种更简单的方法!
谢谢
编辑:
错误:
01-18 11:05:39.720: E/AndroidRuntime(353): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.oursite/com.oursite.Domain_check}: java.lang.NullPointerException
修改后的代码,现在在活动中的代码将绘制输入文本的视图,而不是单独的活动:
public class Hosting extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hosting);
View DomainButton = findViewById(R.id.domain_button);
DomainButton.setOnClickListener((OnClickListener) this);
}
public void onClick (View thisView) {
postData();
}
public void postData() {
EditText domainText = (EditText) findViewById(R.id.hosting_link);
if (domainText.length()>0)
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://www.oursite.com/domainchecker.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id",domainText.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
else
{
// display message if text fields are empty
Toast.makeText(getBaseContext(),"Please enter a domain name",Toast.LENGTH_SHORT).show();
}
}
}
我在您的活动中看不到setContentView()
方法。 因此,当您尝试获取长度时, domainText
变量为null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.