Я создаю простое приложение, которое будет принимать данные от пользователя для регистрации, а затем разрешить пользователям входить в систему.Android-приложение ведет себя странно
По умолчанию макет приложения - это логин, в котором вы можете зарегистрироваться или войти в систему.
Если пользователь уже имеет имя пользователя и пытается войти в систему, приложение работает так, как ожидалось, и после проверки открывается страница приветствия.
Однако при нажатии кнопки регистрации открывается раскрывающаяся страница, где пользователь может ввести данные для регистрации, а затем нажать кнопку регистрации.
При успешном создании нового пользователя и его переадресации на страницу входа в систему.
Проблема возникает, когда я пытаюсь войти в систему после того, как я был перенаправлен со страницы регистрации на страницу входа.
Я получаю следующую ошибку, и страница входа в систему перезагружается сама по себе.
12-29 17:20:02.327 5823-5823/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: in.techbreeze.android.cake, PID: 5823
java.lang.IllegalStateException: Could not find a method login(View) in the activity class in.techbreeze.android.cake.Signup for onClick handler on view class android.widget.Button with id 'login_button'
at android.view.View$1.onClick(View.java:3815)
at android.view.View.performClick(View.java:4443)
at android.view.View$PerformClick.run(View.java:18433)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5021)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoSuchMethodException: login [class android.view.View]
at java.lang.Class.getConstructorOrMethod(Class.java:472)
at java.lang.Class.getMethod(Class.java:857)
at android.view.View$1.onClick(View.java:3808)
at android.view.View.performClick(View.java:4443)
at android.view.View$PerformClick.run(View.java:18433)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5021)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
at dalvik.system.NativeStart.main(Native Method)
Как вы можете видеть, он ищет OnClick обработчик login
в signup.java
файл вместо файла login.java
. Почему это происходит?
Это login.java
файл кода
package in.techbreeze.android.cake;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
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.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class Login extends ActionBarActivity {
EditText login_username, login_password;
String uname, pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login_username = (EditText) findViewById(R.id.login_username);
login_password = (EditText) findViewById(R.id.login_password);
final Button switchsignup = (Button) findViewById(R.id.signup_button);
switchsignup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent act2 = new Intent(view.getContext(), Signup.class);
startActivity(act2);
}
});
}
public void login(View v) {
try{
// CALL post method to make post method call
post();
}
catch(Exception ex)
{
String error = ex.getMessage();
}
}
//Method to get list value pair and form the query
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
//Method to post data to webservice
public void post() throws UnsupportedEncodingException
{
try
{
// Calling async task to get json
new DownloadOperation().execute();
}
catch (Exception e) {
e.printStackTrace();
}
}
//Handle popout messages
public void error(boolean flag, String etext) {
if (flag == true) {
Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
//Code to handle failure
login_username.setText("");
login_password.setText("");
} else {
Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_welcome);
}
}
//Asynctask
private class DownloadOperation extends AsyncTask<Void, Void, String> {
String uname = "";
String pass = "";
ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
uname = login_username.getText().toString();
pass = login_password.getText().toString();
//Initiate ProgressBar
dialog = ProgressDialog.show(Login.this, "Please Wait", "Loggin you in ...");
}
@Override
protected String doInBackground(Void... params) {
String response = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://rgbpallete.in/led/api/login");
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
return response;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
dialog.dismiss();
Log.d("tag", "Result:\n" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String message = jsonObj.getString("message");
boolean error = jsonObj.getBoolean("error");
error(error,message);
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Это код signup.java
файл
package in.techbreeze.android.cake;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
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.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class Signup extends ActionBarActivity {
EditText signup_username, signup_password, signup_cpassword, signup_email, signup_phone;
String pass, cpass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
signup_username = (EditText) findViewById(R.id.signup_username);
signup_password = (EditText) findViewById(R.id.signup_password);
signup_cpassword = (EditText) findViewById(R.id.signup_cpassword);
signup_email = (EditText) findViewById(R.id.signup_email);
signup_phone = (EditText) findViewById(R.id.signup_phone);
final Button switchlogin = (Button) findViewById(R.id.back_button);
switchlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent act2 = new Intent(view.getContext(), Login.class);
startActivity(act2);
}
});
}
public void signup(View v) {
try{
pass = signup_password.getText().toString();
cpass = signup_cpassword.getText().toString();
if(pass.equals(cpass))
{
// CALL post method to make post method call
post();
}
else
{
Toast.makeText(getBaseContext(), "Passwords mismatch", Toast.LENGTH_SHORT).show();
signup_password.setText("");
signup_cpassword.setText("");
}
}
catch(Exception ex)
{
String error = ex.getMessage();
}
}
//Method to get list value pair and form the query
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
//Method to post data to webservice
public void post() throws UnsupportedEncodingException
{
try
{
// Calling async task to get json
new DownloadOperation().execute();
}
catch (Exception e) {
e.printStackTrace();
}
}
//Handle popout messages
public void error(boolean flag, String etext) {
if (flag == true) {
Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
//Code to handle failure
signup_username.setText("");
signup_password.setText("");
signup_cpassword.setText("");
signup_email.setText("");
signup_phone.setText("");
} else {
Toast.makeText(getBaseContext(), etext, Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_login);
}
}
//Asynctask
private class DownloadOperation extends AsyncTask<Void, Void, String> {
String uname, pass, cpass, email, phone;
ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
uname = signup_username.getText().toString();
pass = signup_password.getText().toString();
cpass = signup_cpassword.getText().toString();
email = signup_email.getText().toString();
phone=signup_phone.getText().toString();
//Initiate ProgressBar
dialog = ProgressDialog.show(Signup.this, "Please Wait", "Signing you up ...");
}
@Override
protected String doInBackground(Void... params) {
String response = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://rgbpallete.in/led/api/signup");
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
return response;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
dialog.dismiss();
Log.d("tag", "Result:\n" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String message = jsonObj.getString("message");
boolean error = jsonObj.getBoolean("error");
error(error,message);
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_signup, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Это место, где Вы можете загрузить проект из http://www21.zippyshare.com/v/88368638/file.html
PS: Я implimented решения, изложенные здесь, ничего не работали, это нетронутая версия.
Где ваш код 'Регистрация Actvity'? –
понятно, почему ... login (View) должен быть методом в текущей деятельности ... нет связи между activity_login.xml и java class ... – Selvin
@Selvin вы могли бы рассказать мне, как его решить в ответ? Я действительно новичок в андроиде, и это мое первое приложение. –