As the title says, I have encountered that error when I tried working with Firebase database. I have tried numerous solutions found online but nothing seems to have worked for me. Below you can find my code and also, a brief information regarding on what I've tried so far before posting on stackOverflow.
The code is the following:
package com.example.vlad.restaurantorder;
import android.app.ProgressDialog;
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 com.example.vlad.restaurantorder.Model.User;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.rengwuxian.materialedittext.MaterialEditText;
public class LogIn extends AppCompatActivity {
EditText editPhone, editPassword;
Button btnLogIn;
FirebaseDatabase database;
DatabaseReference tableUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
btnLogIn = (Button)findViewById(R.id.btnLogInScreenLogIn);
editPhone = (MaterialEditText)findViewById(R.id.edtPhone);
editPassword = (MaterialEditText)findViewById(R.id.edtPassword);
//database
database = FirebaseDatabase.getInstance();
tableUser = database.getReference("User");
btnLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog progressDialog = new ProgressDialog(LogIn.this);
progressDialog.setMessage("Please wait...");
progressDialog.show();
tableUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(editPhone.getText().toString()).exists()){
progressDialog.dismiss();
User user = dataSnapshot.child(editPhone.getText().toString()).getValue(User.class);
if(user.getPassword().equals(editPassword.getText().toString())){
Toast.makeText(getApplicationContext(), "You are logged in!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Log in failed!", Toast.LENGTH_SHORT).show();
}
}
else {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "User does not exists!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
}
What I have tried so far before posting here: Disabling proGuard and putting minifyEnable on false in build.gradle in debug{}; Restarting android studio, as I've read other people's posts who also encountered the problem said that this worked for them; On line where I used tableUser = database.getReference("User"); I also tried using tableUser = database.getReference().child("User");
Any help is much appreciated. Thank you very much
Later edit: adding the LogIn activity xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/login_screen_image"
tools:context="com.example.vlad.restaurantorder.LogIn">
<LinearLayout
android:orientation="vertical"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtPhone"
android:hint="Phone Number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#android:color/white"
android:text="0293292442"
android:textColor="#android:color/white"
android:textSize="34sp"
android:inputType="phone"
app:met_floatingLabel="highlight"
app:met_baseColor="#android:color/white"
app:met_maxCharacters="11"
app:met_primaryColor="#android:color/white"
app:met_singleLineEllipsis="true"
/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtPassword"
android:hint="Password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="#android:color/white"
android:text="5678"
android:textColor="#android:color/white"
android:textSize="34sp"
android:inputType="textPassword"
app:met_floatingLabel="highlight"
app:met_baseColor="#android:color/white"
app:met_maxCharacters="11"
app:met_primaryColor="#android:color/white"
app:met_singleLineEllipsis="true"
/>
</LinearLayout>
<info.hoang8f.widget.FButton
android:id="#+id/btnLogInScreenLogIn"
android:text="#string/LogIn"
android:textColor="#android:color/white"
android:layout_marginRight="8dp"
android:layout_marginLeft="8dp"
android:layout_alignParentBottom="true"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:buttonColor="#color/btnLogIn"
app:shadowColor="#android:color/black"
app:shadowEnabled="true"
app:shadowHeight="5dp"
app:cornerRadius="4dp"
/>
Later edit: LogCat image:
It seems your code should work just fine if there is no other warning/error showing up. The missing instance error/message might only be because it takes some time to read the data from Firebase.
After adding the ValueEventListener, the app will take some time to "listen" to or read the data from Firebase. So, add some log messages to each of the if/else block as below, recompile and fire up the app, open the Logcat view in Android Studio and then click the button btnLogIn on the app screen. Then wait (make sure internet is available to the device/emulator and Firebase Database is connected).
In Logcat window, you should see the Log messages show up depending on the if/else block that was entered in onDataChange. E.g..... D/ANY_TAG: entered onDataChange
Code with debug lines:
tableUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("ANY_TAG", "entered onDataChange");
if(dataSnapshot.child(editPhone.getText().toString()).exists()){
Log.d("ANY_TAG", "entered onDataChange/childExists");
progressDialog.dismiss();
User user = dataSnapshot.child(editPhone.getText().toString()).getValue(User.class);
if(user.getPassword().equals(editPassword.getText().toString())){
Log.d("ANY_TAG", "entered onDataChange/childExists/equalPassword");
Toast.makeText(getApplicationContext(), "You are logged in!", Toast.LENGTH_SHORT).show();
}
else{
Log.d("ANY_TAG", "entered onDataChange/childExists/unEqualPasswords");
Toast.makeText(getApplicationContext(), "Log in failed!", Toast.LENGTH_SHORT).show();
}
}
else {
Log.d("ANY_TAG", "entered onDataChange/childDoesNotExist");
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "User does not exists!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Related
I'm working on a mobile application for an online learning center and it requires the user to register using their email address. I don't know how to verify that the email address entered by the user actually exists.
--- This is my XML code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="HardcodedText">
<!--EditText which takes input
as Email from the user-->
<EditText
android:id="#+id/emailField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="64dp"
android:layout_marginEnd="16dp"
android:drawableStart="#drawable/ic_email_black_24dp"
android:drawablePadding="12dp"
android:hint="Email" />
<!--Button which when clicked validates
the entered email is valid or not-->
<Button
android:id="#+id/validateButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/emailField"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:backgroundTint="#color/colorPrimary"
android:text="VALIDATE"
android:textColor="#android:color/white" />
</RelativeLayout>
--- And this is my Java code
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
// EditText filed for Email
EditText etMail;
// Button to validate the Email address
Button bValidate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// register all the UI elements
// with their appropriate IDs
etMail = findViewById(R.id.emailField);
bValidate = findViewById(R.id.validateButton);
// handle the VALIDATE button to show the toast
// message whether the entered email is valid or not
bValidate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
emailValidator(etMail);
}
});
}
// the function which triggered when the VALIDATE button is clicked
// which validates the email address entered by the user
public void emailValidator(EditText etMail) {
// extract the entered data from the EditText
String emailToText = etMail.getText().toString();
// Android offers the inbuilt patterns which the entered
// data from the EditText field needs to be compared with
// In this case the entered data needs to compared with
// the EMAIL_ADDRESS, which is implemented same below
if (!emailToText.isEmpty() && Patterns.EMAIL_ADDRESS.matcher(emailToText).matches()) {
Toast.makeText(this, "Email Verified !", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Enter valid Email address !", Toast.LENGTH_SHORT).show();
}
}
}
--- But it only checks that the email is valid. I don't know if it's on the server or not.
Can this be done in Java code? If yes, please show me an example.
I was creating an app then a question come out:
how can i keep user in activity?
I've put two editTexts with input of int.
i want user be kept in activity until he/she puts valid numbers in edittexts.
any ideas?
The solution is very simple all you need to do is get the string values from the edit text box and have a condition in your setonclicklistener that checks the strings if they match to a certain value, if yes the intent from current activity will take you to next if not it will show an error on the edit text box (by using .setError()) and return.
Here is the Java Class Code:
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity);
EditText editText1,editText2;
Button button;
editText1=findViewById(R.id.ed1);
editText2=findViewById(R.id.ed2);
button=findViewById(R.id.check_input);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!editText1.getText().toString().equals("Don"))
{
Toast.makeText(ActivityA.this, "You Can't Leave this Activity, Input Correct Fields", Toast.LENGTH_SHORT).show();
editText1.setError("Input Correct values");
return;
}
if(!editText1.getText().toString().equals("Tom"))
{
Toast.makeText(ActivityA.this, "You Can't Leave this Activity, Input Correct Fields", Toast.LENGTH_SHORT).show();
editText2.setError("Input Correct values");
return;
}
Intent intent=new Intent(ActivityA.this,MainActivity.class);
startActivity(intent);
}
});
}
}
XML Code:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ActivityA">
<EditText
android:layout_margin="10dp"
android:id="#+id/ed1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Input Data Here"
android:textColor="#000000"
android:textSize="20sp" />
<EditText
android:layout_margin="10dp"
android:layout_below="#id/ed1"
android:id="#+id/ed2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Input Data Here"
android:textColor="#000000"
android:textSize="20sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ed2"
android:id="#+id/check_input"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:text="Go to Next Activity"
/>
</RelativeLayout>
Output:
I've created a spinner that takes some user-generated strings (in my case classes - the school type) and displays them in a typical spinner way. My problem occurs when trying to select an item from the spinner. I can tap on the spinner and select the class, but the spinner never shows that I have the class selected. Before adding user-generated strings, I had a string-array xml file that worked perfectly.
I've tried adding notifyDataSetChanged() at the end of the onCreate() method, created a spinner layout with a transparent background and black text, and setting an setOnItemSelectedListener(). None of these worked, so I reverted code back to original state.
Screenshot of problem:
addAssignment.java
package com.nbdeg.unityplanner;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.nbdeg.unityplanner.data.Assignments;
import com.nbdeg.unityplanner.data.Classes;
import java.util.ArrayList;
public class addAssignment extends AppCompatActivity {
EditText mAssignmentName;
EditText mDueDate;
EditText mExtraInfo;
Spinner mDueClass;
SeekBar mPercentComplete;
int percentComplete = 0;
FirebaseAnalytics mFirebaseAnalytics;
DatabaseReference assignmentDb;
DatabaseReference classDb;
FirebaseUser user;
long assignmentCounter;
ArrayList<String> classList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_assignment);
// Sets title to "Create an assignment"
try {getSupportActionBar().setTitle("Create An Assignment");}
catch (NullPointerException e) {
e.printStackTrace();
}
// Getting number of assignments (serves as assignment ID in database)
Bundle extras = getIntent().getExtras();
assignmentCounter = extras.getLong("counter");
// Finds firebase database
user = FirebaseAuth.getInstance().getCurrentUser();
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
assignmentDb = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child("assignments");
classDb = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child("classes");
// Gets all classes
classDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
Classes mClass = userSnapshot.getValue(Classes.class);
Log.i("Info", "Class loaded: " + mClass.getClassName());
classList.add(mClass.getClassName());
}
Log.i("Info", "Classes loaded: " + classList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("DB", "Error: " + databaseError.getMessage());
}
});
// Find view by ID calls
mAssignmentName = (EditText) findViewById(R.id.assignment_name);
mDueDate = (EditText) findViewById(R.id.due_date_edittext);
mExtraInfo = (EditText) findViewById(R.id.extra_homework_info);
mDueClass = (Spinner) findViewById(R.id.class_spinner);
mPercentComplete = (SeekBar) findViewById(R.id.percentComplete);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, classList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDueClass.setAdapter(adapter);
// Sets DueDate EditText to open a datepicker when clicked
new EditTextDatePicker(this, R.id.due_date_edittext);
mPercentComplete.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
percentComplete = progress;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
// Adds a SAVE button to the Action Bar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save, menu);
return true;
}
// Gets and saves information when SAVE is clicked
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Getting information from views
String dueDate = mDueDate.getText().toString();
String assignmentName = mAssignmentName.getText().toString();
String extraInfo = mExtraInfo.getText().toString();
String dueClass = mDueClass.getItemAtPosition(mDueClass.getSelectedItemPosition()).toString();
mFirebaseAnalytics.logEvent("Assignment Created", null);
Log.i("DB", "Creating assignment named " + assignmentName);
assignmentDb.child(Long.toString(assignmentCounter)).setValue
(new Assignments(assignmentName, dueClass, dueDate, extraInfo, percentComplete));
/*
// Test to make sure info is being collected correctly.
Log.i("Class", dueClass);
Log.i("Due", dueDate);
Log.i("Name", homeworkName);
Log.i("Extra", extraInfo);
*/
// Bring user back to MainActivity
startActivity(new Intent(addAssignment.this, MainActivity.class));
return super.onOptionsItemSelected(item);
}
}
activity_add_assignment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_add_homework"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.nbdeg.unityplanner.addAssignment">
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:inputType="textCapSentences"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/assignment_name"
android:hint="Assignment Name"
android:padding="5dp"
android:textSize="18sp"
android:background="#null" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/assignment_name"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="43dp"
android:orientation="horizontal"
android:layout_below="#id/assignment_name"
android:layout_alignParentStart="true"
android:id="#+id/linearLayout">
<Spinner
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="#+id/class_spinner"
android:theme="#android:style/Theme.Holo.Light.DarkActionBar"
android:layout_weight="1"
android:background="#null"/>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#c0c0c0"/>
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/due_date_edittext"
android:padding="5dp"
android:focusable="false"
android:hint="Due Date"
android:textSize="16sp"
android:background="#null" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/linearLayout"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_below="#+id/linearLayout"
android:layout_alignParentStart="true"
android:id="#+id/percentCompleteLayout"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Completion"
android:padding="5dp"
android:textColor="#color/black"
android:textSize="15sp"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/percentComplete"
android:layout_marginBottom="1dp"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/percentCompleteLayout"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/extra_homework_info"
android:hint="Extra Infomation"
android:textSize="16sp"
android:layout_below="#id/percentCompleteLayout"
android:layout_alignParentStart="true"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#null" />
</RelativeLayout>
spinner_layout.xml*
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:gravity="left"
android:padding="5dip"
android:textColor="#android:color/black"
android:background="#android:color/transparent"
/>
I'm wondering if there is a way to fix this and have the spinner display the default / user choice. If you need any more of the code, all of it can be found in the GitHub. Thanks in advance for all answers!
Solution: Try loading the classes prior to starting the activity, for example in the MainActivity. Then pass the values along through an intent.
Example:
MainActivty.java
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launch Add Homework Activity
Intent intent = new Intent(MainActivity.this, addAssignment.class);
intent.putExtra("classListNames", classListNames);
startActivity(intent);
...
classDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
classList.clear();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
Classes mClass = userSnapshot.getValue(Classes.class);
Log.i(TAG, "Class loaded: " + mClass.getClassName());
classList.add(mClass);
classListNames.add(mClass.getClassName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "Error: " + databaseError.getMessage());
}
});
addAssignment.java
// Gets class list
Bundle extras = getIntent().getExtras();
classListNames = extras.getStringArrayList("classListNames");
...
mDueClass = (Spinner) findViewById(R.id.class_spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, classListNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDueClass.setAdapter(adapter);
Cause: After some debugging, I discovered the cause of the problem to be timing differences. The app would request the classes be sent, create the spinner, then load the classes. The difference in timing was milliseconds, but just enough to cause the problem.
I have two rather basic questions I believe which needs answering:
1) When I run my emulator on the home screen my SignIn button is unresponsive and I am unsure why as I have tried alternative methods but whenever I click nothing happens and no error is showing. Code is shown below:
package com.techblogon.loginexample;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class HomeActivity extends Activity
{
Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create a instance of SQLite Database
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get The Reference Of Buttons
btnSignIn=(Button)findViewById(R.id.buttonSignIN);
btnSignUp=(Button)findViewById(R.id.buttonSignUP);
// Set OnClick Listener on SignUp button
btnSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity and Start The Activity
Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
startActivity(intentSignUP);
}
});
}
// Method to handleClick Event of Sign In Button
public void signIn(View V)
{
final Dialog dialog = new Dialog(HomeActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIN);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(HomeActivity.this, "Welcome", Toast.LENGTH_LONG).show();
dialog.dismiss();
Intent ii=new Intent(HomeActivity.this,MainMenu.class);
startActivity(ii);
}
else
{
Toast.makeText(HomeActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
Could somebody provide me with the best sqlite database viewer for eclipse, I am looking to view the records of the database I have created on my emulator
My XML is as follows
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/picture" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello, Welcome"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/buttonSignIN"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:text="Sign In" />
<Button
android:id="#+id/buttonSignUP"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:text="Sign Up" />
</LinearLayout>
you are missing an attribute in xml for buttonSignIN button
android:onClick="signIn"
Try this,
<Button
android:id="#+id/buttonSignIN"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:onClick="signIn"
android:text="Sign In" />
You need to understand the difference between setting clickListener in java code and setting a attribute from xml for the button click. These are two different ways in which you could achieve click events for any element.
I have an android app in which there are many scenarios where request and response happens to-from server. For example:login i.e. authentication. When user enters username and password, then the credentials are verified against the one responded by Server.
But sometimes what happens is that due to slow network the response comes late and android pop-up a force close dialog box, which is highly embarrassing.
I was thinking that is there a way to segregate the code which hits the server in some separate thread and till it gets me a response. I may show a progress bar instead of force close. Is it a good solution?
Example code:
//this code will be called when user presses Login button on UI
public void authenticate(View view) {
//the logic for authentication
if(authentication==true){
//go to home page
}
}
In the above code how can I separate the logic for authentication so that force close does not occur when response is late as expected.
I would also appreciate any other better approach to tackle such scenarios of force close.
Do not include any task which takes time to execute in your main thread. You should do httpCommunication in different thread. and it will avoid this ANR.
What docs says >>
In Android, application responsiveness is monitored by the Activity Manager and Window Manager system services. Android will display the ANR dialog for a particular application when it detects one of the following conditions:
No response to an input event (e.g. key press, screen touch) within 5 seconds
A BroadcastReceiver hasn't finished executing within 10 seconds
Read this document specially created for Designing for responsiveness and to avoid ANR
You can use AsyncTask as well.
You can either use AsyncTask or http://loopj.com/android-async-http/
Show a progress dialog on UI meanwhile. Provide a callback function which will be called once response from server is received.
Use below sample code to do a login process. You can use AsyncTask to do the login process.
The LoginActivity class, which uses AsyncTask.
On Login button click, I am executing the AsyncTask.
During the login process, this will display a ProgressDialog
After the process completion, dismisses the ProgressDialogand displays a status message to user
The class code:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private Button login_Button = null;
private EditText userNameText = null;
private EditText passwordText = null;
private String uName = "";
private String pass = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_login);
login_Button = (Button) findViewById(R.id.cmdDoLogin);
userNameText = (EditText) findViewById(R.id.editTextUserName);
passwordText = (EditText) findViewById(R.id.editTextPassword);
login_Button.setOnClickListener(new OnClickListener() {
public void onClick(View paramView) {
uName = userNameText.getText().toString().trim();
pass = passwordText.getText().toString().trim();
if (uName.equals("") || pass.equals("")) {
Toast.makeText(LoginActivity.this,
"Fill both username and password fields",
Toast.LENGTH_SHORT).show();
} else {
new LoginActivity.DoLoginProcess().execute(); // calling the AsyncTask here
}
}
});
}
private class DoLoginProcess extends AsyncTask<Void, Void, Integer> {
ProgressDialog pd = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(LoginActivity.this);
pd.setTitle("Logging In...");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
int loginStatus = 0 ; // treat this as loginStatus. 0 = login failed; 1=login success. You can return this value to onPostExecute function
//*********************************************
// do login process over internet here. Hope you already have the code to do the login process over internet.
//*********************************************
return loginStatus;
}
#Override
protected void onPostExecute(Integer status) {
super.onPostExecute(status);
pd.dismiss(); // dismiss the progress dialog
if (status == 0) { // login failed
AlertDialog alertDialog = new AlertDialog.Builder(
LoginActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Login failed");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
LoginActivity.this.finish();
dialog.cancel();
}
});
alertDialog.setIcon(android.R.drawable.ic_dialog_info);
alertDialog.show();
} else if(status == 1) { // login success
AlertDialog alertDialog = new AlertDialog.Builder(
LoginActivity.this).create();
alertDialog.setTitle("Success");
alertDialog.setMessage("Login success");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
LoginActivity.this.finish();
dialog.cancel();
}
});
alertDialog.setIcon(android.R.drawable.ic_dialog_info);
alertDialog.show();
}
}
}
}
The test_login layout XMl file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/loginbglayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp" >
<TableLayout
android:id="#+id/holderLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
<TableRow
android:id="#+id/row1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<TextView
android:id="#+id/textViewUserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:gravity="right"
android:text="UserName"
android:textColor="#ffffff" />
<EditText
android:id="#+id/editTextUserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" >
</EditText>
</TableRow>
<TableRow
android:id="#+id/row2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:gravity="right"
android:text="Password"
android:textColor="#ffffff" />
<EditText
android:id="#+id/editTextPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="textPassword" />
</TableRow>
<TableRow
android:id="#+id/row3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center" >
<View
android:layout_width="0dp"
android:layout_height="2dip"
android:layout_weight="1"
android:focusable="false" />
<Button
android:id="#+id/cmdDoLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Login" >
</Button>
</TableRow>
</TableLayout>
</RelativeLayout>