您好,我是Android新手,目前正在使用MySql,PHP和JSON开发一个简单的登录和注册android应用。我已经在xampp(本地服务器)中创建了一个数据库和表。每当我尝试注册时,都会遇到很多错误。已经有类似的问题,但是答案并没有帮助我。提前致谢。
这是我的代码
JSONParser
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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 parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
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"){
// request method is 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 parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
注册.java
import android.app.Activity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
// Creating the Java class
public class Register extends Activity implements OnClickListener{
// Creating variables for username and password...
private EditText user,pass;
private Button register;
// Creating the progressDialog...
private ProgressDialog pDialog;
// Creating reference for the JSONParser...
JSONParser jsonparser = new JSONParser();
// Getting the url to run the php register script..
// Here I am using a localserver since I dont have access to a real server..
private static final String LOGIN_URL = "http://http://127.0.0.1/webservice/register.php";
// Creating ids for messages...
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
// Creating the onCreate method...
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// getting references for the username,password and the button elements
user = (EditText) findViewById(R.id.get_username);
pass = (EditText) findViewById(R.id.get_password);
register = (Button) findViewById(R.id.submit);
// Creating onClickListener for the button...
register.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// getting method for create new user...
new CreateUser().execute();
Intent intent = new Intent(this, Usersuccess.class);
}
// Creating a new class called CreateUser...
class CreateUser extends AsyncTask<String, String, String>{
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("username", username));
params1.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonparser.makeHttpRequest(
LOGIN_URL, "POST", params1);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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 product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Login.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
//Creating the class that extends the Activity class
public class LoginScreen extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
Button Signup = (Button) findViewById(R.id.signup);
Signup.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// Creating intent for Signup process..
Intent i = new Intent(LoginScreen.this,Register.class);
startActivity(i);
}
}
这是我的日志:
10-31 12:45:28.441: D/request!(359): starting
10-31 12:45:30.041: W/System.err(359): java.net.UnknownHostException: http
10-31 12:45:30.041: W/System.err(359): at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
10-31 12:45:30.051: W/System.err(359): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
10-31 12:45:30.051: W/System.err(359): at java.net.InetAddress.getAllByName(InetAddress.java:256)
10-31 12:45:30.051: W/System.err(359): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
10-31 12:45:30.051: W/System.err(359): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10-31 12:45:30.061: W/System.err(359): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
10-31 12:45:30.061: W/System.err(359): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
10-31 12:45:30.071: W/System.err(359): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-31 12:45:30.071: W/System.err(359): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-31 12:45:30.080: W/System.err(359): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-31 12:45:30.080: W/System.err(359): at com.augustasoftsol.gmoapp.JSONParser.makeHttpRequest(JSONParser.java:96)
10-31 12:45:30.080: W/System.err(359): at com.augustasoftsol.gmoapp.Register$CreateUser.doInBackground(Register.java:99)
10-31 12:45:30.080: W/System.err(359): at com.augustasoftsol.gmoapp.Register$CreateUser.doInBackground(Register.java:1)
10-31 12:45:30.091: W/System.err(359): at android.os.AsyncTask$2.call(AsyncTask.java:185)
10-31 12:45:30.101: W/System.err(359): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
10-31 12:45:30.101: W/System.err(359): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
10-31 12:45:30.101: W/System.err(359): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
10-31 12:45:30.132: W/System.err(359): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
10-31 12:45:30.132: W/System.err(359): at java.lang.Thread.run(Thread.java:1019)
10-31 12:45:30.132: E/Buffer Error(359): Error converting result java.lang.NullPointerException
10-31 12:45:30.141: E/JSON Parser(359): Error parsing data org.json.JSONException: End of input at character 0 of
10-31 12:45:30.151: W/dalvikvm(359): threadid=9: thread exiting with uncaught exception (group=0x40015560)
10-31 12:45:30.171: E/AndroidRuntime(359): FATAL EXCEPTION: AsyncTask #1
10-31 12:45:30.171: E/AndroidRuntime(359): java.lang.RuntimeException: An error occured while executing doInBackground()
10-31 12:45:30.171: E/AndroidRuntime(359): at android.os.AsyncTask$3.done(AsyncTask.java:200)
10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
10-31 12:45:30.171: E/AndroidRuntime(359): at java.lang.Thread.run(Thread.java:1019)
10-31 12:45:30.171: E/AndroidRuntime(359): Caused by: java.lang.NullPointerException
10-31 12:45:30.171: E/AndroidRuntime(359): at com.augustasoftsol.gmoapp.Register$CreateUser.doInBackground(Register.java:103)
10-31 12:45:30.171: E/AndroidRuntime(359): at com.augustasoftsol.gmoapp.Register$CreateUser.doInBackground(Register.java:1)
10-31 12:45:30.171: E/AndroidRuntime(359): at android.os.AsyncTask$2.call(AsyncTask.java:185)
10-31 12:45:30.171: E/AndroidRuntime(359): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
10-31 12:45:30.171: E/AndroidRuntime(359): ... 4 more
10-31 12:45:32.121: E/WindowManager(359): Activity com.augustasoftsol.gmoapp.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405a3fe0 that was originally added here
10-31 12:45:32.121: E/WindowManager(359): android.view.WindowLeaked: Activity com.augustasoftsol.gmoapp.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405a3fe0 that was originally added here
10-31 12:45:32.121: E/WindowManager(359): at android.view.ViewRoot.<init>(ViewRoot.java:258)
10-31 12:45:32.121: E/WindowManager(359): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
10-31 12:45:32.121: E/WindowManager(359): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
10-31 12:45:32.121: E/WindowManager(359): at android.view.Window$LocalWindowManager.addView(Window.java:424)
10-31 12:45:32.121: E/WindowManager(359): at android.app.Dialog.show(Dialog.java:241)
10-31 12:45:32.121: E/WindowManager(359): at com.augustasoftsol.gmoapp.Register$CreateUser.onPreExecute(Register.java:82)
10-31 12:45:32.121: E/WindowManager(359): at android.os.AsyncTask.execute(AsyncTask.java:391)
10-31 12:45:32.121: E/WindowManager(359): at com.augustasoftsol.gmoapp.Register.onClick(Register.java:63)
10-31 12:45:32.121: E/WindowManager(359): at android.view.View.performClick(View.java:2485)
10-31 12:45:32.121: E/WindowManager(359): at android.view.View$PerformClick.run(View.java:9080)
10-31 12:45:32.121: E/WindowManager(359): at android.os.Handler.handleCallback(Handler.java:587)
10-31 12:45:32.121: E/WindowManager(359): at android.os.Handler.dispatchMessage(Handler.java:92)
10-31 12:45:32.121: E/WindowManager(359): at android.os.Looper.loop(Looper.java:123)
10-31 12:45:32.121: E/WindowManager(359): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-31 12:45:32.121: E/WindowManager(359): at java.lang.reflect.Method.invokeNative(Native Method)
10-31 12:45:32.121: E/WindowManager(359): at java.lang.reflect.Method.invoke(Method.java:507)
10-31 12:45:32.121: E/WindowManager(359): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-31 12:45:32.121: E/WindowManager(359): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-31 12:45:32.121: E/WindowManager(359): at dalvik.system.NativeStart.main(Native Method)
10-31 12:45:35.381: I/Process(359): Sending signal. PID: 359 SIG: 9
最佳答案
使用本地服务器并在模拟器上进行测试时
采用,
private static final String LOGIN_URL = "http://10.0.2.2/webservice/register.php";
并且,如果您要在真实设备上测试应用程序,请使用承载本地服务器的计算机的IP。
希望对您有所帮助!
关于java - 转换结果java.lang.NullPointerException时出错,并且解析数据org.json.JSONException时出错:在字符0的输入结束,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26669801/