When ever I click on the login button it always shows me check ur internet toast I don't know why I have also turned off my firewall also please help
I have also passed the internet permission also in the manifest .
Can someone also share the link from where I can learn how to pass values in android from sql server
thanks in advance !
MainActivity.java
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
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.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity
{
// Declaring layout button, edit texts
Button login;
EditText username,password;
ProgressBar progressBar;
// End Declaring layout button, edit texts
// Declaring connection variables
Connection con;
String un,pass,db,ip;
//End Declaring connection variables
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting values from button, texts and progress bar
login = (Button) findViewById(R.id.button);
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.editText2);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
// End Getting values from button, texts and progress bar
// Declaring Server ip, username, database name and password
ip = "LAPTOP-KOS272HK";
db = "fmv";
un = "username";
pass = "password";
// Declaring Server ip, username, database name and password
// Setting up the function when button login is clicked
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CheckLogin checkLogin = new CheckLogin();// this is the Asynctask, which is used to process in background to reduce load on app process
checkLogin.execute("");
}
});
//End Setting up the function when button login is clicked
}
public class CheckLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute()
{
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r)
{
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess)
{
Toast.makeText(MainActivity.this , "Login Successfull" , Toast.LENGTH_LONG).show();
//finish();
}
}
#Override
protected String doInBackground(String... params)
{
String usernam = username.getText().toString();
String passwordd = password.getText().toString();
if(usernam.trim().equals("")|| passwordd.trim().equals(""))
z = "Please enter Username and Password";
else
{
try
{
con = connectionclass(un, pass, db, ip); // Connect to database
if (con == null)
{
z = "Check Your Internet Access!";
}
else
{
// Change below query according to your own database.
String query = "select * from login where user_name= '" + usernam.toString() + "' and pass_word = '"+ passwordd.toString() +"' ";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successful";
isSuccess=true;
con.close();
}
else
{
z = "Invalid Credentials!";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = ex.getMessage();
}
}
return z;
}
}
#SuppressLint("NewApi")
public Connection connectionclass(String user, String password, String database, String server)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + database + ";user=" + user+ ";password=" + password + ";";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return connection;
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tanis.logi">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
Related
i'm trying to connect to SQL Server Database from android studio
i'm using jtds and already import "jtds-1.3.1.jar" module to android studio
in the import part below line i got error
import net.sourceforge.jtds.jdbc.*;
and the error is:
"error: package net.sourceforge.jtds.jdbc does not exist"
. i don't know what i miss.
package com.example.mycar4;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
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.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.sourceforge.jtds.jdbc.*;
public class database extends AppCompatActivity {
// Declaring layout button, edit texts
Button login;
EditText username,password;
ProgressBar progressBar;
// End Declaring layout button, edit texts
// Declaring connection variables
Connection con;
String un,pass,db,ip;
String usernam,passwordd;
//End Declaring connection variables
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
// Getting values from button, texts and progress bar
login = (Button) findViewById(R.id.btn_Login);
username = (EditText) findViewById(R.id.et_username);
password = (EditText) findViewById(R.id.et_password);
progressBar = (ProgressBar) findViewById(R.id.pbbar);
progressBar.setVisibility(View.GONE);
// End Getting values from button, texts and progress bar
// Declaring Server ip, username, database name and password
ip = "***";
db = "***";
un = "***";
pass = "***";
// Declaring Server ip, username, database name and password
// Setting up the function when button login is clicked
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
usernam = username.getText().toString();
passwordd = password.getText().toString();
CheckLogin checkLogin = new CheckLogin();// this is the Asynctask, which is used to process in background to reduce load on app process
checkLogin.execute("");
}
});
//End Setting up the function when button login is clicked
}
public class CheckLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute()
{
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r)
{
progressBar.setVisibility(View.GONE);
Toast.makeText(database.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess)
{
Toast.makeText(database.this , "Login Successfull" , Toast.LENGTH_LONG).show();
//finish();
}
}
#Override
protected String doInBackground(String... params)
{
if(usernam.trim().equals("")|| passwordd.trim().equals(""))
z = "Please enter Username and Password";
else
{
try
{
con = connectionclass(un, pass, db, ip); // Connect to database
if (con == null)
{
z = "Check Your Internet Access!";
}
else
{
String query = "select * from login where username= '" + usernam.toString() + "' and password = '"+ passwordd.toString() +"' ";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successful";
isSuccess=true;
con.close();
}
else
{
z = "Invalid Credentials!";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = ex.getMessage();
}
}
return z;
}
}
#SuppressLint("NewApi")
public Connection connectionclass(String user, String password, String database, String server)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
ConnectionURL = "jdbc:jtds:sqlserver://sql5009.mywindowshosting.com;database=DB_A2C00B_login;user=DB_A2C00B_login_admin;password=login#123";
// ConnectionURL =
"jdbc:jtds:sqlserver://192.168.1.9;database=msss;instance=SQLEXPRESS;Network
Protocol=NamedPipes" ;
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return connection;
}
}
To connect an Android App with a SQL server, you'll need to set up a web (Http) server in between the two. You can build this web server in any language you're familiar with be it java (J2EE) or php etc.
This web server will be hosted with your SQL server and will take Http requests from the Android app, process it, forward the request as queries to your SQL server and then return it back to your app as REST/JSON (the current format of sending data over the web) or SOAP/XML (the old way of sending data over the web).
App >> Web Server >> Database Server
The web server should be RESTful and the app can interact with it via Http requests via the library Retrofit2.
Here's some resources to get you started;
Retrofit by Square.
Retrofit Github repository.
Simple CRUD example with Java RESTful Web Service, a brief tutorial.
RESTful Web Services: A Tutorial Android + Java Web Services
if you are using android studio or eclipse you should put the jtds jar file in the correct location
it is in the libs (library) folder inside app n your project. Once you put it in the libs > right click then add library.
another note you should use 1.2.7 or lower which is much supported
I'm just starting to use Android Studio and allready having trouble, I need to conect to a database on sqlserver via my cellphone, but it crashes before the whole thing starts to work, I need a little help please, here is the code:
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class Farmaciapp extends AppCompatActivity {
EditText edtMed =(EditText)findViewById(R.id.edtMedicamento);
String ConsulMed = edtMed.getText().toString();
public void Meds (View v){
Connection conexion = null;
String url = "jdbc:jtds:sqlserver://192.168.1.69;databaseName=Medicamentos;";
String query = "Select Descripcion from Medicina where Nombre = '" + ConsulMed + "'";
try {
Connection con = DriverManager.getConnection(url);
Statement state = con.createStatement();
ResultSet resultado = state.executeQuery(query);
while (resultado.next()){
String res = resultado.getString(1);
TextView Explicacion = (TextView) findViewById(R.id.mltExplic);
Explicacion.setText(res);
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.getMessage() , Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_farmaciapp);
}
}
The reason is you are trying to access which haven't yet created. Or in another word we can't reference or call findViewById until the layout is inflated.
so make below changes
public class Farmaciapp extends AppCompatActivity {
EditText edtMed;
String ConsulMed = edtMed.getText().toString();
public void Meds (View v){
Connection conexion = null;
String url = "jdbc:jtds:sqlserver://192.168.1.69;databaseName=Medicamentos;";
String query = "Select Descripcion from Medicina where Nombre = '" + ConsulMed + "'";
try {
Connection con = DriverManager.getConnection(url);
Statement state = con.createStatement();
ResultSet resultado = state.executeQuery(query);
while (resultado.next()){
String res = resultado.getString(1);
TextView Explicacion = (TextView) findViewById(R.id.mltExplic);
Explicacion.setText(res);
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.getMessage() , Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_farmaciapp);
edtMed =(EditText)findViewById(R.id.edtMedicamento);
}
}
make sure to access edtMed after onCreate not before that will work. onCreate() is the way for activity to inflate the layout.
You need to Do findViewById inside onCreate() method
Declare your EditText edtMed as global
EditText edtMed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_farmaciapp);
edtMed =(EditText)findViewById(R.id.edtMedicamento);
}
Also get text from your EditText inside Meds (View v)
public void Meds (View v){
String ConsulMed = edtMed.getText().toString();
Connection conexion = null;
String url = "jdbc:jtds:sqlserver://192.168.1.69;databaseName=Medicamentos;";
String query = "Select Descripcion from Medicina where Nombre = '" + ConsulMed + "'";
try {
Connection con = DriverManager.getConnection(url);
Statement state = con.createStatement();
ResultSet resultado = state.executeQuery(query);
while (resultado.next()){
String res = resultado.getString(1);
TextView Explicacion = (TextView) findViewById(R.id.mltExplic);
Explicacion.setText(res);
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.getMessage() , Toast.LENGTH_SHORT).show();
}
}
I was following this tutorial (http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/) to create a user login and registration for an application using volly. Everything works fine when I make it a stand alone app with no other features. The issue starts when I try integrate it with another application.
I am copying the classes produced from the tutorial straight into an existing project but I am getting a null pointer. Now before I go any further, I know what a null pointer is and I know how to solve them.
I am new-ish to Android and I am having trouble finding this one and would greatly appreciate some help with it rather then people just directing me to here -What is a NullPointerException, and how do I fix it? - as I have already looked at this but it still doesnt help me locate this error.
Login Activity
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import com.example.rory.pocketchef.R;
import com.example.rory.pocketchef.app.AppConfig;
import com.example.rory.pocketchef.app.AppController;
import com.example.rory.pocketchef.helper.SQLiteHandler;
import com.example.rory.pocketchef.helper.SessionManager;
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, FirstActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this, FirstActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
AppController
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Android Manifest
<uses-permission android:name="android.permission.INTERNET" />
<android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
<android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_logo"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/MyMaterialTheme" >
<activity
android:name=".activity.LoginActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SingleRecipeDisplay"
android:label="#string/title_activity_single_recipe_display"
android:theme="#style/MyMaterialTheme" >
</activity>
<activity android:name=".Favourites" >
</activity>
<activity android:name=".Help" >
</activity>
<activity android:name=".activity.RegisterActivity">
</activity>
</application>
Error
java.lang.NullPointerException: Attempt to invoke virtual method 'void
com.example.rory.pocketchef.app.AppController.addToRequestQueue(com.android.volley.Request,
java.lang.String)' on a null object reference 02-22 15:03:54.296
13823-13823/com.example.rory.pocketchef E/AndroidRuntime: at
com.example.rory.pocketchef.activity.LoginActivity.checkLogin(LoginActivity.java:183)
02-22 15:03:54.296 13823-13823/com.example.rory.pocketchef
E/AndroidRuntime: at
com.example.rory.pocketchef.activity.LoginActivity.access$200(LoginActivity.java:30)
02-22 15:03:54.296 13823-13823/com.example.rory.pocketchef
E/AndroidRuntime: at
com.example.rory.pocketchef.activity.LoginActivity$1.onClick(LoginActivity.java:78)
Your application instance is null. It's Singleton class but instance is never created.
Problem is that you missed to add name in <application> tag. Name should be AppController or even better full package path of AppController.
[EDIT]
And use this instead getApplicationContext() in AppController.
I am trying to make an persistent login application which then read sms from my phone and sends them to the an api with meaage body as well as the date and sender information. How can I proceed for the same.
I have made the login app but persistent login like facebook and other applications is not working.
Here is my code for the login application:
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
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 org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class LoginActivity extends ActionBarActivity {
private EditText un,pw;
private Button sign;
private TextView msg;
private String resp, errorMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
un = (EditText) findViewById(R.id.et_Username);
pw = (EditText) findViewById(R.id.et_Password);
sign = (Button) findViewById(R.id.bt_SignIn);
msg = (TextView) findViewById(R.id.tv_error);
sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/**
* According with the new StrictGuard policy, running long tasks
* on the Main UI thread is not possible So creating new thread
* to create and execute http operations
*/
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",
un.getText().toString()));
postParameters.add(new BasicNameValuePair("password",
pw.getText().toString()));
String response = null;
try {
response = SimpleHttpClient
.executeHttpPost(
url,
postParameters);
String res = response.toString();
System.out.println(res);
resp = res.replaceAll("\\s+", "");
} catch (Exception e) {
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try {
Thread.sleep(1000);
/**
* Inside the new thread we cannot update the main thread So
* updating the main thread outside the new thread
*/
msg.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty()) {
msg.setText(errorMsg);
}
} catch (Exception e) {
msg.setText(e.getMessage());
}
}
});
}
#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);
}
}
I tried this now,got the idea for shred prefernece but somewhow its not working for me
I tried this it doesn't show my main activity:
Can you find the problem:
MainActivity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class MainActivity extends Activity {
private String resp, errorMsg;
private EditText username,password;
/*public static final String MyPREFERENCES = "MyPrefs" ;
public static final String name = "nameKey";
public static final String pass = "passwordKey";
SharedPreferences sharedpreferences;*/
SessionManager session;
private TextView msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.editText1);
password = (EditText)findViewById(R.id.editText2);
msg = (TextView) findViewById(R.id.tv_error);
session = new SessionManager(this);
}
#Override
protected void onResume() {
//sharedpreferences=getSharedPreferences(MyPREFERENCES,
// Context.MODE_PRIVATE);
if (session.getuser()!=null)
{
if(session.getpassword()!=null){
Intent i = new Intent(this,
Welcome.class);
startActivity(i);
}
}
super.onResume();
}
public void login(View view){
String u = username.getText().toString();
String p = password.getText().toString();
{
/**
* According with the new StrictGuard policy, running long tasks
* on the Main UI thread is not possible So creating new thread
* to create and execute http operations
*/
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",
username.getText().toString()));
postParameters.add(new BasicNameValuePair("password",
password.getText().toString()));
String response = null;
try {
response = SimpleHttpClient
.executeHttpPost(
"<url>",
postParameters);
String res = response.toString();
//System.out.println(res);
resp = res.replaceAll("\\s+", "");
} catch (Exception e) {
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try {
Thread.sleep(1000);
/**
* Inside the new thread we cannot update the main thread So
* updating the main thread outside the new thread
*/
msg.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty()) {
msg.setText(errorMsg);
}
} catch (Exception e) {
msg.setText(e.getMessage());
}
}
if (resp.contains("false")) {
session.saveSession(u, p);
}
}
#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;
}
}
Welcome:
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class Welcome extends Activity {
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
session = new SessionManager(this);
}
#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);
return true;
}
public void logout(View view){
session.logoutUser();
moveTaskToBack(true);
Welcome.this.finish();
}
public void exit(View view){
moveTaskToBack(true);
Welcome.this.finish();
}
public List<Sms> getAllSms() {
List<Sms> lstSms = new ArrayList<Sms>();
Sms objSms = new Sms();
Uri message = Uri.parse("content://sms/inbox");
ContentResolver cr = this.getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
this.startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
if(c.getString(c.getColumnIndexOrThrow("address")).contains("icicib")|| c.getString(c.getColumnIndexOrThrow("address")).contains("hdfcbk") || c.getString(c.getColumnIndexOrThrow("address")).contains("dbalrt")
||c.getString(c.getColumnIndexOrThrow("address")).contains("citibk")||c.getString(c.getColumnIndexOrThrow("address")).contains("unionb")||c.getString(c.getColumnIndexOrThrow("address")).contains("atmsbi")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("sbiinb") || c.getString(c.getColumnIndexOrThrow("address")).contains("indusb") ||c.getString(c.getColumnIndexOrThrow("address")).contains("fedbnk")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("kotakb")||c.getString(c.getColumnIndexOrThrow("address")).contains("axisbk")||c.getString(c.getColumnIndexOrThrow("address")).contains("pnbsms")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("hsbcin") || c.getString(c.getColumnIndexOrThrow("address")).contains("canbnk") || c.getString(c.getColumnIndexOrThrow("address")).contains("idbi")
||c.getString(c.getColumnIndexOrThrow("address")).contains("iob") || c.getString(c.getColumnIndexOrThrow("address")).contains("citibk") || c.getString(c.getColumnIndexOrThrow("address")).contains("hdfcbk")
||c.getString(c.getColumnIndexOrThrow("address")).contains("fromsc") ||c.getString(c.getColumnIndexOrThrow("address")).contains("myamex") || c.getString(c.getColumnIndexOrThrow("address")).contains("26463872")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("sbicrd") || c.getString(c.getColumnIndexOrThrow("address")).contains("icici?") || c.getString(c.getColumnIndexOrThrow("address")).contains("syndbk")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("121") || c.getString(c.getColumnIndexOrThrow("address")).contains("best deal(121)") || c.getString(c.getColumnIndexOrThrow("address")).contains("airtel")
|| c.getString(c.getColumnIndexOrThrow("address")).contains("vfcare") || c.getString(c.getColumnIndexOrThrow("address")).contains("vodafone") || c.getString(c.getColumnIndexOrThrow("address")).contains("mytsky")||c.getString(c.getColumnIndexOrThrow("address")).contains("dishpy") ) {
objSms = new Sms();
objSms.setAddress(c.getString(c .getColumnIndexOrThrow("address")));
objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
lstSms.add(objSms);
}
c.moveToNext();
}
}
// else {
// throw new RuntimeException("You have no SMS");
// }
c.close();
return lstSms;
}
}
SessionManager:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREFER_NAME = "AndroidExamplePref";
public static final String KEY_USER = "username";
public static final String KEY_PWD = "password";
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void saveSession(String user, String pwd){
editor.putString(KEY_USER, user);
editor.putString(KEY_PWD, pwd);
editor.commit();
}
public String getuser()
{
String s = pref.getString(KEY_USER,"");
return s;
}
public String getpassword()
{
String p = pref.getString(KEY_PWD,"");
return p;
}
public void logoutUser(){
editor.clear();
editor.commit();
Intent i = new Intent(_context,.MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package=".sample" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.read_sms" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Welcome"
android:label="#string/title_activity_welcome" >
</activity>
</application>
</manifest>
UPDATED ANSWER:
IT works now
i made session as static and before logging I am checking the shared preference value and accordingly going ahead. Everything is working now.
I guess you are meaning "persistent login application" -> User will log in once & for the next time they will not need to log in again with user name & password, right?
For this the naive approach would be storing the username & password in shared preference / db. But its not a good approach as it stores the password.
Instead of doing this, you can store, the userId/access token (obtained from the response). You should also have an expiration time so that you can prompt for log in validating the userId/access token after certain time.
Facebook seems to do the same thing I guess. E.g. if you clear data from on facebook app, then you does need to log in again.
I hope this gives you a direction.
Updated Answer
I guess you are not clear about pref.getString() method. The overloaded method (with 2 param) will return the 2nd param you sent, if any value with the query KEY (the 1st param)is not found.
In your case, in
public String getuser()
{
String s = pref.getString(KEY_USER,""); // here is the error, "" is not null, its an empty String.
return s;
}
So you can change this trouble causing line into either of the following line-
String s = pref.getString(KEY_USER,null);
or
String s = pref.getString(KEY_USER);
Same problem in the getuser(). Hopefully this will solve your problem :)
I'm trying to connect to a database on a sql server using jTDS-1.2.5. I know that this is dangerous and insecure, and I shouldn't be doing it this way, but I just want to try it, so humor me. To test jTDS I wrote this code in netbeans:
package dbconnecttest;
import java.sql.*;
import net.sourceforge.jtds.jdbc.*;
import net.sourceforge.jtds.jdbcx.*;
public class DBConnectTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
String connString = "jdbc:jtds:sqlserver://MY_SERVER_NAME:24923/Phone_Test;user=testLogin;password=xxxxxxxx;instance=MYINSTANCE";
con = DriverManager.getConnection(connString,"testLogin","xxxxxxxx");
try {
PreparedStatement stmt = con.prepareStatement("SELECT * FROM Product_Inventory_Test WHERE ProductTest = 'Car'");
stmt.execute();
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
System.out.println(rs.getString("ProductTest").replace(" ", "") + " price: $" + rs.getString("PriceTest"));
}
stmt.close();
} catch (Exception e) {
System.out.println("Statement error: " + e.getMessage());
}
con.close();
}
catch (Exception e) {
System.out.println("Connection Error: " + e.getMessage());
}
}
}
Notice, I am connecting on a port other than 1433. I have enabled TCP/IP in the configuration manager, and set the TCP port for all the IP address to 24923. I also made sure it wasn't dynamically assigning TCP ports. This code works fine in netbeans, and it pulls the data from the database without any problems. I'm using similar code in eclipse on my android app:
package com.xxxxxx.xxxxxx;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import net.sourceforge.jtds.jdbc.*;
import net.sourceforge.jtds.jdbcx.*;
public class LoginActivity extends Activity {
TextView labelLogin;
TextView labelError;
EditText txtUsername;
EditText txtPassword;
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Assign properties to login form views
labelLogin = (TextView)findViewById(R.id.labelLogin);
labelError = (TextView)findViewById(R.id.labelError);
txtUsername = (EditText)findViewById(R.id.txtUsername);
txtPassword = (EditText)findViewById(R.id.txtPassword);
btnLogin = (Button)findViewById(R.id.btnLogin);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#SuppressWarnings("deprecation")
public void login_onClick(View view) {
Connection con = null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
String connString = "jdbc:jtds:sqlserver://MY_SERVER_NAME:24923/Phone_Test;user=testLogin;password=xxxxxxxx;instance=MYINSTANCE";
String username = "testLogin";
String password = "xxxxxxxx";
con = DriverManager.getConnection(connString,username,password);
PreparedStatement stmt = null;
try {
//Prepared statement
stmt = con.prepareStatement("SELECT * FROM Logins WHERE Username = ? AND Password = ?");
stmt.setString(1, txtUsername.toString());
stmt.setString(2, txtPassword.toString());
stmt.execute();
ResultSet rs = stmt.getResultSet();
if(rs.next()) {
//Start new activity
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setTitle("Success!");
ad.setMessage("You have logged in successfully!");
ad.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
}
stmt.close();
}
catch (Exception e) {
stmt.close();
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setTitle("Error");
ad.setMessage("Prepared statement error: " + e.getMessage());
ad.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
}
con.close();
}
catch (Exception e) {
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setTitle("Error");
ad.setMessage("Connection error: " + e.getMessage());
ad.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
}
}
}
I have added the jar file to the classpath, and everything seems to work fine. When I run the app on an emulator, though, it gives me the error:
Connection Error: Unable to get information from SQL Server: MY_SERVER_NAME.
I'm kinda stuck on what to do next. Everything seems to be working fine, it just won't connect. I've tried going to command prompt and trying sqlcmd -L, and it has my server in the list. I can also telnet into my server from there. netstat -an shows that it's listening on port 24923 with local ip address 0.0.0.0. I'm just not sure what the problem is, and I've checked the jTDS FAQ tips about resolving this error already. Any ideas/suggestions?