Привет всем, я пытаюсь создать простое действие входа в систему, которое будет аутентифицировать пользователя из базы данных MySql с помощью php …. У меня есть ошибки, которые я не могу решить … пожалуйста, кто-нибудь, помогите мне
Вот основной код активности
public class MainActivity extends Activity {
private static final String LOGIN_URL = "http://servername.com/mypath/Login.php";
EditText un , pas;
Button ok;
ProgressDialog prog;JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Idintify();
ok.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new ToLogin().execute();
}
});
}public void Idintify(){
un = (EditText)findViewById(R.id.Un);
pas = (EditText)findViewById(R.id.Pas);
ok = (Button)findViewById(R.id.ok);
}class ToLogin extends AsyncTask<String, String, String>{boolean failure = false;
@Override protected void onPreExecute() {
super.onPreExecute();
prog = new ProgressDialog(MainActivity.this);
prog.setMessage("Login wait ...");
prog.setIndeterminate(false);
prog.setCancelable(true);
prog.show();
}@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub//int success;
int sucess;
String username = un.getText().toString();
String password = pas.getText().toString();try {
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("username", username));
param.add(new BasicNameValuePair("password", password));Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL,"POST", param);
Log.d("Login attempt", json.toString());
sucess = json.getInt(TAG_SUCCESS);
if (sucess == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(MainActivity.this, Notifications.class);
finish();
startActivity(i);
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;
}protected void onPostExecute(String message) {
prog.dismiss();
if (message != null){
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
}}@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
и это JSONParser.java
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
try {
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
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;
}
и это мой код PHP
введите описание изображения здесь
Мои ошибки Logcat
02-28 20:10:48.132: D/Login attempt(2476): {"message":"You have been sucessfully login","success":1}
02-28 20:10:48.132: D/Login Successful!(2476): {"message":"You have been sucessfully login","success":1}
02-28 20:10:48.852: I/Choreographer(2476): Skipped 43 frames! The application may be doing too much work on its main thread.
02-28 20:10:48.952: W/dalvikvm(2476): threadid=14: thread exiting with uncaught exception (group=0x40a71930)
02-28 20:10:50.375: I/Choreographer(2476): Skipped 35 frames! The application may be doing too much work on its main thread.
02-28 20:10:51.852: W/IInputConnectionWrapper(2476): showStatusIcon on inactive InputConnection
02-28 20:10:53.295: E/AndroidRuntime(2476): FATAL EXCEPTION: AsyncTask #4
02-28 20:10:53.295: E/AndroidRuntime(2476): java.lang.RuntimeException: An error occured while executing doInBackground()
02-28 20:10:53.295: E/AndroidRuntime(2476): at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-28 20:10:53.295: E/AndroidRuntime(2476): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-28 20:10:53.295: E/AndroidRuntime(2476): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-28 20:10:53.295: E/AndroidRuntime(2476): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-28 20:10:53.295: E/AndroidRuntime(2476): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-28 20:10:53.295: E/AndroidRuntime(2476): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-28 20:10:53.295: E/AndroidRuntime(2476): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-28 20:10:53.295: E/AndroidRuntime(2476): at java.lang.Thread.run(Thread.java:856)
02-28 20:10:53.295: E/AndroidRuntime(2476): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.tst/com.example.tst.Notifications}; have you declared this activity in your AndroidManifest.xml?
02-28 20:10:53.295: E/AndroidRuntime(2476): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1618)
02-28 20:10:53.295: E/AndroidRuntime(2476): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1417)
02-28 20:10:53.295: E/AndroidRuntime(2476): at android.app.Activity.startActivityForResult(Activity.java:3370)
02-28 20:10:53.295: E/AndroidRuntime(2476): at android.app.Activity.startActivityForResult(Activity.java:3331)
02-28 20:10:53.295: E/AndroidRuntime(2476): at android.app.Activity.startActivity(Activity.java:3566)
02-28 20:10:53.295: E/AndroidRuntime(2476): at android.app.Activity.startActivity(Activity.java:3534)
02-28 20:10:53.295: E/AndroidRuntime(2476): at com.example.tst.MainActivity$ToLogin.doInBackground(MainActivity.java:114)
02-28 20:10:53.295: E/AndroidRuntime(2476): at com.example.tst.MainActivity$ToLogin.doInBackground(MainActivity.java:1)
02-28 20:10:53.295: E/AndroidRuntime(2476): at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-28 20:10:53.295: E/AndroidRuntime(2476): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-28 20:10:53.295: E/AndroidRuntime(2476): ... 4 more
02-28 20:10:54.352: E/WindowManager(2476): Activity com.example.tst.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d1d988 V.E..... R.....ID 0,0-640,128} that was originally added here
02-28 20:10:54.352: E/WindowManager(2476): android.view.WindowLeaked: Activity com.example.tst.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40d1d988 V.E..... R.....ID 0,0-640,128} that was originally added here
02-28 20:10:54.352: E/WindowManager(2476): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
02-28 20:10:54.352: E/WindowManager(2476): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
02-28 20:10:54.352: E/WindowManager(2476): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
02-28 20:10:54.352: E/WindowManager(2476): at android.app.Dialog.show(Dialog.java:281)
02-28 20:10:54.352: E/WindowManager(2476): at com.example.tst.MainActivity$ToLogin.onPreExecute(MainActivity.java:73)
02-28 20:10:54.352: E/WindowManager(2476): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
02-28 20:10:54.352: E/WindowManager(2476): at android.os.AsyncTask.execute(AsyncTask.java:534)
02-28 20:10:54.352: E/WindowManager(2476): at com.example.tst.MainActivity$1.onClick(MainActivity.java:48)
02-28 20:10:54.352: E/WindowManager(2476): at android.view.View.performClick(View.java:4204)
02-28 20:10:54.352: E/WindowManager(2476): at android.view.View$PerformClick.run(View.java:17355)
02-28 20:10:54.352: E/WindowManager(2476): at android.os.Handler.handleCallback(Handler.java:725)
02-28 20:10:54.352: E/WindowManager(2476): at android.os.Handler.dispatchMessage(Handler.java:92)
02-28 20:10:54.352: E/WindowManager(2476): at android.os.Looper.loop(Looper.java:137)
02-28 20:10:54.352: E/WindowManager(2476): at android.app.ActivityThread.main(ActivityThread.java:5041)
02-28 20:10:54.352: E/WindowManager(2476): at java.lang.reflect.Method.invokeNative(Native Method)
02-28 20:10:54.352: E/WindowManager(2476): at java.lang.reflect.Method.invoke(Method.java:511)
02-28 20:10:54.352: E/WindowManager(2476): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-28 20:10:54.352: E/WindowManager(2476): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-28 20:10:54.352: E/WindowManager(2476): at dalvik.system.NativeStart.main(Native Method)
Важная строка здесь:
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.tst/com.example.tst.Notifications}; have you declared this activity in your AndroidManifest.xml?
Эта ошибка означает, что действие, которое вы пытаетесь выполнить после входа в систему, не существует.
Проблема здесь:
if (sucess == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(MainActivity.this, Notifications.class);
MainActivity.this.finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}
Убедитесь, что ваша целевая активность называется Уведомления, и она объявлена в вашем AndroidManifest.xml
Надеюсь, поможет!!!
не перемещайте активность в методе dobackground (). Измените код, помещенный в onPostExecute (), а не в конец () первым startActivity (i) после finsih (), как в следующем коде
if (success == 1)
{
Log.d("Login Successful!", json.toString());
Intent i = new Intent(MainActivity.this, Notifications.class);
startActivity(i);
finish();
}
else
{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
}