【发布时间】:2014-03-06 20:31:11
【问题描述】:
我正在开发一个 android 应用程序,其中主页面、主活动 (MainActivity.java) 包含 8 个按钮。单击任何按钮都会引导我进入下一个活动,即付款活动(PaymentActivity.java)。付款活动是使用我在 MySQL 中创建的数据库(我的表列名称是-1 accno 和 2 bpassword)在 webhost 免费托管下使用正确的帐号和密码验证我的用户。用于连接到我使用 PHP 脚本的虚拟主机服务器。当我输入已经存储在我的 MySQL 数据库中的帐号和密码并单击“支付”按钮时,它应该使用服务器端的 MySQL 数据库对其进行验证,并显示“支付成功”的祝酒词。现在当我运行时模拟器中的这个应用程序...处理到“检查网络加载”,“联系服务器检查凭据”(请参阅 PaymentActivity.java 代码),但在此之后它向我显示“不幸的是 buttonphp(我的应用程序名称)有停了”。我在这里发布我的整个 android 代码。请通过指定我的错误来帮助我,并建议我正确的代码来修复该错误。任何帮助、建议或建议将不胜感激。提前谢谢你!
PaymentActivity.java
package com.example.buttonphp;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.buttonphp.library.DatabaseHandler;
import com.example.buttonphp.library.UserFunctions;
public class PaymentActivity extends Activity {
Button button1;
EditText inputAccno;
EditText inputPassword;
private TextView loginErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_ACCOUNTNO = "accno";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
// Importing all assets like buttons, text fields
inputAccno = (EditText) findViewById(R.id.accountno);
inputPassword = (EditText) findViewById(R.id.password);
button1 = (Button) findViewById(R.id.button1);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if ( ( !inputAccno.getText().toString().equals("")) &&
(!inputPassword.getText().toString().equals("")) )
{
NetAsync(view);
}
else if ( ( !inputAccno.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Password field empty", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputPassword.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Account no field empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),
"Account no and Password fields are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working.
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
@Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(PaymentActivity.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
// private ProgressDialog nDialog;
@Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
@Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessPayment().execute();
}
else{
nDialog.dismiss();
loginErrorMsg.setText(" Error in Network Connection");
}
}
}
/**
* Async Task to get and send data to My Sql database through JSON respone.
**/
private class ProcessPayment extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String accno,bpassword;
@Override
protected void onPreExecute() {
super.onPreExecute();
inputAccno = (EditText) findViewById(R.id.accountno);
inputPassword = (EditText) findViewById(R.id.password);
accno = inputAccno.getText().toString();
bpassword = inputPassword.getText().toString();
pDialog = new ProgressDialog(PaymentActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Checking credentials ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.paymentUser(accno, bpassword);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
pDialog.setMessage("Payment in process");
//pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
*If JSON array details are stored in SQlite it launches the User Panel.
**/
Intent back = new Intent(getApplicationContext(), MainActivity.class);
back.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(back);
/**
* Close Login Screen
**/
finish();
}else{
pDialog.dismiss();
loginErrorMsg.setText("Incorrect account no / password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void NetAsync(View view){
new NetCheck().execute();
}
}
我的 JSONParser.java 文件
package com.example.buttonphp.library;
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.HttpPost;
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, List<NameValuePair> params) {
// Making HTTP request
try {
// 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();
} 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();
Log.e("JSON", json);
} 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;
}
}
Logcat 错误:
03-05 19:47:50.940: D/dalvikvm(2103): GC_FOR_ALLOC freed 48K, 4% free 3228K/3352K,paused
160ms, total 161ms
03-05 19:47:51.840: D/gralloc_goldfish(2103): Emulator without GPU emulation detected.
03-05 19:47:58.500: I/Choreographer(2103): Skipped 55 frames! The application may be
doing too much work on its main thread.
03-05 19:48:02.660: I/Choreographer(2103): Skipped 773 frames! The application may be
doing too much work on its main thread.
03-05 19:48:04.660: I/Choreographer(2103): Skipped 130 frames! The application may be
doing too much work on its main thread.
03-05 19:48:22.660: D/dalvikvm(2103): GC_FOR_ALLOC freed 141K, 6% free 3600K/3816K,
paused 56ms, total 64ms
03-05 19:48:22.870: D/dalvikvm(2103): GC_FOR_ALLOC freed 60K, 7% free 3620K/3872K,
paused 54ms, total 57ms
03-05 19:48:22.890: I/dalvikvm-heap(2103): Grow heap (frag case) to 4.212MB for 635812
byte allocation
03-05 19:48:23.040: D/dalvikvm(2103): GC_FOR_ALLOC freed <1K, 6% free 4240K/4496K,
paused 144ms, total 144ms
03-05 19:49:56.120: D/dalvikvm(2103): GC_FOR_ALLOC freed 319K, 9% free 4424K/4820K,
paused 157ms, total 707ms
03-05 19:51:33.500: I/Choreographer(2103): Skipped 31 frames! The application may be
doing too much work on its main thread.
03-05 19:51:34.370: W/InputEventReceiver(2103): Attempted to finish an input event but
the input event receiver has already been disposed.
03-05 19:51:34.370: I/Choreographer(2103): Skipped 72 frames! The application may be
doing too much work on its main thread.
03-05 19:51:34.990: I/Choreographer(2103): Skipped 154 frames! The application may be
doing too much work on its main thread.
03-05 19:51:37.200: I/Choreographer(2103): Skipped 78 frames! The application may be
doing too much work on its main thread.
03-05 19:51:37.880: I/Choreographer(2103): Skipped 65 frames! The application may be
doing too much work on its main thread.
03-05 19:51:41.090: I/Choreographer(2103): Skipped 31 frames! The application may be
03-05 19:51:41.140: E/JSON(2103): <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2
Final//EN">n<html>n <head>n <title>Index of /payment</title>n </head>n <body>n<h1>Index
of /payment</h1>n<ul><li><a href="/"> Parent Directory</a></li>n<li><a href="includep/">
includep/</a></li>n<li><a href="indexp.php"> indexp.php</a></li>n</ul>n</body></html>n
03-05 19:51:41.200: E/JSON Parser(2103): Error parsing data org.json.JSONException:
Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
03-05 19:51:41.330: I/Choreographer(2103): Skipped 49 frames! The application may be
doing too much work on its main thread.
03-05 19:51:41.470: D/AndroidRuntime(2103): Shutting down VM
03-05 19:51:41.480: W/dalvikvm(2103): threadid=1: thread exiting with uncaught exception
(group=0xb3a49b90)
03-05 19:51:41.610: E/AndroidRuntime(2103): FATAL EXCEPTION: main
03-05 19:51:41.610: E/AndroidRuntime(2103): Process: com.example.buttonphp, PID: 2103
03-05 19:51:41.610: E/AndroidRuntime(2103): java.lang.NullPointerException
03-05 19:51:41.610: E/AndroidRuntime(2103): at com.example.buttonphp.PaymentActivity
$ProcessPayment.onPostExecute(PaymentActivity.java:191)
03-05 19:51:41.610: E/AndroidRuntime(2103): at com.example.buttonphp.PaymentActivity
$ProcessPayment.onPostExecute(PaymentActivity.java:1)
03-05 19:51:41.610: E/AndroidRuntime(2103): at
android.os.AsyncTask.finish(AsyncTask.java:632)
03-05 19:51:41.610: E/AndroidRuntime(2103): at
android.os.AsyncTask.access$600(AsyncTask.java:177)
03-05 19:51:41.610: E/AndroidRuntime(2103): at
android.os.AsyncTask$InternalHandler.handleMessage (AsyncTask.java:645)
03-05 19:51:41.610: E/AndroidRuntime(2103): at
android.os.Handler.dispatchMessage(Handler.java:102)
03-05 19:51:41.610: E/AndroidRuntime(2103): at android.os.Looper.loop(Looper.java:137)
03-05 19:51:41.610: E/AndroidRuntime(2103): at
android.app.ActivityThread.main(ActivityThread.java:4998)
03-05 19:51:41.610: E/AndroidRuntime(2103): at
java.lang.reflect.Method.invokeNative(Native Method)
03-05 19:51:41.610: E/AndroidRuntime(2103): at
java.lang.reflect.Method.invoke(Method.java:515)
03-05 19:51:41.610: E/AndroidRuntime(2103): at com.android.internal.os.ZygoteInit
$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-05 19:51:41.610: E/AndroidRuntime(2103): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-05 19:51:41.610: E/AndroidRuntime(2103): at dalvik.system.NativeStart.main(Native
Method)
03-05 19:51:45.450: D/dalvikvm(2103): GC_FOR_ALLOC freed 401K, 10% free 4573K/5052K,
paused 324ms,total 324ms
【问题讨论】:
-
要分析的代码很多...请尝试仅粘贴相关代码。
-
在应用程序停止时添加带有错误部分的 logcat。你也可能想使用 header('content-type: application/json; charset=utf-8');在 echo json_encode($response); 之前
-
@Merlevede-主要代码是 PaymentActivity.java 文件,我在其中编写了连接性。
-
@Merlevede - 这是编辑后的代码。谢谢。
-
@albertsmuktupavels- 这是编辑后的代码。谢谢。