我正在编写一个Android登录应用程序,用于检查用户是否有效,然后如果他是有效用户则启动一个新的Activity。我是Android编程和PHP编码的初学者。但是,当我单击登录按钮时,应用程序崩溃。我正在使用PHP代码。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
login=(Button)findViewById(R.id.id_buttonLogin);
register=(Button)findViewById(R.id.id_buttonSignup);
phone=(EditText)findViewById(R.id.id_phone);
password=(EditText)findViewById(R.id.id_password);
//sPhone=phone.getText().toString();
//sPassword=password.getText().toString();
login.setOnClickListener(this);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent registerOption=new Intent("easy.assign.droid.REGISTRATIONOPTIONACTIVITY");
startActivity(registerOption);
}
});
}
public void onClick(View v)
{
new MyAsyncTask().execute();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
String result = null;
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}//END convertStreamToString()
private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
ProgressDialog pDialog;
@Override
protected void onPostExecute(Void result)
{
pDialog.dismiss();
Intent nextpage=new Intent("easy.assign.droid.HOMESTUDENT");
startActivity(nextpage);
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Loading data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... params)
{
//Create new default HTTPClient
httpclient = new DefaultHttpClient();
//Create new HTTP POST with URL to php file as parameter
httppost = new HttpPost("http://10.0.2.2/project/check.php");
sPhone=phone.getText().toString();
sPassword=password.getText().toString();
//Next block of code needs to be surrounded by try/catch block for it to work
try
{
//Create new Array List
nameValuePairs = new ArrayList<NameValuePair>(2);
//place them in an array list
nameValuePairs.add(new BasicNameValuePair("sPhone", sPhone));
nameValuePairs.add(new BasicNameValuePair("sPassword", sPassword));
//Add array list to http post
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//assign executed form container to response
response = httpclient.execute(httppost); //response from the PHP file
//check status code, need to check status code 200
if(response.getStatusLine().getStatusCode() == 200)
{
//assign response entity to http entity
entity = response.getEntity();
//check if entity is not null
if(entity != null)
{
//Create new input stream with received data assigned
InputStream instream = entity.getContent();
//Create new JSON Object. assign converted data as parameter.
jArray = new JSONArray(convertStreamToString(instream));
JSONObject json_data = null;
String retUser = null, retPass = null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
retUser = json_data.get("sphone").toString();
retPass = json_data.get("spassword").toString();
}
//assign json responses to local strings
//String retUser = jsonResponse.getString("sphone");//mySQL table field
//String retPass = jsonResponse.getString("spassword");
//Validate login
if(sPhone.equals(retUser)&& sPassword.equals(retPass))
{ //Check whether 'retUser' and 'retPass' matches username/password
//Display a Toast saying login was a success
SharedPreferences sp = getSharedPreferences("login details", 0);
SharedPreferences.Editor spedit = sp.edit();
spedit.putString("sPhone", sPhone);
spedit.putString("sPassword", sPassword);
spedit.commit();
//Toast.makeText(getBaseContext(), "Successful", Toast.LENGTH_SHORT).show();
}
else
{
//Display a Toast saying it failed.
Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
//Display toast when there is a connection error
//Change message to something more friendly
//Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();
}
return null;
}
}
}
这是PHP代码:
<?php
$connect = mysqli_connect("localhost","root","","easyassigndroid");
if(mysqli_connect_errno($connect))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "success";
}
$username = isset($_POST['sPhone']) ? $_POST['sPhone'] : '';
$password = isset($_POST['sPassword']) ? $_POST['sPassword'] : '';
$query = mysqli_query($connect, "select * from users where sphone='$username' and spassword='$password' ");
$num = mysqli_num_rows($query);
if($num==1)
{
while($list = mysqli_fetch_assoc($query))
{
$output = $list;
print(json_encode($output));
}
mysqli_close();
}
?>
我得到“org.json.JSONException:类型java.lang.String的值成功无法转换为JSONObject”和“FATAL EXCEPTION”。另外,我在logcat中得到以下异常:
03-31 11:24:43.337: W/System.err(532): org.json.JSONException: Value success of type java.lang.String cannot be converted to JSONObject
03-31 11:24:43.337: W/System.err(532): at org.json.JSON.typeMismatch(JSON.java:111)
03-31 11:24:43.367: W/System.err(532): at org.json.JSONObject.<init>(JSONObject.java:158)
03-31 11:24:43.377: W/System.err(532): at org.json.JSONObject.<init>(JSONObject.java:171)
03-31 11:24:43.377: W/System.err(532): at easy.assign.droid.LoginActivity$MyAsyncTask.doInBackground(LoginActivity.java:160)
03-31 11:24:43.377: W/System.err(532): at easy.assign.droid.LoginActivity$MyAsyncTask.doInBackground(LoginActivity.java:1)
03-31 11:24:43.407: W/System.err(532): at android.os.AsyncTask$2.call(AsyncTask.java:264)
03-31 11:24:43.407: W/System.err(532): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-31 11:24:43.417: W/System.err(532): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-31 11:24:43.417: W/System.err(532): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
03-31 11:24:43.447: W/System.err(532): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-31 11:24:43.447: W/System.err(532): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-31 11:24:43.457: W/System.err(532): at java.lang.Thread.run(Thread.java:856)
03-31 11:24:43.507: W/dalvikvm(532): threadid=11: thread exiting with uncaught exception (group=0x409c01f8)
03-31 11:24:43.617: E/AndroidRuntime(532): FATAL EXCEPTION: AsyncTask #1
03-31 11:24:43.617: E/AndroidRuntime(532): java.lang.RuntimeException: An error occured while executing doInBackground()
03-31 11:24:43.617: E/AndroidRuntime(532): at android.os.AsyncTask$3.done(AsyncTask.java:278)
03-31 11:24:43.617: E/AndroidRuntime(532): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-31 11:24:43.617: E/AndroidRuntime(532): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-31 11:24:43.617: E/AndroidRuntime(532): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-31 11:24:43.617: E/AndroidRuntime(532): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-31 11:24:43.617: E/AndroidRuntime(532): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
03-31 11:24:43.617: E/AndroidRuntime(532): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-31 11:24:43.617: E/AndroidRuntime(532): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-31 11:24:43.617: E/AndroidRuntime(532): at java.lang.Thread.run(Thread.java:856)
03-31 11:24:43.617: E/AndroidRuntime(532): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
03-31 11:24:43.617: E/AndroidRuntime(532): at android.os.Handler.<init>(Handler.java:121)
03-31 11:24:43.617: E/AndroidRuntime(532): at android.widget.Toast$TN.<init>(Toast.java:317)
03-31 11:24:43.617: E/AndroidRuntime(532): at android.widget.Toast.<init>(Toast.java:91)
03-31 11:24:43.617: E/AndroidRuntime(532): at android.widget.Toast.makeText(Toast.java:233)
03-31 11:24:43.617: E/AndroidRuntime(532): at easy.assign.droid.LoginActivity$MyAsyncTask.doInBackground(LoginActivity.java:194)
03-31 11:24:43.617: E/AndroidRuntime(532): at easy.assign.droid.LoginActivity$MyAsyncTask.doInBackground(LoginActivity.java:1)
03-31 11:24:43.617: E/AndroidRuntime(532): at android.os.AsyncTask$2.call(AsyncTask.java:264)
03-31 11:24:43.617: E/AndroidRuntime(532): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-31 11:24:43.617: E/AndroidRuntime(532): ... 5 more
03-31 11:24:44.507: I/dalvikvm(532): threadid=3: reacting to signal 3
03-31 11:24:44.527: I/dalvikvm(532): Wrote stack traces to '/data/anr/traces.txt'
03-31 11:24:44.797: E/WindowManager(532): Activity easy.assign.droid.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@411ddc48 that was originally added here
03-31 11:24:44.797: E/WindowManager(532): android.view.WindowLeaked: Activity easy.assign.droid.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@411ddc48 that was originally added here
03-31 11:24:44.797: E/WindowManager(532): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:344)
03-31 11:24:44.797: E/WindowManager(532): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
03-31 11:24:44.797: E/WindowManager(532): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
03-31 11:24:44.797: E/WindowManager(532): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
03-31 11:24:44.797: E/WindowManager(532): at android.view.Window$LocalWindowManager.addView(Window.java:537)
03-31 11:24:44.797: E/WindowManager(532): at android.app.Dialog.show(Dialog.java:278)
03-31 11:24:44.797: E/WindowManager(532): at android.app.ProgressDialog.show(ProgressDialog.java:116)
03-31 11:24:44.797: E/WindowManager(532): at android.app.ProgressDialog.show(ProgressDialog.java:99)
03-31 11:24:44.797: E/WindowManager(532): at android.app.ProgressDialog.show(ProgressDialog.java:94)
03-31 11:24:44.797: E/WindowManager(532): at easy.assign.droid.LoginActivity$MyAsyncTask.onPreExecute(LoginActivity.java:117)
03-31 11:24:44.797: E/WindowManager(532): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
03-31 11:24:44.797: E/WindowManager(532): at android.os.AsyncTask.execute(AsyncTask.java:511)
03-31 11:24:44.797: E/WindowManager(532): at easy.assign.droid.LoginActivity.onClick(LoginActivity.java:75)
03-31 11:24:44.797: E/WindowManager(532): at android.view.View.performClick(View.java:3511)
03-31 11:24:44.797: E/WindowManager(532): at android.view.View$PerformClick.run(View.java:14105)
03-31 11:24:44.797: E/WindowManager(532): at android.os.Handler.handleCallback(Handler.java:605)
03-31 11:24:44.797: E/WindowManager(532): at android.os.Handler.dispatchMessage(Handler.java:92)
03-31 11:24:44.797: E/WindowManager(532): at android.os.Looper.loop(Looper.java:137)
03-31 11:24:44.797: E/WindowManager(532): at android.app.ActivityThread.main(ActivityThread.java:4424)
03-31 11:24:44.797: E/WindowManager(532): at java.lang.reflect.Method.invokeNative(Native Method)
03-31 11:24:44.797: E/WindowManager(532): at java.lang.reflect.Method.invoke(Method.java:511)
03-31 11:24:44.797: E/WindowManager(532): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-31 11:24:44.797: E/WindowManager(532): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-31 11:24:44.797: E/WindowManager(532): at dalvik.system.NativeStart.main(Native Method)
03-31 11:24:47.237: I/Process(532): Sending signal. PID: 532 SIG: 9
谁能告诉我问题出在哪里?在PHP代码,Android代码或两者兼而有之?我真的需要尽快修复我的项目。任何人都可以帮助我吗?
提前谢谢! :)
答案 0 :(得分:0)
您尝试在Toast
中显示doInBackground()
消息,在runOnUiThread()
中运行此代码
在doInBackground()方法中更改此代码
Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
和这个
sPhone=phone.getText().toString();
sPassword=password.getText().toString();
像这样
runOnUiThread(new Runnable() {
public void run() {
sPhone=phone.getText().toString();
sPassword=password.getText().toString();
}
});
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
}
});
答案 1 :(得分:0)
这可能对您有所帮助
doInBackground
sPhone=phone.getText().toString();
sPassword=password.getText().toString();
你试图从Edittext获取String意味着无法在此处绑定Control并且
Toast like
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
}
});
答案 2 :(得分:-1)
new MyAsyncTask()。execute();
私有类MyAsyncTask扩展了AsyncTask
你必须写
new MyAsyncTask().execute(null,null,null);