catch exception while connecting android application to mysql using jdbc - java

public class MainActivity extends Activity {
Button login,signup;
EditText name,pass;
ResultSet res;
int a=0;
setting id to the views in xml page
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login=(Button)findViewById(R.id.login);
signup=(Button)findViewById(R.id.sign);
name=(EditText)findViewById(R.id.username);
pass=(EditText)findViewById(R.id.password);
establishing mysql connection on "login" button click.
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String n=name.getText().toString();
String p=pass.getText().toString();
Connection co
Statement st;
try
{
Class.forName("com.mysql.jdbc.Driver")
co =DriverManager.getConnection("jdbc:mysql://localhost /mcon","root","");
retriving the data from login "table" in mysql.i have stored two fields in login table for username and password with same value "admin".On the login button click the page will directed to admin page if the user enter correct admin, admin in the edit text.
st = co.createStatement();
res=st.executeQuery("select * from login");
Boolean rec = res.next();
if (!rec)
{
Toast.makeText(getApplication(),"norecordinthetable",
Toast.LENGTH_LONG).show( );
}
else {
do {
String s3 = res.getString(1);
String s4 = res.getString(2);
if (n.equals(s3) && p.equals(s4))
Intent iii=new Intent(MainActivity.this,Admin.class);
startActivity(iii);
a = 1;
break;
}
} while (res.next());
}
if (a == 0)
{
Toast.makeText(getApplication(),"wrongName/Password",
Toast.LENGTH_LONG).show();
name.setText("");
pass.setText("");
}
st.close();
co.close();
} catch (Exception e) {
Toast.makeText(getApplication(), "error",Toast.LENGTH_LONG).show();
}
}
});

the jdbc is really a overdue framework,try to use some new ones like mybaits. You will get much more help for the widely using of mybaits.

Make Sure you have mysql-connector-java-3.0.17-ga-bin.jar driver.
Check for permissions in the androidManifest.xml file.

Related

How to autoincrement userID in Firestore?

So I created a booking app which sends data into booking collection taking userID as Document Name.
But when the user books again it overwrites the previous booking userID document.
What I want to do is: 1) Implement autoincrement on userID, and also 2) display the autoincremented booking too
(Notice I'm using userID because I want to keep it unique to that user only).
3) I also want to implement a limit on booking if someone can help with that.
Firestore Firebase Image:
The code to send data into BOOKING COLLECTION and creating DOCUMENT with userID:
public class bookingpage extends AppCompatActivity {
EditText mFirstnamelastname,mMobnum,mPincode,mFlatno,mArea,mLandmark,mTown,mState;
Button mBook;
String userID;
FirebaseAuth fAuth;
FirebaseFirestore fstore;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookingpage);
//pickup
mFirstnamelastname=findViewById(R.id.firstlastname);
mMobnum=findViewById(R.id.mobnum);
mPincode=findViewById(R.id.pincode);
mFlatno=findViewById(R.id.flatno);
mArea=findViewById(R.id.area);
mLandmark=findViewById(R.id.landmark);
mTown=findViewById(R.id.town);
mState=findViewById(R.id.state);
mBook=findViewById(R.id.editbook);
progressBar=findViewById(R.id.progressBar4);
fAuth=FirebaseAuth.getInstance();
fstore=FirebaseFirestore.getInstance();
mBook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//pickup
String firstname = mFirstnamelastname.getText().toString().trim();
String phoneno = mMobnum.getText().toString().trim();
String pincode = mPincode.getText().toString().trim();
String flatno = mFlatno.getText().toString().trim();
String area = mArea.getText().toString().trim();
String landmark = mLandmark.getText().toString().trim();
String town = mTown.getText().toString().trim();
String state = mState.getText().toString().trim();
progressBar.setVisibility(View.VISIBLE);
//saving data
userID=fAuth.getCurrentUser().getUid();
//creating a document reference creating a collection booking and making a new doc using user id
DocumentReference documentReference = fstore.collection("Booking").document(userID);
//creating a hashmap to send data
Map<String,Object> book = new HashMap<>();
//setting status
book.put("Status -","Active");
//pickup
book.put("a1 - Fullname",firstname);
book.put("a2 - PhoneNo",phoneno);
book.put("a3 - Pincode",pincode);
book.put("a4 - Flatno",flatno);
book.put("a5 - Area",area);
book.put("a6 - Landmark",landmark);
book.put("a7 - Town",town);
book.put("a8 - State",state);
//using the document reference to set user document
documentReference.set(book).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(bookingpage.this, "Booking Successful", Toast.LENGTH_SHORT).show();
Log.d("Tag","onSuccess: Successfully booked for "+ userID);
startActivity(new Intent(getApplicationContext(),MainActivity2.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(bookingpage.this, "Error!" + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
progressBar.setVisibility(View.INVISIBLE);
}
});
}
}
The code to display the booking collection's document with userID:
final DocumentReference documentReference = fstore.collection("Booking").document(userID);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
//putting if else fixed crashing
if (e != null) {
Log.d("Tag", "Error:" + e.getMessage());
} else {
mStatus.setText(documentSnapshot.getString("Status -"));
mFirstnamelastname.setText(documentSnapshot.getString("a1 - Fullname"));
mMobnum.setText(documentSnapshot.getString("a2 - PhoneNo"));
mPincode.setText(documentSnapshot.getString("a3 - Pincode"));
mFlatno.setText(documentSnapshot.getString("a4 - Flatno"));
mArea.setText(documentSnapshot.getString("a5 - Area"));
mLandmark.setText(documentSnapshot.getString("a6 - Landmark"));
mTown.setText(documentSnapshot.getString("a7 - Town"));
mState.setText(documentSnapshot.getString("a8 - State"));
}
}
});
I'm a beginner please try to explain your answer so that I can understand & learn more :)
Well... you just shouldn't use the UserId's as document names in the Booking collection. It's just goes against logic and best-practices.
You should instead let Firestore create a BookingId. It would be your current booking document + a new field (String) holding the UserId of the user who made the booking.
This would be a more logical (and scalable) way.
To limit the number of bookings, you could add a field in your UserId documents (in users collection), called bookingCount (Integer). Each time a User books, check if the bookingCount >= bookingLimit (arbitrary value of your choosing).
If bookingCount < bookingLimit, then allow them to book and increment the bookingCount by 1.

Firebase Database Reference Error: No such instance field: 'mDatabaseReference'

I'm using Firebase Realtime Database to store data for a project. I'm using Android Studio and Java to create a mobile app. In this particular activity, a new user is filling out a form to sign up for the service. Once they input their info and hit the submit button, the on click handles that info and inserts it into the Database.
Here is the relevant code for that class:
public class CreateUserActivity extends AppCompatActivity {
private DatabaseReference mDatabaseReference;
private List<String> mInterestList;
private EditText mUsername;
private EditText mPassword;
private EditText mEmail;
private EditText mLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mInterestList = new ArrayList<>();
mUsername = findViewById(R.id.text_username);
mPassword = findViewById(R.id.text_password);
mEmail = findViewById(R.id.text_email);
mLocation = findViewById(R.id.text_location);
}
public void onCheckboxClicked(View view) {
CheckBox checkbox = (CheckBox) view;
boolean isChecked = checkbox.isChecked();
String interest = checkbox.getText().toString();
if(isChecked) {
mInterestList.add(interest);
}else {
mInterestList.remove(interest);
}
}
public void onSaveUser(View view) {
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
String email = mEmail.getText().toString();
String location = mLocation.getText().toString();
if(TextUtils.isEmpty(username) ||
TextUtils.isEmpty(password) ||
TextUtils.isEmpty(email) ||
TextUtils.isEmpty(location) ||
mInterestList.size() == 0) {
displayToast("Please enter values for all fields");
}else {
List<String> interests = mInterestList;
User user = new User(username, password, email, location, interests, null);
mDatabaseReference.child("users").child(username).setValue(user, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(#Nullable DatabaseError databaseError, #NonNull DatabaseReference databaseReference) {
if(databaseError != null) {
Log.e(GetTogetherApp.LOG_TAG, databaseError.getMessage());
}else{
displayToast("User created!");
}
}
});
}
}
As I've run through breakpoints the error seems to fire on this line:
mDatabaseReference.child("users").child(username).setValue()
Specifically once I try and enter into the setValue() method. The other two child() calls work to find the path as intended. I have the database reference set as a member variable, so I'm not sure why it seems to lose it at that point.
Here's a look at my database structure
Firebase Database Structure Pic
Error in Android Studio:
The error message in your screenshot is in the variable inspector in the Android Studio debugger. It means that where the error occurs, there is no variable mDatabaseReference so the debugger can't show its value. This is not the actual cause of the crash, merely the debugger telling you that it can't show you something you asked for.
You can find the actual cause of the problem by inspecting the InvocationTargetException e.

Register page else/if

I am very new to java and need some help. I would like to add a function to this register page where users cannot leave their password and username fields blank. I would very much appreciate it if you could type the lines of code as it would be easier for me to visualize.
I have tried implementing else if to this page but it doesn't work and there is no error as well, so i removed those codes. Those codes does not appear in the lines of code i have shown here.Cheers
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
db = new DatabaseHelper(this);
mTextUsername = (EditText)findViewById(R.id.edittext_username);
mTextPassword = (EditText)findViewById(R.id.edittext_password);
mTextCnfPassword = (EditText)findViewById(R.id.edittext_cnf_password);
mButtonRegister = (ImageButton)findViewById(R.id.imagebutton_register);
mTextViewLogin = (TextView)findViewById(R.id.textview_login);
mTextViewLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent LoginIntent = new Intent(RegisterActivity.this,LoginPageActivity.class);
startActivity(LoginIntent);
}
});
mButtonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = mTextUsername.getText().toString().trim();
String pwd = mTextPassword.getText().toString().trim();
String cnf_pwd = mTextCnfPassword.getText().toString().trim();
if(pwd.equals(cnf_pwd)) {
Long val = db.adduser(user,pwd);
if(val > 0){
Toast.makeText(RegisterActivity.this,"Successfully Registered.",Toast.LENGTH_SHORT).show();
Intent movetoLogin = new Intent(RegisterActivity.this,LoginPageActivity.class);
startActivity(movetoLogin);
}
else{
Toast.makeText(RegisterActivity.this,"Registration Error.",Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(RegisterActivity.this,"Those passwords didn't match.Try Again.",Toast.LENGTH_SHORT).show();
}
}
});
}
}
You can use the required attribute in html to avid those fields being left blanked.If you use this then you will not need a code to handle blank fields but it will control that situation in the frontend itself.
Refer here how to use it : required attribute
Have you tried make a length comparisson ?
Change this line: if(pwd.equals(cnf_pwd)) { to
if(pwd.length() > 0 && user.length() > 0 && pwd.equals(cnf_pwd)) {
There is no need to make it that complicated. After declaring strings,You can use
if(pwd.isEmpty() || user.isEmpty() )
{
Toast.makeText(RegisterActivity.this,"Enter Username and Password",Toast.LENGTH_SHORT).show();
}
else
{
if{pwd.equals(cnf_pwd))
{
Toast.makeText(RegisterActivity.this,"Successfully Registered.",Toast.LENGTH_SHORT).show();
Intent movetoLogin = new Intent(RegisterActivity.this,LoginPageActivity.class);
startActivity(movetoLogin);
}
else
{
Toast.makeText(RegisterActivity.this,"Make sure Password Entered is same",Toast.LENGTH_SHORT).show();
}
}

NumberFormatException in Android

I'm making an application in which the user can add Store departments and for those departments the ability to add the cities of where the departments are located.
I keep on getting a NumberFormatException when I'm trying to add a city for a departement:
Caused by: java.lang.NumberFormatException: Invalid long: "null"
at java.lang.Long.invalidLong(Long.java:124)
at java.lang.Long.parseLong(Long.java:345)
at java.lang.Long.parseLong(Long.java:321)
at org.hello.addgroups.vestiging_list.onCreate(vestiging_list.java:45)
after this the app crashes but when I restart the app the values are added into the list.
these are my classes:
Add_vestiging.java:
public class Add_vestiging extends Activity implements View.OnClickListener{
EditText et,hiddenet;
Button add_bt, cancel_btn;
SQLController dbcon;
Intent i;
Long groupd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_vestiging);
et = (EditText)findViewById(R.id.vestigingName);
add_bt = (Button) findViewById(R.id.addBtn);
cancel_btn = (Button) findViewById(R.id.cancelBtn);
dbcon = new SQLController(this);
try {
dbcon.open();
} catch(SQLException e) {
e.printStackTrace();
}
i = getIntent();
String id = i.getStringExtra("groupID");
groupd = Long.parseLong(id);
add_bt.setOnClickListener(this);
cancel_btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.addBtn:
String name = et.getText().toString();
try {
dbcon.insertVestiging(groupd, name);
}catch(SQLiteException e) {
e.printStackTrace();
}
Intent main = new Intent(Add_vestiging.this, vestiging_list.class);
startActivity(main);
break;
case R.id.cancelBtn:
super.finish();
break;
}
}
}
vestiging_list.java:
public class vestiging_list extends Activity {
ListView lv;
SQLController dbcon;
TextView title;
Button addves;
Long long_id;
String groupid;
Intent add_ves;
String groupname;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vestiging_list);
dbcon = new SQLController(this);
title = (TextView) findViewById(R.id.vestitel);
try {
dbcon.open();
} catch (SQLException e) {
e.printStackTrace();
}
add_ves = getIntent();
groupid = add_ves.getStringExtra("groupID");
groupname = add_ves.getStringExtra("groupName");
title.setText(groupname);
long_id = Long.parseLong(groupid);
addves = (Button)findViewById(R.id.addves_bt_id);
lv = (ListView)findViewById(R.id.vestigingList_id);
addves.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add_ves = new Intent(getApplicationContext(), Add_vestiging.class);
add_ves.putExtra("groupID", groupid);
startActivity(add_ves);
}
});
Cursor cursor = dbcon.readVestigingen(long_id);
String[] from = new String[] { GroupDatabaseHelper.V_ID, GroupDatabaseHelper.VESNAME};
int[] to = new int [] { R.id.vesID, R.id.vesName};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(vestiging_list.this, R.layout.vestiging_single_row_item, cursor, from, to,1);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
}
Any ideas on how to remove the NumberFormatException?
Any help is greatly appreciated.
Thanks in advance.
Any ideas on how to remove the NumberFormatException?
The exception is caused by Long.parseLong in vestiging_list at line 45. The reason is that groupid, in your case in null. Since you didn't fill up the Intent object you used to start vestiging_list.
E.g.
case R.id.addBtn:
String name = et.getText().toString();
try {
dbcon.insertVestiging(groupd, name);
}catch(SQLiteException e) {
e.printStackTrace();
}
Intent main = new Intent(Add_vestiging.this, vestiging_list.class);
main.putExtra("groupID", String.valueOf(groupd));
startActivity(main);
break;
assuming that groupd is a long.
I think problem is in the following line :
int[] to = new int [] { R.id.vesID, R.id.vesName};
What is the type of "R.id.vesName" ?. It should be integer.
From the stack trace that you have provided I can assume that groupId is null:
groupid = add_ves.getStringExtra("groupID");
...
long_id = Long.parseLong(groupid);
According to the Long's Javadoc Long#parseLong(String) throws an Exception if the argument is not a parsable Long, sth which is the case with null.
Check if groupid can be null else you have a bug. If it can be null then check if it equals null and then set long_id to an appropriate value e.g. 0 or -1.
It looks to me like you're creating an Intent, but you're not passing the info to the intent. The class reference to the current class is just a trace, and doesn't include info.
When you make the Intent in the Add_vestiging class, in onClick, do something like main.putExtra("groupID", id).
Looks like you're putting it in the SQLController, so you could try passing that as well.

How to store the .txt file in SQLite Android

I created application of write and read file. when i click button ,my file is write and also read the file on the same button click.I want as and when my file is write , that file is save it into SQLite.I'm surfing lot of on the net but can't find proper source or ideas how to do this.And that file is compare with input String something like "code" . If this input_String is match with that file which is store in the SQLite database , if match user can't go ahead for the further process.I would appreciate if anybody out there is capable of giving me some advice on this one and I hope other people find this helpful too.Here is my code.Thanks in Advanced.
The Activity class
public class Write extends Activity {
/** Called when the activity is first created. */
EditText myText;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
myText = (EditText) findViewById(R.id.myText);
Button createButton = (Button) findViewById(R.id.btnCreate);
Button readButton = (Button) findViewById(R.id.btnRead);
createButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
createFile(myText.getText().toString());
myText.setText("");
readFile();
}
});
}
private void createFile(String Text)
{
FileOutputStream fos = null;
try
{
fos = openFileOutput("mynote.txt", MODE_PRIVATE);
fos.write(Text.getBytes());
Toast.makeText(getApplicationContext(), "File created succesfully",
Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e)
{
Log.e("CreateFile", e.getLocalizedMessage());
}
catch (IOException e)
{
Log.e("CreateFile", e.getLocalizedMessage());
}
finally
{
if (fos != null)
{
try
{
// drain the stream
fos.flush();
fos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
And the DataBase_Adapter code
//Table Name
public static final String TABLE_NAME_CODE="code_table";
//Colum,n Names
public static final String KEY_CODE_ID="ID";
public static final String KEY_CODE_NAME="USERNAME";
//Table Create Statement
public static final String DATABASE_CREATE_CODE = "CREATE TABLE "+TABLE_NAME_CODE+" ("+KEY_CODE_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+KEY_CODE_NAME+"TEXT)";
//Insert Code in Database code_table
public void saveCode(String strKey_Code)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(KEY_CODE_NAME , strKey_Code);
// Insert the row into your table
db.insert(TABLE_NAME_CODE, null, newValues);
}
The approach you have taken could be improved a little bit, consider storing in the database only the name of the files, you already have the files saved, right? why store their content again in the database?

Categories

Resources