How to prevent duplicate entry in registration activity with "Username already taken" - java

I would like to include a code such that, when a user registers a username that has already been used in my app, he/she will get a toast saying "Username is already taken".
Register.java
public class Register extends AppCompatActivity {
EditText regEmail, regPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
regEmail = (EditText)findViewById(R.id.reg_email);
regPassword = (EditText)findViewById(R.id.reg_password);
}
public void OnReg(View view) {
String strEmail = regEmail.getText().toString();
String strPassword = regPassword.getText().toString();
String type = "register";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, strEmail, strPassword);
}}
BackgroundWorker.java
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.93.22.231/login.php";
String register_url = "http://10.93.22.231/register.php";
if (type.equals("login")){
try {
String email = 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("email","UTF-8")+"="+URLEncoder.encode(email,"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();
}
} else if (type.equals("register")){
try {
String regEmail = params[1];
String regPassword = params[2];
URL url = new URL(register_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("email","UTF-8")+"="+URLEncoder.encode(regEmail,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(regPassword,"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);
if (result.contains("success")) {
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
} else {
alertDialog.show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Register.php
<?php
require "conn.php";
$email = $_POST["email"];
$password = $_POST["password"];
$mysql_qry = "INSERT INTO users (email, password) VALUES ('$email','$password')";
if($conn->query($mysql_qry) === TRUE){
echo "Insert successful";
} else {
echo "Insert failed, please try again.";
}
$conn->close();
?>

Toast.makeText(YourActivtyOrContext,"Username Taken", Toast.LENGTH_LONG).show();

on Post execute you can do some thing like this
also at the server level if the username already exists you should not save the record instead of that you should pass the value that username already exists
#Override
protected void onPostExecute(String result) {
if (result.contains("success")) {
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
} else {
Toast.makeText(context,result, Toast.LENGTH_LONG).show();
}
}

Hey please check this code, maybe it can solve your problem. This is simple code.
if (ConnectivityDetector.isConnectingToInternet(RegisterActivity.this)) {
JSONObject jsonObjectInput = new JSONObject();
jsonObjectInput.put(WebField.REGISTER_USER.REQUEST_USER_NAME,
edtUserName.getText().toString());
String mode = "RegisterUser";
new GetJsonWithCallBack(RegisterActivity.this, jsonObjectInput,
1, mode, new OnUpdateListener() {
#Override
public void onUpdateComplete(JSONObject jsonObject,
boolean isSuccess) {
if (isSuccess) {
try {
if (jsonObject != null) {
if (jsonObject.has("userDetail")) {
JSONObject jsonUserDetails = jsonObject.getJSONObject("userDetail");
RegisterData regData = new RegisterData();
regData.setUserName(jsonUserDetails.getString(WebField.REGISTER_USER.RESPONSE_USER_NAME));
SessionManager.saveData(RegisterActivity.this, regData);
finish();
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
if (jsonObject != null) {
try {
String Status = jsonObject.getString("status");
String message = jsonObject.getString("message");
if (message.equalsIgnoreCase("User already Exists")) {
GlobalMethod.showAlert(RegisterActivity.this, "User name already exists..!!");
} else if (message.equalsIgnoreCase("Email id already Exists")) {
GlobalMethod.showAlert(RegisterActivity.this, "Email id already exists..!!");
} else if (message.equalsIgnoreCase("Mobile no already Exists")) {
GlobalMethod.showAlert(RegisterActivity.this, "Mobile no already exists..!!");
} else {
GlobalMethod.showAlert(RegisterActivity.this, jsonObject.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
}
}
}).execute();
} else {
AlertDialogUtility.showInternetAlert(RegisterActivity.this);
}
} catch (Exception e) {
e.printStackTrace();
}

try this way
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
if (result.contains("success")) {
JSONObject json= new JSONObject(result);
if(json.has("message"){
String message=json.getString("message");
Toast.makeText(ctx,message,Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
} else {
alertDialog.show();
}
}
UPDATE
User validation query
$mysql_qry="SELECT * FROM users WHERE email='$email'";
if($conn->query($mysql_qry) === TRUE){
}else{}

Related

How to make in alertDialog by clicking OK then, go to the next page?

My problems :
1. I have error on it.
2. Why cannot go to the next page when I use startActivity?
3. How to solve?
4. I already use startActivity by using Intent method
Below is prove 1 :
Below is prove 2 :
Below is prove 3 :
Below is code snippet :
public void OnLog(View view)
{
String Username = username.getText().toString();
String Password = password.getText().toString();
String type = "login";
if(Username.equals("") || Password.equals(""))
{
Toast.makeText(getApplicationContext(), "Please fill the Username and Password!", Toast.LENGTH_LONG).show();
}
else {
Background bg = new Background(Context, act);
bg.execute(type, Username, Password);
}
}
Below is coding for Background.java :
public class Background extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
Background(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params)
{
String type = params[0];
String login_url = "http://172.20.10.4/LoginLab3.php";
String reg_url = "http://172.20.10.4/RegisterLab3.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 (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else if(type.equals("register"))
{
try {
String name = params[1];
String surname = params[2];
String age = params[3];
String username = params[4];
String password = params[5];
URL url = new URL(reg_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("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
+URLEncoder.encode("surname","UTF-8")+"="+URLEncoder.encode(surname,"UTF-8")+"&"
+URLEncoder.encode("age","UTF-8")+"="+URLEncoder.encode(age,"UTF-8")+"&"
+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 (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.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Login Status");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Login.this, Welcome.class));
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
dialog.create().show();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
}
Help me! i have some problem on it. I already use almost all method, but cannot go to the next page. Why ?
Activity OnCreate Code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Pass activity to Async Task
new Background(this).execute();
}
Async Task
public class Background extends AsyncTask<Void,Void,Void> {
private Context context;
public Background(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent(context, TargetActivity.class);
context.startActivity(intent);
((Activity)context).finish();
}
}
Try context.startActivity() because AsyncTask class don't have startActivity() method inherited.
Also, pass the activity in the constructor and assign it to a variable and use that variable while creating intent
Context context;
Activity activity;
AlertDialog alertDialog;
Background(Context ctx, Activity act) {
context = ctx;
activity = act;
}
inside onClick()
context.startActivity(new Intent(activity, Welcome.class));

Why still cannot go to next page?

MY PROBLEMS :
1. No error on it.
2. Cannot go to next page but I already put if else statement for login at onPostExecute.
3. It is true my if else statement?
Below is a prove my button clickable but not go to the next page :
Below is my onPostExecute code snippet :
Below is : Background.java for connection mysql database.
public class Background extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
Background(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params)
{
String type = params[0];
String login_url = "http://172.20.10.4/LoginLab3.php";
String reg_url = "http://172.20.10.4/RegisterLab3.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 (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else if(type.equals("register"))
{
try {
String name = params[1];
String surname = params[2];
String age = params[3];
String username = params[4];
String password = params[5];
URL url = new URL(reg_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("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
+URLEncoder.encode("surname","UTF-8")+"="+URLEncoder.encode(surname,"UTF-8")+"&"
+URLEncoder.encode("age","UTF-8")+"="+URLEncoder.encode(age,"UTF-8")+"&"
+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 (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(final String result)
{
final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Login Status");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
Boolean login = (context.equals("login"));
if(login==true)
{
Intent in = new Intent(context, Welcome.class);
context.startActivity(in);
((Activity)context).finish();
}
else
{
dialog.setMessage("Wrong username and password");
}
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
dialog.create().show();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
}
Below is : Login.java
public class Login extends AppCompatActivity
{
EditText username, password;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = findViewById(R.id.etUsername);
password = findViewById(R.id.etPassword);
}
public void OnLog(View view)
{
String Username = username.getText().toString();
String Password = password.getText().toString();
String type = "login";
if(Username.equals("") || Password.equals(""))
{
Toast.makeText(getApplicationContext(), "Username and Password are required!", Toast.LENGTH_LONG).show();
}
else {
Background bg = new Background(this);
bg.execute(type, Username, Password);
}
}
public void OnReg(View view) {
startActivity(new Intent(getApplicationContext(), Register.class));
}
}
The condition on your if statement is never true.
context of type Context can never equal to a string of login. So the if clause is never run.
The yellow highlighted inspection is probably complaining about that.
I think the login result will be in the string result passed in as a parameter. You'll probably have to parse the result and see if the login is successful.

Compiler skips try bracket?

So I have this little App that should only show a JSON-Object(not even parse it) in the Textview "tvJsonItem" after you push the button "btnHit". I have built in multiple Toasts to follow its procedure, but if i push the button, i only get the Toast Test1 from the onPostExecute. It seems like the Programme skips the whole try bracket.
public class MainActivity extends AppCompatActivity {
private TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnHit = (Button) findViewById(R.id.btnHit);
tvData = (TextView) findViewById(R.id.tvJsonItem);
}
public void onClick(View view) {
new JSONTask().execute();
Toast.makeText(getApplicationContext(), "onClick", Toast.LENGTH_LONG);
}
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String...params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
URL url = null;
try {
url = new URL("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
Toast.makeText(MainActivity.this, "test2", Toast.LENGTH_LONG).show();
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String result = buffer.toString();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Malformed", Toast.LENGTH_LONG);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "IOException", Toast.LENGTH_LONG);
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
protected void onPostExecute(String result){
super.onPostExecute(result);
tvData.setText(result);
Toast.makeText(getApplicationContext(), "test1", Toast.LENGTH_LONG).show();
}
}
}
You can't call toast.show() in doInBackground, because toast.show() should call in Main UI Thread.
for the test, convert toast.show() to log.d()...

Unable to send data to server in Android

I'm new to Android. Don't know which part has gone wrong. The thing is I'm unable to send the data to the server in Android Studio.
This is the error I'm facing
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\students\connection.php:6 Stack trace: #0 C:\xampp\htdocs\students\add_employee.php(2): include() #1 {main} thrown in C:\xampp\htdocs\students\connection.php on line 6
The code goes like this...
Main Activity
public class MainActivity extends AppCompatActivity {
Button b1;
EditText e1;
private ProgressDialog pDialog;
private JSONObject json;
private int success=0;
private HTTPURLConnection service;
private String strname ="";
//Initialize webservice URL
private String path = "http://localhost/student/add_employee.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
e1 = (EditText) findViewById(R.id.editText9);
service=new HTTPURLConnection();
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!e1.getText().toString().equals("") ) {
strname = e1.getText().toString();
//Call WebService
new PostDataTOServer().execute();
} else {
Toast.makeText(getApplicationContext(), "Please Enter all fields", Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(MainActivity.this, Student1.class);
startActivity(intent);
}
});
}
private class PostDataTOServer extends AsyncTask<Void, Void, Void> {
String response = "";
//Create hashmap Object to send parameters to web service
HashMap<String, String> postDataParams;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postDataParams=new HashMap<String, String>();
postDataParams.put("name", strname);
//Call ServerData() method to call webservice and store result in response
response= service.ServerData(path,postDataParams);
try {
json = new JSONObject(response);
//Get Values from JSONobject
System.out.println("success=" + json.get("success"));
success = json.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if(success==1) {
Toast.makeText(getApplicationContext(), "Employee Added successfully..!", Toast.LENGTH_LONG).show();
}
}
}
}
HTTPURLConnection
public class HTTPURLConnection {
String response="";
URL url;
public String ServerData(String path,HashMap<String, String> params) {
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//Log.d("Output",br.toString());
while ((line = br.readLine()) != null) {
response += line;
Log.d("output lines", line);
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}}
My PHP code
add_employee.php
<?php
include('connection.php');
$emp_name=$_POST["name"];
$success=0;
$status="Active";
$sql = "INSERT INTO `employee` (`emp_name`)
VALUES ('$emp_name')";
if(mysql_query($sql))
{
$success=1;
}
$response["success"]=$success;
die(json_encode($response));
mysql_close($con);
?>
connection.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('student');
?>

Android - Attempted to finish an input event but the input event receiver has already been disposed

In Logcat It Displays : Attempted to finish an input event but the input event receiver has already been disposed
In Catch Block Message Box I am Having An Error Like println needs a message. Please Help Me.
I Use Android Studio 2.0
Here is LOGCAT :
"12-13 03:48:40.598 2129-2129/com.mysqlapp.bug.mysqlapp
W/InputEventReceiver: Attempted to finish an input event but the input
event receiver has already been disposed."
public class MainActivity extends AppCompatActivity {
EditText etUserName,etPassword;
String userName,password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUserName = (EditText) findViewById(R.id.etUserName);
etPassword = (EditText) findViewById(R.id.etPassword);
}
public void btnLoginClick(View v)
{
try
{
userName = etUserName.getText().toString();
password = etPassword.getText().toString();
Log.d("Hello","Here");
MySqlDatabaseHelper sqlCls = new MySqlDatabaseHelper(this);
sqlCls.doInBackground("login",userName,password);
}
catch (Exception ex)
{
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle("Something Went Wrong");
alert.setMessage("-"+ex.getMessage()+"-");
alert.show();
}
}
}
Here is Second Class :
public class MySqlDatabaseHelper extends AsyncTask<String,Void,String> {
Context ctx;
String method,userID,userName,password,postData,result;
MySqlDatabaseHelper(Context _ctx)
{
ctx = _ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
method = params[0].toString();
if(method.equals("login"))
{
userName = params[1].toString();
password = params[2].toString();
URL url = new URL("http://10.0.2.2/Android/login.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os,"UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
postData = URLEncoder.encode("uname","UTF-8") + "=" + URLEncoder.encode(userName,"UTF-8") + "&" +
URLEncoder.encode("password","UTF-8") + "=" + URLEncoder.encode(password,"UTF-8");
bw.write(postData);
bw.flush();
bw.close();
osw.close();
os.close();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is,"UTF-8");
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null)
{
result += line;
}
br.close();
isr.close();
is.close();
conn.disconnect();
return result;
}
else
{
return "NONE";
}
}
catch (Exception ex)
{
String err = (ex.getMessage() == null) ? "Error occured" : ex.getMessage();
Log.e("Err",err);
AlertDialog alert = new AlertDialog.Builder(ctx).create();
alert.setTitle("Something Went Wrong1");
alert.setMessage("-"+ex.getMessage()+"-");
alert.show();
return "ERR";
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
AlertDialog alert = new AlertDialog.Builder(ctx).create();
alert.setTitle("Successfully Worked");
alert.setMessage("-"+result+"-");
alert.show();
}
}

Categories