Unable to send data to server in Android - java

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

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

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

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{}

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

Login not successful on MySQL database from android app

I have created an android app that logins into a MySQL database but I don't receive any results. The 'result' variable in the alert dialog box in backgroundWorker.java (function "onPostExecute") returns null, can anyone solve this problem?
BackgroundWorker.java`
public class BackgroundWorker extends
AsyncTask<String,String,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx)
{
context =ctx;
}
#Override
protected String doInBackground(String... params) {
String type=params[0];
String login_url="192.168.10.9/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,"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) {
Log.i("ok", "Result " + Result);
alertDialog.setMessage(Result);
alertDialog.show();
}
CheckConn.java
public class CheckConn extends AppCompatActivity {
EditText user;
EditText pass;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.check_conn);
user = (EditText) findViewById(R.id.et_u);
pass = (EditText) findViewById(R.id.et_p);
Button press = (Button) findViewById(R.id.btn_login);
press.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onLogin();
}
});
}
public void onLogin()
{
String username= user.getText().toString();
String password=pass.getText().toString();
String type="login";
BackgroundWorker backgroundWorker=new BackgroundWorker(this);
backgroundWorker.execute(type,username,password);
}
}
connection.php
<?php
$mysql_usernmae="root";
$mysql_password="*****";
$db="map";
$db= new mysqli('localhost',$mysql_usernmae,$mysql_password,$db);
?>
login.php
<?php
require "connection.php";
$user_name=$_POST["user_name"];
$user_pass=$_POST["password"];
$mysql_qry="select * from user_info where user_name like
'$user_name' and user_password like 'user_pass';";
$result=mysqli_query($db,$mysql_qry);
if (mysqli_num_rows($result) > 0)
{
echo "login Successsss";
}
else
{
echo "faileddddd Booooo";
}
?>
`
why you don't ejecute first your login.php file in the browser, harcode the values for user_name and user_pass, and check if the connection is working on server side,
after that you can check if your user and pass are coming from android app, I must assume you have a database with some data in the table you are making the query, also check if the name of database, table, query are correct, you can check with MySQL workbench if the query works and is returning some result.

Want to login to Router with android application

I'm just starting to develop android application and want to try to connect to my router. Wrote application using Jackson, but get stuck with json request for login to the router. IP of my router is 192.168.1.1 and username and password should be taken from EditText fields.
android.os.NetworkOnMainThreadException
There is json string for login:
{ "jsonrpc": "2.0", "id": 1, "method": "call", "params": [ "00000000000000000000000000000000", "session",
"login", { "username": "root", "password": "admin01" } ] }
This is my RestRequest.java
public class RestRequest {
private static final String TAG = JacksonUtil.class.getSimpleName();
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
//Constructor with no parameter
public RestRequest(){
}
public String makeWebServiceCall(String url, int requestmethod){
return this.makeWebServiceCall(url, requestmethod, null);
}
public String makeWebServiceCall(String urladdress, int requestmethod, HashMap<String, String> params){
URL url;
String responce = "";
try {
url = new URL(urladdress);
HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setReadTimeout(15000);
urlconnection.setConnectTimeout(15000);
urlconnection.setDoInput(true);
urlconnection.setDoOutput(true);
if(requestmethod == POST){
urlconnection.setRequestMethod("POST");
}else if(requestmethod == GET){
urlconnection.setRequestMethod("GET");
}
if(params != null){
OutputStream outputstream = urlconnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputstream, "UTF-8"));
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"));
}
bufferedWriter.write(result.toString());
bufferedWriter.flush();
bufferedWriter.close();
outputstream.close();
}
int responceCode = urlconnection.getResponseCode();
if(responceCode == HttpsURLConnection.HTTP_OK){
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
while ((line = br.readLine()) != null){
responce += line;
}
}else {
responce = "";
}
} catch (Exception e){
Log.e(TAG, "IOException parsing to json", e);
}
return response;
}
Edited my LoginActivity.java
Can anyone to look at this activity and tell what I'm doing wrong
public class LoginActivity extends AppCompatActivity {
private String page_url = "http://192.168.1.1/ubus";
#Bind(R.id.user_name_edit_text)
TextView user_name;
#Bind(R.id.user_password_edit_text)
TextView user_password;
#Bind(R.id.login_button)
Button login_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url = page_url;
String username = getUserName();
String password = getPassword();
TryToLogin tryToLogin = new TryToLogin();
tryToLogin.execute(url, username, password);
}
});
class TryToLogin extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params) {
URL url = null;
try {
url = new URL(page_url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
connection.connect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String getUserName() {
String username = user_name.getText().toString();
return username;
}
private String getPassword() {
String password = user_password.getText().toString();
return password;
}
You cannot make network calls using the main thread in Android - this is by design to ensure the UI thread remains responsive and does not wait. You need to perform this call in an AsyncThread or normal Thread

Categories