2014-12-29 2 views
-2

Я создаю простое приложение, которое будет принимать данные от пользователя для регистрации, а затем разрешить пользователям входить в систему.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 решения, изложенные здесь, ничего не работали, это нетронутая версия.

+0

Где ваш код 'Регистрация Actvity'? –

+1

понятно, почему ... login (View) должен быть методом в текущей деятельности ... нет связи между activity_login.xml и java class ... – Selvin

+0

@Selvin вы могли бы рассказать мне, как его решить в ответ? Я действительно новичок в андроиде, и это мое первое приложение. –

ответ

1

Это окончательное решение:

activity_login.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" 
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Login"> 

    <TextView android:text="Login to Control Panel" android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/login_text" 
     android:textSize="20dp" 
     android:layout_alignRight="@+id/login_username" 
     android:layout_alignEnd="@+id/login_username" 
     android:layout_alignLeft="@+id/login_username" 
     android:layout_alignStart="@+id/login_username" /> 

    <Button 
     style="?android:attr/buttonStyleSmall" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Login" 
     android:id="@+id/login_button" 
     android:layout_alignParentBottom="true"/> 

    <Button 
     style="?android:attr/buttonStyleSmall" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Signup" 
     android:id="@+id/signup_button" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentEnd="true" /> 

    <EditText 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/login_username" 
     android:hint="Username" 
     android:layout_above="@+id/login_password" 
     android:layout_alignLeft="@+id/login_password" 
     android:layout_alignStart="@+id/login_password" 
     android:layout_toLeftOf="@+id/signup_button" 
     android:layout_toStartOf="@+id/signup_button" /> 

    <EditText 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:inputType="textPassword" 
     android:ems="10" 
     android:id="@+id/login_password" 
     android:hint="Password" 
     android:layout_centerVertical="true" 
     android:layout_centerHorizontal="true" /> 

</RelativeLayout> 

Login.java

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); 
      } 
     }); 

     /* 
      - TIP - 

      Try always to do as the following instead of call a method into the xml; because you have 
      more control of which xml is being called right here 
     */ 
     final Button btLogin = (Button) findViewById(R.id.login_button); 
     btLogin.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Intent act2 = new Intent(view.getContext(), Signup.class); 
       startActivity(act2); 
      } 
     }); 


    } 

    //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); 
    } 

} 

activity_signup.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" 
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    tools:context="in.techbreeze.android.cake.Signup"> 

    <TextView android:text="Enter details to signup" android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/signup_text" /> 

    <Button 
     style="?android:attr/buttonStyleSmall" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Back" 
     android:id="@+id/back_button" 
     android:layout_marginBottom="71dp" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentEnd="true" 
     android:layout_marginRight="71dp" 
     android:layout_marginEnd="71dp" /> 

    <EditText 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/signup_username" 
     android:layout_marginTop="92dp" 
     android:hint="Username" 
     android:layout_below="@+id/signup_text" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:layout_alignRight="@+id/signup_password" 
     android:layout_alignEnd="@+id/signup_password" /> 

    <EditText 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:inputType="textPassword" 
     android:ems="10" 
     android:id="@+id/signup_password" 
     android:layout_below="@+id/signup_username" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:hint="Password" /> 

    <EditText 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:inputType="textPassword" 
     android:ems="10" 
     android:id="@+id/signup_cpassword" 
     android:layout_below="@+id/signup_password" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:hint="Confirm Password" /> 

    <EditText 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:inputType="textEmailAddress" 
     android:ems="10" 
     android:id="@+id/signup_email" 
     android:layout_below="@+id/signup_cpassword" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:hint="Email" /> 

    <EditText 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:inputType="phone" 
     android:ems="10" 
     android:id="@+id/signup_phone" 
     android:layout_below="@+id/signup_email" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:hint="Phone Number" /> 

    <Button 
     style="?android:attr/buttonStyleSmall" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Singup" 
     android:id="@+id/signup_button" 
     android:layout_above="@+id/back_button" 
     android:layout_alignRight="@+id/back_button" 
     android:layout_alignEnd="@+id/back_button"/> 

</RelativeLayout> 

Регистрация.Java

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); 

    /* 
     - TIP - 

     finish(); instead of Intent act2 = new Intent(view.getContext(), Login.class); 
      startActivity(act2); 

     When you call startActivity you call another activity and don't back to the last activity. For this, you 
     have to use finish() instead. 

    */ 
    final Button switchlogin = (Button) findViewById(R.id.back_button); 
    switchlogin.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      finish(); 
     } 
    }); 

    /* 
     - TIP - 

     It's like the Login.java TIP 

     Try always to do as the following instead of call a method into the xml; because you have 
     more control of which xml is being called right here 
    */ 
    final Button btSignup = (Button) findViewById(R.id.signup_button); 
    btSignup.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      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(); 

     /* 
      - TIP - 

      finish() instead of setContentView(R.layout.activity_login) 

      You have to finalize the activity instead of set another content or call startActivity to back. 

      You cannot do like you did here(setContentView(R.layout.activity_login)); because doing it you just change the xml and 
      not change the activity, so causing the error that you posted 
     */ 
     finish(); 

    } 
} 

//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); 
} 

}

Есть несколько советов, которые я добавил в код; вы можете найти их поиск по TIP

+0

попробовал это по-своему но теперь ничего не происходит, когда я нажимаю кнопку входа в систему после переадресации страницы регистрации на вход. –

+0

Вы завершаете Singup.class? Где метод Post()? –

+0

Вы хотите, чтобы я опубликовал полный код signup.java? –

1

Прежде всего его преступник свяжет ваши функции в xml.

Во-вторых, вид, который содержит кнопку входа в систему i.e activity_login.xml), похоже, ищет функцию входа в класс Registration. Таким образом, вы получите возможность удалить :onClick из функции xml и привязать ее к соответствующему классу ... i.e Войдите в систему , и вам стоит хорошо.

+0

попробовала, но на этот раз нажатие кнопки входа в систему после перенаправления со страницы регистрации ничего не делает –

Смежные вопросы