您好我是Android编程的新手。我试图在Android中创建一个登录/注册应用程序。我创建了php脚本来连接和修改我的数据库。以下是我通过查看教程为应用程序编写的代码,但是当我尝试运行它时,我遇到了一些错误。有人可以告诉我哪里出错了。
public class RegisterActivity extends ActionBarActivity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText username;
EditText password;
EditText emailid;
EditText phonenumber;
// url to create new product
private static String url_register_user = "http://www.doc.ic.ac.uk/project/2013/271/g1327139/webapp/php%20script/index.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_user);
// Edit Text
username = (EditText) findViewById(R.id.reg_username);
password = (EditText) findViewById(R.id.reg_password);
emailid = (EditText) findViewById(R.id.reg_emailid);
phonenumber = (EditText) findViewById(R.id.reg_mobilenumber);
// Create button
Button register = (Button) findViewById(R.id.register);
// button click event
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new RegisterNewUser().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
private class RegisterNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setMessage("Registering User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Registering user
* */
protected String doInBackground(String... args) {
String userName = username.getText().toString();
String passWord = password.getText().toString();
String emailId = emailid.getText().toString();
String phoneNumber = phonenumber.getText().toString();
String register = "register";
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register));
params.add(new BasicNameValuePair("username", userName));
params.add(new BasicNameValuePair("password", passWord));
params.add(new BasicNameValuePair("emailid", emailId));
params.add(new BasicNameValuePair("phonenumber", phoneNumber));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeServiceCall(url_register_user,
2, params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.register_user, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
这是我尝试注册新用户时遇到的错误。
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at
com.example.pubcrawl.app.RegisterActivity$RegisterNewUser.doInBackground(RegisterActivity.java:113)
at com.example.pubcrawl.app.RegisterActivity$RegisterNewUser.doInBackground(RegisterActivity.java:74)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
05-26 15:20:51.511 8766-8766/com.example.pubcrawl.app E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.pubcrawl.app.RegisterActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42ba7588 V.E..... R......D 0,0- 1026,288} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:456)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:267)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:288)
at `enter code here`com.example.pubcrawl.app.RegisterActivity$RegisterNewUser.onPreExecute(RegisterActivity.j ava:86)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.pubcrawl.app.RegisterActivity$1.onClick(RegisterActivity.java:64)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19330)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
05-26 15:20:57.607 8766-9420/com.example.pubcrawl.app I/Process﹕ Sending signal. PID: 8766 SIG: 9
答案 0 :(得分:1)
你可以这样做
JSONParser类
public class JSONParser
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params)
{
try
{
if (method == "POST")
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else if (method == "GET")
{
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e)
{
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
<强> RegisterActivity 强>
public class RegisterActivity extends ActionBarActivity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText username;
EditText password;
EditText emailid;
EditText phonenumber;
// url to create new product
private static String url_register_user = "http://www.doc.ic.ac.uk/project/2013/271/g1327139/webapp/php%20script/index.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_user);
// Edit Text
username = (EditText) findViewById(R.id.reg_username);
password = (EditText) findViewById(R.id.reg_password);
emailid = (EditText) findViewById(R.id.reg_emailid);
phonenumber = (EditText) findViewById(R.id.reg_mobilenumber);
// Create button
Button register = (Button) findViewById(R.id.register);
// button click event
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new RegisterNewUser().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
private class RegisterNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setMessage("Registering User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Registering user
* */
protected String doInBackground(String... args) {
String userName = username.getText().toString();
String passWord = password.getText().toString();
String emailId = emailid.getText().toString();
String phoneNumber = phonenumber.getText().toString();
String register = "register";
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register));
params.add(new BasicNameValuePair("username", userName));
params.add(new BasicNameValuePair("password", passWord));
params.add(new BasicNameValuePair("emailid", emailId));
params.add(new BasicNameValuePair("phonenumber", phoneNumber));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeServiceCall(url_register_user,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.register_user, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
答案 1 :(得分:0)
我建议在代码中添加一个断点并逐步执行它。
我的记忆告诉我makeServiceCall应该有params URL,METHOD和PARAMS。你的方法实际上是2吗?
如果没有放入断点并找出错误所在的位置。
另外,请检查此问题Android call PHP with HTTP-GET。
如果您在开发Android应用程序时正在寻找&#34;调用PHP脚本,那么会返回大量网站&#34;