为android构建一个简单的注册过程。有这个过程的后端api。作为JSON的数据存储在DB中并获得响应。我想把这个响应作为一个来自main方法的字符串,并根据我编写的代码。但我认为在asynctask上犯了一个错误。作为一个新手,我没有得到这个,可能我的呼吁不是在正确的时间,但无法组织它。所以需要建议。
JsonPostClient.java
public class JsonPostClient {
private static final String TAG = "HttpClient";
public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
Log.i(TAG,"<JSONObject>\n"+jsonObjSend.toString()+"\n</JSONObject>");
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient
.execute(httpPostRequest);
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response
.getFirstHeader("Content-Encoding");
if (contentEncoding != null
&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString = convertStreamToString(instream);
Log.e("ERROR IS", resultString);
instream.close();
JSONObject jsonObjRecv = new JSONObject(resultString);
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return jsonObjRecv;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
我的注册页面。 的 RegisterActivity.java
public class RegisterActivity extends Activity {
String responseResult;
JsonPostClient postData = new JsonPostClient();
private EditText etName, etPassword, etEmail, etPhone, etAddress;
private Button btnReg;
RegInfo person;
JSONObject jsonObject = new JSONObject();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.register);
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
etName = (EditText) findViewById(R.id.reg_fullname);
etEmail = (EditText) findViewById(R.id.reg_email);
etPassword = (EditText) findViewById(R.id.reg_password);
etPhone = (EditText) findViewById(R.id.reg_phone);
etAddress = (EditText) findViewById(R.id.reg_address);
btnReg = (Button) findViewById(R.id.btnRegister);
// using getter setter class
person = new RegInfo();
person.setName(etName.getText().toString());
person.setEmail(etEmail.getText().toString());
person.setPassword(etPassword.getText().toString());
person.setPhone(etPhone.getText().toString());
person.setAddress(etAddress.getText().toString());
// Listening to Login Screen link
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Switching to Login Screen/closing register screen
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
finish();
}
});
// Register button onclick
btnReg.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (!validate())
Toast.makeText(getBaseContext(), "Enter some data!",
Toast.LENGTH_LONG).show();
else {
new HttpAsyncTask().execute();
}
}
});
}
public String PostData(RegInfo person) {
String URL = "http://192.168.1.149/500apps/index.php?r=locShareReg/post";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("user_name", person.getName());
jsonObject.put("password", person.getPassword());
jsonObject.put("email", person.getEmail());
jsonObject.put("phone", person.getPhone());
jsonObject.put("address", person.getAddress());
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject responseReceive = new JSONObject();
responseReceive = JsonPostClient.SendHttpPost(URL, jsonObject);
responseResult = responseReceive.optString("Success");
Log.i("responseResult", responseResult);
return responseResult;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
person = new RegInfo();
person.setName(etName.getText().toString());
person.setEmail(etEmail.getText().toString());
person.setPassword(etPassword.getText().toString());
person.setPhone(etPhone.getText().toString());
person.setAddress(etAddress.getText().toString());
return PostData(person);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG)
.show();
Log.d("response onpost", result);
}
}
private boolean validate() {
if (etName.getText().toString().trim().equals(""))
return false;
else if (etEmail.getText().toString().trim().equals(""))
return false;
else if (etPassword.getText().toString().trim().equals(""))
return false;
else if (etPhone.getText().toString().trim().equals(""))
return false;
else if (etAddress.getText().toString().trim().equals(""))
return false;
else
return true;
}
}
//我发布了 JSONdata
{
"user_name": "Ashif",
"phone": "52527282",
"address": "Gulshan",
"email": "demo@gmail.com",
"password": "123456"
}
我可以在logcat中看到它
//回复
"Success"
此响应显示在JsonPostClient.java中,但我想从RegisterActivity类打印它。所以我做了这个
JSONObject responseReceive = new JSONObject();
responseReceive = JsonPostClient.SendHttpPost(URL, jsonObject);
responseResult = responseReceive.optString("Success");
Log.i("responseResult", responseResult);
但始终显示错误
08-27 12:00:56.631: E/AndroidRuntime(20480): FATAL EXCEPTION: AsyncTask #1
08-27 12:00:56.631: E/AndroidRuntime(20480): java.lang.RuntimeException: An error occured while executing doInBackground()
08-27 12:00:56.631: E/AndroidRuntime(20480): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-27 12:00:56.631: E/AndroidRuntime(20480): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-27 12:00:56.631: E/AndroidRuntime(20480): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-27 12:00:56.631: E/AndroidRuntime(20480): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-27 12:00:56.631: E/AndroidRuntime(20480): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-27 12:00:56.631: E/AndroidRuntime(20480): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-27 12:00:56.631: E/AndroidRuntime(20480): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-27 12:00:56.631: E/AndroidRuntime(20480): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-27 12:00:56.631: E/AndroidRuntime(20480): at java.lang.Thread.run(Thread.java:856)
08-27 12:00:56.631: E/AndroidRuntime(20480): Caused by: java.lang.NullPointerException
08-27 12:00:56.631: E/AndroidRuntime(20480): at com.example.shareapplogregcheck.RegisterActivity.PostData(RegisterActivity.java:132)
08-27 12:00:56.631: E/AndroidRuntime(20480): at com.example.shareapplogregcheck.RegisterActivity$HttpAsyncTask.doInBackground(RegisterActivity.java:151)
08-27 12:00:56.631: E/AndroidRuntime(20480): at com.example.shareapplogregcheck.RegisterActivity$HttpAsyncTask.doInBackground(RegisterActivity.java:1)
08-27 12:00:56.631: E/AndroidRuntime(20480): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-27 12:00:56.631: E/AndroidRuntime(20480): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-27 12:00:56.631: E/AndroidRuntime(20480): ... 5 more
答案 0 :(得分:0)
案例1:
如果您不想在AsyncTask中使用任何doInBackground
,则需要使用HttpAsyncTask
参数更改Void
parameter
。
代码:
@Override
protected String doInBackground(Void... urls) {
...
}
您的错误日志行:
at com.example.shareapplogregcheck.RegisterActivity $ HttpAsyncTask.doInBackground(RegisterActivity.java:1)