AsyncTask seems not to proceed to onPre/PostExecute() - android

I have this class WelcomeActivity and backgroundLogin which does a login sequence. I have my username and password editbox on the WelcomeActivity and then the login button is pressed I proceeds to the backgroungLogin to connect to the database and then compare the values of the available entries.
WelcomeActivity:
package com.a000webhostapp.cbhtermitecontrol.termitecontrol;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WelcomeActivity extends AppCompatActivity{
Button loginButton;
EditText userText, codeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
loginButton = (Button) findViewById(R.id.loginButtonXML);
userText = (EditText) findViewById(R.id.userTextXML);
codeText = (EditText) findViewById(R.id.codeTextXML);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = userText.getText().toString();
String password = codeText.getText().toString();
String type = "login";
backgroundLogin backgroundLogin = new backgroundLogin(WelcomeActivity.this);
backgroundLogin.execute(type, username, password);
}
});
}
public void onLogin(View view){
String username = userText.getText().toString();
String password = codeText.getText().toString();
String type = "login";
backgroundLogin backgroundLogin = new backgroundLogin(this);
backgroundLogin.execute(type, username, password);
}
}
backgroundActivity:
package com.a000webhostapp.cbhtermitecontrol.termitecontrol;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.speech.tts.Voice;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class backgroundLogin extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
backgroundLogin (Context ctx){
this.context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "https://cbhtermitecontrol.000webhostapp.com/android/loginA2DB.php";
if(type.equals("login"))
try {
String username = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(username, "UTF-8")+"&"
+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line;
while ((line = bufferedReader.readLine())!=null){
result+=line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
There are my code, however when I pressed the login button the onPre/PostExecute seem not working. Looking in the Run App Logs in Android Studio the only feed back I got after pressing the login button is this
D/libc: [NET] android_getaddrinfo_proxy get netid:0
D/libc: [NET] android_getaddrinfo_proxy-, success

Make sure to call
alertDialog.show();
In both onPreExecute and onPostExecute

Related

Android studio problems login validation

So I've been cracking my brain with this issues. I'm trying to validate if the an user credentials on a app connected to mysql are valid. The thing is that wherever I try to compare the result of the query with a string all I get is the else statement.
Here's the Fragment for the Login
package com.example.pablorjd.CheckThisOut;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Login extends AppCompatActivity {
EditText etUsername;
EditText etPassword;
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etUsername = (EditText)findViewById(R.id.etUsername);
etPassword = (EditText)findViewById(R.id.etPassword);
btnLogin = (Button)findViewById(R.id.btnLogin);
}
public void onLogin(View view){
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type,username,password);
}
}
I'm using a background class to make the connection to mysql
package com.example.pablorjd.CheckThisOut;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://10.20.13.31/checkthisout/login.php";
if (type.equals("login")){
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine())!=null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String result) {
if (result.equals("true")){
Toast.makeText(context, "If is working", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,result, Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
I know the DB connections is working because I'm actually receiving the message that I set on the php file.
All I know is that for some reason the if statement is not working for this.
please if someone could shed a light for me that'd be great.
OK so, for some reason, the validation just wouldn't take the string comparison and instead jumped to the else statement showing in this case a Toast. What I had to do was to modify the string given to me by the php file so it would be just a number (0 or 1 in this case). then I parsed the string into an int and the if worked like a charm.
This is the resulting code
#Override
protected void onPostExecute(String result) {
int val = Integer.parseInt(result.replaceAll("[\\D]",""));
if (val == 0){
Intent intent = new Intent(context,MainActivity.class);
context.startActivity(intent);
Toast.makeText(context,"Login exitoso",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"Login erroneo",Toast.LENGTH_SHORT).show();
}
}
I still don't know why the if statement wouldn't work with strings.

Class 'SigninActivity' must either be declared abstract or implement abstract method 'doInBackground(Params...)' in 'AsyncTask'

Main Activity :
package com.example.phpmysql;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText usernameField,passwordField;
private TextView status,role,method;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
new SigninActivity(this,status,role,1).execute(username,password);
}
}
SigninActivity:
package com.example.phpmysql;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;
public class SigninActivity extends AsyncTask{
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,TextView
roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://myphpmysqlweb.hostei.com/login.php?username="+username+"& password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
} else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://myphpmysqlweb.hostei.com/loginpost.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" +
URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" +
URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
}
}
The public class SigninActivity extends AsyncTask is shown in red underline saying Class SigninActivity must either be declared abstract or implement abstract method doInBackground(Params...) in AsyncTask?
I tried adding the doInBackground but it says that it is never used?
I tried making it adbstract but then i could not call the class from mainactivity
You need to provide the generic parameters as
public class SigninActivity extends AsyncTask<String, Void, String>
otherwise the parameter type will be of raw-type and signature won't match

how to call method in login page

i'm currently trying to make a validation for a login page, which is to validate whether the account is in my database or not, i'm to call the method of invokelogin(), but it seems but i don't know how to call the method, need some help with it.
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class Activity_Login extends Activity{
private Button btnSignIn;
String username;
String pass;
public static final String USER_NAME = "USERNAME";
EditText txtUser;
EditText Pass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnSignIn = (Button) findViewById(R.id.btnSignIn);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchActivity3();
}
});
}
public void launchActivity3() {
txtUser = (EditText) findViewById(R.id.txtUser);
Pass = (EditText) findViewById(R.id.txtPass);
if (txtUser.getText().toString().equals("")) {
Toast.makeText(Activity_Login.this, "UserName must Be Filled", Toast.LENGTH_SHORT).show();
} else if (Pass.getText().toString().equals("")) {
Toast.makeText(Activity_Login.this, "Password must be Filled", Toast.LENGTH_SHORT).show();
} else {
invokeLogin();
}
Intent intent_SignIn = new Intent(Activity_Login.this, Activity_Drawer2.class);
startActivity(intent_SignIn);
}
public void invokeLogin(View view){
username = txtUser.getText().toString();
pass = Pass.getText().toString();
login(username,pass);
}
private void login (final String username, String pass){
class LoginAsync extends AsyncTask<String, Void, String> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(Activity_Login.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
String result = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.10.1.11/login.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
String s = result.trim();
loadingDialog.dismiss();
if (s.equalsIgnoreCase("success")) {
Intent intent = new Intent(Activity_Login.this, Activity_Drawer2.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, pass);
}
}
You can pass txtUser and Pass to invokeLogin();
so it look like invokeLogin(txtUser,Pass);
Then your invokeLogin method
public void invokeLogin(String username, String pass){
login(username,pass);
}

Intent in android error

Everyone i'm getting error while using Intent in android. I have a MainActivity from where i call another class called BackgroundWorker so after doing some functions of login i want to go to user page if it is a sucesss.enter code here im attaching my code here Please help
package com.example.user.mybookapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText UsernameEt, PasswordEt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsernameEt = (EditText) findViewById(R.id.etusername);
PasswordEt = (EditText) findViewById(R.id.etpassword);
}
public void OnLogin(View view) {
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type,username,password);
}
}
//BackgoundWorker class
package com.example.user.mybookapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by user on 15-09-2016.
*/
public class BackgroundWorker extends AsyncTask<String,Void,String> {
public Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String[] params)
{
String type = params[0];
String login_url = "http://192.168.4.2/login.php";
if(type.equals("login"))
{
try {
//Context context = getApplicationContext();
//Toast t= Toast.makeText(ctx,"click",Toast.LENGTH_SHORT).show();
//alertDialog = new AlertDialog.Builder(context).create();
//alertDialog.setTitle("login status");
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode(password,"UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!=null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("login status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
String s=result.trim();
if (s.equalsIgnoreCase("success")){
Intent i =Intent(BackgroundWorker.this,User.class);//Problem
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Intent i =Intent(context,User.class);
This should fix the error, intent should be called using current context.
Intent i =Intent(context,User.class);
context.startActivity(i);
This will work as BackgroundWorker.this is a non activity reference.
Intent intent = new Intent(mContext,SecondClass.class);
intent.putExtra("KEY","Value");
startActivity(intent);
//here KEY = the identifier of specific value
//on other side of SecondClass Activity. catch this data using
String res = getIntent().getStringExtra("KEY");
Intent constructor needs a context as first parameter and you are giving it AsyncTask. You are not constructing object of Intent class properly, in other words you have forgotten to write new keyword.This is the syntax to create a object:-
<Class> <objectName> = new <Class/Subclass>(constructor_params_separated_by_commas);
Intent i =Intent(BackgroundWorker.this,User.class);//Problem
change it to
Intent i =new Intent(context,User.class);//Problem solved
context.startActivity(i);
As mentioned in the answers above, first problem is the inappropriate context, second problem is that you are passing wrong arguments in your background worker class while performing background task execution. Your AsyncTask extension:
AsyncTask<String, Void, String>
shows that you must pass String in doInBackground method, while in the code above you are trying to get string Array although you have passed String parameters from your main activity i.e
protected String doInBackground(String[] params)
should be
protected String doInBackground(String... params)
Hope that solves the issue.

Android Studio, app stopped working

I'm new to Android studio.
I follow tutorials on Youtube and Google errors, but this time I cant seem to find how to fix this problem.
I'm creating a simple login-in and register app, that uses a mysql database. When I launch the app and click on the register button the app closes and states: "App stopped working".
I checked out the logcat and found this:
09-13 17:23:19.607 2229-2236/com.example.appname.appname E/art﹕ Failed sending reply to debugger: Broken pipe
09-13 17:23:47.756 2229-2229/com.example.appname.appname E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.appname.appname, PID: 2229
java.lang.IllegalStateException: Could not find method userReg(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.Button
at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4479)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4443)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void userReg()
{
startActivity(new Intent(this, Register.class));
}
public void userLogin(View view)
{
}
}
Register.java
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class Register extends Activity {
EditText ET_NAME,ET_USER_NAME,ET_USER_PASS;
String name,user_name,user_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
ET_NAME = (EditText) findViewById(R.id.name);
ET_USER_NAME = (EditText) findViewById(R.id.new_user_name);
ET_USER_PASS = (EditText) findViewById(R.id.new_user_pass);
}
public void userReg(View view)
{
name = ET_NAME.getText().toString();
user_name = ET_USER_NAME.getText().toString();
user_pass = ET_USER_PASS.getText().toString();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,name,user_name,user_pass);
finish();
}
}
Backgroundtask.java
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx=ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://10.0.2.2.2/webapp/register.php";
String login_url = "http://10.0.2.2.2/webapp/login.php";
String method = params[0];
if(method.equals("register"))
{
String name = params [1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter (new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") +"=" +URLEncoder.encode(name, "UTF-8") + "&"+
URLEncoder.encode("user_name", "UTF-8") +"=" +URLEncoder.encode(user_name, "UTF-8") + "&"+
URLEncoder.encode("user_pass", "UTF-8") +"=" +URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration Success..";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}
}
Change in your Mainactivity.java
public void userReg()
{
startActivity(new Intent(this, Register.class));
}
to
public void userReg(View v)
{
startActivity(new Intent(Mainactivity.this, Register.class));
}
And in Register.java
public void userReg(View view)
{
name = ET_NAME.getText().toString();
user_name = ET_USER_NAME.getText().toString();
user_pass = ET_USER_PASS.getText().toString();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,name,user_name,user_pass);
finish();
}
to
public void userReg(View view)
{
name = ET_NAME.getText().toString();
user_name = ET_USER_NAME.getText().toString();
user_pass = ET_USER_PASS.getText().toString();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(Register.this);
backgroundTask.execute(method,name,user_name,user_pass);
finish();
}
The error appeared because the app couldn't find userReg(View) method that was written in the onClick attribute of your button in xml. You need to add parameter "View" in your method. Simply fix these lines of code:
MainActivity.java
public void userReg() {
startActivity(new Intent(this, Register.class));
}
to
public void userReg(View v) {
startActivity(new Intent(MainActivity.this, Register.class));
}

Categories

Resources