I've been sitting with this problem for 2 weeks now and I hope 1 of you can help me with this.
The following code I have for connecting with out database.
package com.example.sunapp;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
String ip = "xxx.xxx.xxx.xxx";
String classs = "net.sourgeforge.jtds.jdbc.Driver";
String db = "xxxx";
String un = "xxxx";
String password = "xxxx";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs);
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO1", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO2", e.getMessage());
} catch (Exception e) {
Log.e("ERRO3", e.getMessage());
}
return conn;
}
}
When I hit 'Inloggen' I get the following error
"02-19 15:15:02.679 8488-10423/com.example.sunapp E/ERRO2: net.sourgeforge.jtds.jdbc.Driver"
Below the code of the login activity of the application
package com.example.sunapp;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.os.AsyncTask;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class LoginActivity extends AppCompatActivity {
//Declaring connection
ConnectionClass connectionClass;
EditText etGebruikersnaam, etWachtwoord;
CardView cvInloggen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.hide();
connectionClass = new ConnectionClass();
final EditText etGebruikersnaam = findViewById(R.id.etGebruikersnaam);
final EditText etWachtwoord = findViewById(R.id.etWachtwoord);
final CardView cvInloggen = findViewById(R.id.cvInloggen);
final TextView RegistreerLink = findViewById(R.id.tvRegistreren);
RegistreerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registreerIntent = new Intent(LoginActivity.this, RegistryActivity.class);
LoginActivity.this.startActivity(registreerIntent);
}
});
cvInloggen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSucces = false;
final EditText etGebruikersnaam = findViewById(R.id.etGebruikersnaam);
final EditText etWachtwoord = findViewById(R.id.etWachtwoord);
String userid = etGebruikersnaam.getText().toString();
String password = etWachtwoord.getText().toString();
#Override
protected String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Vul hier uw gebruikersnaam en wachtwoord in";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
String query = "select * from compose.tblGebruikers where Gebruikersnaam='" + userid + "' and Wachtwoord='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next())
{
z = "Login succesfull";
isSucces = true;
}
else
{
z = "Invalid Credentials";
isSucces = false;
}
}
}
catch (Exception ex)
{
isSucces = false;
z = "Exceptions";
}
}
return z;
}
}
}
I must be doing something wrong but, what is the question. the message I'm getting comes from the classnotfoundexception. I still not managed to make it work.
Related
I am trying to connect my android login app to XAMP server(an Apache is running in local machine) through jtds jdbc. It seems the code fails to connect the server. Here's the code:
ConnectionClass.java
package com.ercess.databaseconnection;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.os.Bundle;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
public String driver = "net.sourceforge.jtds.jdbc.Driver";
String url = "jdbc:mysql://localhost/events-test";
//String url = "jdbc:mysql://127.0.0.1/events-test";
public String un = "root";
public String password = "password";
public String db = "users";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
java.sql.Connection conn = null;
String ConnURL = null;
try{
Class.forName(driver);
ConnURL = "jdbc:jtds:sqlserver://" + "127.0.0.1" +";databaseName="+ db + ";user=" + un+ ";password=" + password + ";";
conn = DriverManager.getConnection(ConnURL);
}catch (SQLException se){
Log.e("ERROR", se.getMessage());
}catch (ClassNotFoundException e){
Log.e("ERROR", e.getMessage());
}catch(Exception e){
Log.e("ERROR", e.getMessage());
}
//Log.d("conn",conn.toString());
return conn;
}
}
MainActivity.java
package com.ercess.databaseconnection;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
public class MainActivity extends AppCompatActivity {
EditText email, password;
Button login;
ProgressDialog progressDialog;
ConnectionClass connectionClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
login = findViewById(R.id.login);
connectionClass = new ConnectionClass();
progressDialog = new ProgressDialog(this);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dologin dologin = new Dologin();
dologin.execute();
}
});
}
public class Dologin extends AsyncTask<String, String, String>{
String emailstring = email.getText().toString();
String passstring = password.getText().toString();
String z = "";
boolean isSuccess = false;
String em, pass;
#Override
protected void onPreExecute() {
progressDialog.setMessage("Loading...");
progressDialog.show();
super.onPreExecute();
}
protected String doInBackground(String... params){
if(emailstring.trim().equals("") || passstring.trim().equals(""))
z = "Please enter all fields........";
else
{
try{
Connection con = connectionClass.CONN();
if(con == null){
z="Please, check your internet connection....";
}else{
String query = "select * from users where user='"+emailstring+"'and password='"+passstring+"'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
em = rs.getString(0);
pass = rs.getString(1);
if(em.equals(emailstring) && pass.equals(passstring))
{
isSuccess = true;
z = "Login successful...";
}
else isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions"+ex;
}
}
return z;
}
#Override
protected void onPostExecute (String s){
Toast.makeText(getBaseContext(),""+z, Toast.LENGTH_LONG).show();
progressDialog.hide();
}
}
}
I am getting this output: "Please, check your internet connection...." .
This message should fire up only when con = null.
How to resolve?
Android does not support MySQL OR SQL Server : -
You can Use Sqllite
https://www.tutorialspoint.com/android/android_sqlite_database.htm
Or you can Access MySQL by PHP :-
https://www.tutorialspoint.com/android/android_php_mysql.htm
I faced the same problem...
The main problem is in your ConnectionClass.
String url = "jdbc:mysql://localhost/events-test";
public String un = "root";
public String password = "password";
public String db = "users";
this was your code, well, when you are using root and localhost, it's creating the check your internet connection problem. so to solve it, you have to create a new user and instead of localhost, use the IP Address of your internet.
To create new user, if you are using phpmyadmin, click the privileges tab, there you see add user option. Create user there, give all database privileges to that user and save it. Then use the username and password instead of "root"and "password".
Now to get your IP address, go to command prompt, type ipconfig, you will find ip address. In your above code, instead of localhost, type your ip address, for example,
String url = "jdbc:mysql://192.168.0.12/events-test";
And you have to give internet access in the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
This should solve your problem.
At the moment I can add users into the database through postman or emulator but I need to be able insert the data from actual android device .What adjustments do I have to take ? Please have a look at the code below
This is my main activity that I using in my app :
package ie.example.artur.adminapp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.HashMap;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
EditText editTextName,editTextEmail,editTextPassword;
TextView textView;
private static final String DB_URL = "jdbc:mysql://10.3.2.51/socialmedia_website";
private static final String USER = "zzz";
private static final String PASS = "zzz";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
textView = (TextView) findViewById(R.id.textView);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void btnConn(View view) {
findViewById(R.id.layoutProgress).setVisibility(View.VISIBLE);
final ApiClient apiClient = new ApiClient();
String email = editTextEmail.getText().toString();
String name = editTextName.getText().toString();
String password = editTextPassword.getText().toString();
HashMap<String,String> parameters = new HashMap<>();
parameters.put("email",email);
parameters.put("name",name);
parameters.put("password",password);
Call<ApiResponse> call = apiClient.loginUser(parameters);
call.enqueue(new Callback<ApiResponse>() {
#Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
if(response.isSuccessful())
{
ApiResponse apiResponse = response.body();
if(apiResponse.getStatus() == 200 || apiResponse.getStatus() == 201)
{
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
Send objSend = new Send();
objSend.execute("");
//Toast.makeText(MainActivity.this,"Success", Toast.LENGTH_SHORT);
textView.setText("Success.");
}
else
{
//Toast.makeText(MainActivity.this,apiResponse.getErrors(), Toast.LENGTH_SHORT);
textView.setText(apiResponse.getErrors());
}
}
else
{
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
//Toast.makeText(MainActivity.this,"Invalid api response.", Toast.LENGTH_SHORT);
textView.setText("Invalid api response.");
}
}
#Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
//Toast.makeText(MainActivity.this,"No host available or please check network connectivity.", Toast.LENGTH_SHORT);
textView.setText("No host available or please check network connectivity.");
}
});
}
private class Send extends AsyncTask<String, String, String>
{
String msg = "";
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
#Override
protected void onPreExecute() {
textView.setText("Please Wait Inserting Data");
}
#Override
protected String doInBackground(String... strings) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
if (conn == null) {
msg = "Connection goes wrong";
} else {
String query = "Insert INTO users (name,email,password) VALUES('" + name+"','"+email+"','"+password+"')";
Statement stmt = conn.createStatement();
stmt.executeUpdate(query);
msg = "Inserting Successful!!";
}
conn.close();
}
catch(
Exception e
)
{
msg = "Connection goes Wrong";
e.printStackTrace();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {textView.setText(msg);}
}
}
Api client class
package ie.example.artur.adminapp;
import java.util.HashMap;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by asifj on 7/25/2017.
*/
public class ApiClient
{
private String BASE_URL = BuildConfig.BASE_URL;
ApiEndPoints apiService;
public ApiClient() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging); // <-- this is the important line!
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).client(httpClient.build()).build();
apiService = retrofit.create(ApiEndPoints.class);
}
public Call<ApiResponse> loginUser(HashMap<String, String> parameters)
{
return apiService.usercreate(parameters);
}
}
If you need me to share any more class please let me know in the comments
//this is a class you'll call in you main activity
public class PostRequest extends AsyncTask<Void, Void, String> {
private String parameters;
private Context context;
public PostRequest(Context context) {
this.context = context;
Log.d("PostRequest", "Context set : " + context);
}
public void setParameters(String parameters) {
this.parameters = parameters;
Log.d("PostRequest", "Parameters set : " + parameters);
}
#Override
protected String doInBackground(Void... params) {
String response = null;
try {
URL url = new URL("url of your php script");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
OutputStreamWriter request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
response = sb.toString();
isr.close();
reader.close();
} catch (IOException e) {
// Error
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
//in your main activity you'll call it like so
PostRequest postRequest = new PostRequest(getContext());
postRequest.setParameters("param1=" + "param1value" + "¶m2=" + "param2value");
postRequest.execute();
Hello I am beginner to android.I want to make a database connection to mssql server in my pc. I found example on the net.
I think I have something wrong in connection. Because I have two records in my User table. But this code only gives me first record in table.
Here is ConnectionClass.java :
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
String ip = "127.0.0.1:1433";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "DBAndroid1";
String un = "TestUser";
String password = "123";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs).newInstance();
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO0", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO1", e.getMessage());
} catch (Exception e) {
Log.e("ERRO2", e.getMessage());
}
return conn;
}
}
Here is my MainActivity.java.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ConnectionClass connectionClass;
EditText edtuserid, edtpass;
Button btnlogin;
ProgressBar pbbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
edtuserid = (EditText) findViewById(R.id.et_username);
edtpass = (EditText) findViewById(R.id.et_password);
btnlogin = (Button) findViewById(R.id.btn_Login);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
String userid = edtuserid.getText().toString();
String password = edtpass.getText().toString();
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this,r,Toast.LENGTH_SHORT).show();
if(isSuccess) {
Toast.makeText(MainActivity.this,r,Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select Username from [User]";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
int columnCount = rs.getMetaData().getColumnCount();
System.out.println("Eleman sayisi: "+ columnCount);
if(rs.next())
{
String lastName = rs.getString("Username");
z = "Login successfull";
z = z + " " + lastName;
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions burda mi "+ ex;
}
}
return z;
}
}
}
I hope you can help. Thank you.
You have two records in table but you are using if(rs.next()) to fetch record which will return only single record.
Use for loop or while loop to get all records and iterate resultset in loop.
My data is not inserting to database of webhost.
Here is my ActionActivity.java from where I will send data to the database.
import android.app.Activity;
import android.content.Context;
import android.provider.Settings;
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.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
public class ActionActivity extends Activity {
private String t;
TextView timer;
EditText e1,e2;
Button save;
static InputStream is = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_action);
Bundle time = getIntent().getExtras();
t = (String) time.get("com.example.masba.timemanagement.MESSAGE");
e1 = (EditText) findViewById(R.id.editText);
e1.setText(t, TextView.BufferType.EDITABLE);
e2 = (EditText) findViewById(R.id.editText2);
save = (Button) findViewById(R.id.save);
}
public void insert(View view){
String actionName = e1.getText().toString();
String time = e2.getText().toString();
Toast.makeText(this, "Data Inserting...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(actionName, time);
e1.setText("");
e2.setText("");
}
#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_main, 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);
}
}
Now my SignupActivity.java Which extends Asynctask.
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String actionName = arg0[0];
String time = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?actioname=" + URLEncoder.encode(actionName, "UTF-8");
data += "&time=" + URLEncoder.encode(time, "UTF-8");
link = "http://masumalmasba.comli.com/insertdata.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully.", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Now my insertdata.php code is:
<?php
$servername="mysql6.000webhost.com";
$username = "a1871724_masum";
$password = "almasba012";
$dbname = "a1871724_actiont";
$conn = new mysqli($servername , $username , $password , $dbname);
if($conn->connect_error)
{
die("Connection Failed: ".$conn->connect_error);
}
$action = $_GET['actionname'];
$time = $_GET['time'];
$sql = "INSERT INTO actiontime (name,time) VALUES ('($action)','($time)')";
if($conn->query($sql)===TRUE){
echo "New record created succesfully";
}
else{
echo "Error";
mysql_close($conn);
}
?>
I am using AsyncTask in my application and sometimes when I run the application I get the error as java.util.cancellationexception.
Can someone let me know the reason of this error or the way this can be removed?
import java.util.concurrent.ExecutionException;
import com.babbleville.io.BabbleVilleSyncTask;
import com.babbleville.io.GetCurrentLocation;
import com.babbleville.utils.BabbleVilleWebServiceUrl;
import com.babbleville.utils.ConstantCodes;
import com.babbleville.utils.LoadContent;
import com.babbleville.io.LoginParse;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BabbleVilleMainActivity extends Activity implements OnClickListener
{
private Button btnLogin = null;
private Button btnNewUserSignUp = null;
private Button btnForgotPwd = null;
//private boolean loginFlag = false;
private EditText emailId = null;
private EditText password = null;
private String userName = null;
private String pwd = null;
String url = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
btnLogin = (Button) findViewById (R.id.btnLogin);
btnNewUserSignUp = (Button) findViewById(R.id.btnNewUser);
btnForgotPwd = (Button) findViewById(R.id.btnForgotPwd);
emailId = (EditText) findViewById(R.id.emailId);
password = (EditText) findViewById(R.id.password);
//Temporary. Should be removed later on.
emailId.setText("sunil#softwebsolutions.com");
password.setText("sunil123");
btnLogin.setOnClickListener(this);
btnNewUserSignUp.setOnClickListener(this);
btnForgotPwd.setOnClickListener(this);
}
/**
* This is the overriden method for getting the click events.
* #param View v = is the view on which click event this method is called.
* For eg, on Login click button v will btnLogin.
*/
public void onClick(View v)
{
if(v == btnLogin)
{
userName = emailId.getText().toString().trim();
pwd = password.getText().toString().trim();
System.out.println("User name ==> " + userName);
System.out.println("Password ==> " + pwd);
if(userName == null || pwd == null || userName.equals("") || pwd.equals(""))
{
Toast toast = Toast.makeText(BabbleVilleMainActivity.this, "Please enter your Username and Password!", 50);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else
{
url = null;
/*url = ConstantCodes.LOGIN_URL + ConstantCodes.ACTION + "=" + ConstantCodes.LOGIN_ACTION + "&" +
ConstantCodes.EMAILID + "=" + this.userName + "&" + ConstantCodes.PWD + "=" + this.pwd ;*/
url = BabbleVilleWebServiceUrl.getLoginURL() + ConstantCodes.EMAILID + "=" + this.userName + "&" + ConstantCodes.PWD + "=" + this.pwd ;
System.out.println("Login URL ==> " + url);
BabbleVilleSyncTask loginTask = new BabbleVilleSyncTask(v.getContext());
loginTask.execute(url);
//System.out.println("status===>"+loginTask.getStatus());
try
{
String result = loginTask.get().trim();
System.out.println("Result returned from Login Task ==> " + result);
LoginParse.loginParser(result);
if(LoginParse.getLoginAck())
{
/*ConstantCodes.BABBLE_START_NUM = 0;
ConstantCodes.BABBLE_END_NUM = 5;*/
// loadBabbles();
GetCurrentLocation location = new GetCurrentLocation(v.getContext());
String lat = location.getCurrentLatitude();
String lon = location.getCurrentLongitude();
System.out.println("Latitude ==> " + lat + " Longitude ==> " + lon);
//Babble babble_add_data = new Babble(BabbleVilleMainActivity.this,"babble");
LoadContent loadContent = new LoadContent(BabbleVilleMainActivity.this);
loadContent.loadBabbles(lat, lon);
loadContent.loadVilles();
//loadContent.loadUserDetails();
//mContext = v.getContext();
Intent homeScreenIntent = new Intent(BabbleVilleMainActivity.this, HomeScreenActivity.class);
BabbleVilleMainActivity.this.startActivity(homeScreenIntent);
}
else
{
Toast toast = Toast.makeText(BabbleVilleMainActivity.this, "Username or Password is incorrect", 50);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
}
}
else if(v == btnForgotPwd)
{
Intent forgetPwdIntent = new Intent(BabbleVilleMainActivity.this, ForgotPasswordActivity.class);
BabbleVilleMainActivity.this.startActivity(forgetPwdIntent);
}
else if(v == btnNewUserSignUp)
{
Intent newUserIntent = new Intent(BabbleVilleMainActivity.this, NewUserSignUpActivity.class);
BabbleVilleMainActivity.this.startActivity(newUserIntent);
}
}
}
The exception occurs at String result = loginTask.get().trim().
Can you let me know now what is the problem?
package com.babbleville.io;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class BabbleVilleSyncTask extends AsyncTask<String, Void, String>
{
private Context context = null;
private final HttpClient httpClient = new DefaultHttpClient();
private String content = null;
private String error = null;
private ProgressDialog progressDialog = null;
private String finalResult = null;
public BabbleVilleSyncTask(Context context)
{
this.context = context;
progressDialog = new ProgressDialog(this.context);
}
protected void onPreExecute()
{
progressDialog.setMessage("Please Wait....");
progressDialog.show();
}
protected String doInBackground(String... urls)
{
try
{
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
content = httpClient.execute(httpget, responseHandler);
}
catch (ClientProtocolException e)
{
error = e.getMessage();
Log.e("ClientProtocolException", error);
cancel(true);
}
catch (IOException e)
{
error = e.getMessage();
Log.e("IOException", error);
cancel(true);
}
httpClient.getConnectionManager().shutdown();
return content;
}
protected void onPostExecute(String result)
{
progressDialog.dismiss();
}
}
Please let me know how can I use the result returned in onPostExecute.