Create New Document For Every New User - java

Right now, I'm on an activity where a user has to input their first name, last name, and id into an EditText. The value they put in there is saved onto the Firestore Console. Here is my problem:
I open my app and sign in with google with my google account, let's call this account my primary account. I fill in the 3 EditTexts, and press on the save button that I named as "btnNextStep" (because it's meant to bring you to the next part of the form, but for now it is the "save" button). Once I press save, I can see the data I filled in, on Google Firestore. Now if I were to sign in to another Google account on the same device, call it my secondary account, and I fill in the EditTexts. Once I press save, instead of creating a new document in Firestore, it overwrites the primary account's data. The final product on Firestore is that it has the data from the secondary account saved, but the data from the primary account is now gone.
Here is the code to my .java file for this activity:
package com.example.attenda_attempt3;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.FirebaseFirestore;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class StudentInformationFormActivity extends AppCompatActivity {
Button btnNextStep;
EditText etFirstName;
EditText etLastName;
EditText etSchoolID;
FirebaseFirestore db = FirebaseFirestore.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_information_form);
btnNextStep = findViewById(R.id.btnNextStep);
etFirstName = findViewById(R.id.etFirstName);
etLastName = findViewById(R.id.etLastName);
etSchoolID = findViewById(R.id.etSchoolID);
btnNextStep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String firstName = etFirstName.getText().toString();
String lastName = etLastName.getText().toString();
String schoolID = etSchoolID.getText().toString();
Map<String, Object> data = new HashMap<>();
data.put("First Name", firstName);
data.put("Last Name", lastName);
data.put("School ID", schoolID);
db.collection("Users").document("User Information").set(data)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Toast.makeText(getApplicationContext(), "Error Occurred, Data Not Saved", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
Can someone help me make it so everytime a user presses the "btnNextStep", it creates a new document and saves the data.

You'll need to generate a unique ID for each user and enter that into this line:
db.collection("Users").document("uniqueUserId").set(data)
If you'd be using Firebase Authentication, it'd automatically generate such a unique user ID for each user. But since you're not using any existing user management API (which is fine), you'll need to generate the ID yourself, associate it with the user in the database as shown above, and possibly also store it in local storage (like SharedPreferences) to be able to restore it when the app restarts.

Related

Do not show Onboarding activity again on button click [duplicate]

This question already has answers here:
How to run an activity only once like Splash screen
(5 answers)
Closed 1 year ago.
I have a Android App built in Android studio, on this app, I am using a Walkthrough Activity.
How can set this activity in a way that when a button is clicked, this page won't show again.
This is the function "public void onFinishButtonPressed()" and this is the part where I added onlick listener to the button, how should it be done in a way that once this function is called, this activity will not open again.
I have tried to implement a code to show activity only on first time run, but it is still not the desired result, i really want this page to keep showing until using clicks on that button.
Thanks for your help in advance.
My code;
package com.frigate.vpn.view;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.frigate.vpn.R;
import com.shashank.sony.fancywalkthroughlib.FancyWalkthroughActivity;
import com.shashank.sony.fancywalkthroughlib.FancyWalkthroughCard;
import java.util.ArrayList;
import java.util.List;
public class Walkthrough extends FancyWalkthroughActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FancyWalkthroughCard fancywalkthroughCard1 = new FancyWalkthroughCard("Welcome to Frigate Media VPN", "Let me show you why so many people love Frigate Media VPN", R.drawable.find_restaurant1);
FancyWalkthroughCard fancywalkthroughCard2 = new FancyWalkthroughCard("We Protect your Privacy", "Internet access is mind free, we'll keep you safe",R.drawable.pickthebest);
FancyWalkthroughCard fancywalkthroughCard3 = new FancyWalkthroughCard("Fast & Limitless!", "We provide you the fastest servers without limits.",R.drawable.chooseurmeal);
FancyWalkthroughCard fancywalkthroughCard4 = new FancyWalkthroughCard("Frigate Media VPN is 100% Free", "You do not have to worry about paying for expensive VPN, we give you everything for free.",R.drawable.mealisonway);
fancywalkthroughCard1.setBackgroundColor(R.color.white);
fancywalkthroughCard1.setIconLayoutParams(300,300,0,0,0,0);
fancywalkthroughCard2.setBackgroundColor(R.color.white);
fancywalkthroughCard2.setIconLayoutParams(300,300,0,0,0,0);
fancywalkthroughCard3.setBackgroundColor(R.color.white);
fancywalkthroughCard3.setIconLayoutParams(300,300,0,0,0,0);
fancywalkthroughCard4.setBackgroundColor(R.color.white);
fancywalkthroughCard4.setIconLayoutParams(300,300,0,0,0,0);
List<FancyWalkthroughCard> pages = new ArrayList<>();
pages.add(fancywalkthroughCard1);
pages.add(fancywalkthroughCard2);
pages.add(fancywalkthroughCard3);
pages.add(fancywalkthroughCard4);
for (FancyWalkthroughCard page : pages) {
page.setTitleColor(R.color.black);
page.setDescriptionColor(R.color.black);
}
setFinishButtonTitle("Get Started");
showNavigationControls(true);
setColorBackground(R.color.white);
//setImageBackground(R.drawable.restaurant);
setInactiveIndicatorColor(R.color.grey_600);
setActiveIndicatorColor(R.color.colorGreen);
setOnboardPages(pages);
}
#Override
public void onFinishButtonPressed() {
Intent intent = new Intent(Walkthrough.this, MainActivity.class);
startActivity(intent);
finish();
}
}
Why not just use a global boolean variable named "isFinishedButtonPressed" set to false by default and when the button is pressed set it to true, and with the correct conditions it should do what you want, no ?

Login activity goes to next activity even if the condition is not true [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
This is my code in which I am trying to move to Next activity which is Dashboard after user is authenticated it works well but it moves to next activity even if credentials are incorrect or wrong...
I have written if else condition for moving to next activity and not moving to next activity....
But still it moves to next activity I don't know why is this happening...
MainActivity.java
package com.example.demo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
EditText etusername, etpassword;
String username, password;
FloatingActionButton loginbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etusername = findViewById(R.id.etemail);
etpassword = findViewById(R.id.etpw);
loginbtn=findViewById(R.id.floatingloginButton);
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Output 1","Button clicked");
loginverify();
}
});
}
private void loginverify() {
username = etusername.getText().toString().trim();
password = etpassword.getText().toString().trim();
Log.d("Output 2","login verify Function called");
if (username.isEmpty()) {
Toast.makeText(MainActivity.this, "Username cannnot be empty", Toast.LENGTH_SHORT).show();
Log.d("Output 3","if con 1");
return;
} else if (password.isEmpty()) {
Toast.makeText(MainActivity.this, "Password cannnot be empty", Toast.LENGTH_SHORT).show();
Log.d("Output 3","if con 2");
return;
}else{
Log.d("Output 5","inside else");
StringRequest request= new StringRequest(Request.Method.POST, "https://**url**/login.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d("Output 4",response);
if(!response.equalsIgnoreCase("Login Failed.......Try Again..")){
Log.d("Output 6","login failed");
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Dashboard.class));
}else{
Log.d("Output 6","login passed");
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
return;
}
// Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
// startActivity(new Intent(getApplicationContext(),Dashboard.class));
//Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("Response error",error.getMessage().toString());
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<String, String>();
params.put("login_name",username);
params.put("login_pass",password);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(MainActivity.this);
requestQueue.add(request);
}
}
}
Below is my php code... Sorry for such a weak code...
<?php
require "../dbcn.php";
$user_name = $_POST["login_name"];
$user_pass = $_POST["login_pass"];
$sql_query = "select Firstname,Lastname from users where emailid like '$user_name' and password like '$user_pass';";
$result = mysqli_query($db_conx,$sql_query);
if(mysqli_num_rows($result) >0 )
{
$row = mysqli_fetch_assoc($result);
$name =$row["Firstname"]." ".$row["Lastname"];
echo "Login Success..Welcome ".$name;
}
else
{
echo "Login Failed.......Try Again..";
}
?>
comparing String results is very, VERY wrong approach... besides that this if is also very improper
if(!response.equalsIgnoreCase("Login Failed.......Try Again..")){
}
so anything other that above String will open next Activity, e.g. when you change even a single character on server-side, or connection broke in the middle and you will get only half of String... (theoretically)
for letting user to some hidden/restricted area you should ALWAYS use positive, clearly stated condition, not opposite of deny... try with if(response.startsWith("Login Success")), but still comparing Strings isn't good idea... (thats why you got downvotes)
consider using some standard for formatting text, like XML or JSON, or just return some int codes, e.g. 0 for positive log in, -1 password mismatch, -2 user not found, etc. depends on your purposes. and of course as logged in condition use if(result==0), not ! of all other possible codes...
I recommended you use JSON format inside onResponse method and use equals() instead of equalsIgnoreCase.OnResponse method takes some time depending upon your response data and internet speed. If you are use boolean value in response this is the best of condition.

How to extract API and DB calls from Android Activity?

I'm very new on Android world. After developing a beautiful Rest API I thought Android development will be easy, but I'm stuck on basics.
On my Android app, I created Login, that makes an API call, that return a token when valid credentials are provided; this token is stored on shared preferences, and user is redirected to the principal activity: HomeActivity.
This Activity has a lot of work to do:
It has a BottomNavigationBar, so when the user clicks on a button of it, a new Fragment will be loaded.
Call to the API endpoint to get resources and show it depending on the fragment.
Store API response on Database to avoid overload server.
Surely, for Android developer this will be quite easy, but for my is like this:
import android.arch.persistence.room.Room;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.ibosca.thub.database.AppDatabase;
import com.ibosca.thub.helpers.BottomNavigationViewHelper;
import com.ibosca.thub.models.Channel;
import com.ibosca.thub.models.Content;
import com.ibosca.thub.models.ContentList;
import com.ibosca.thub.models.Town;
import com.ibosca.thub.models.User;
import com.ibosca.thub.parser.ContentParser;
import com.ibosca.thub.volley.MySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HomeActivity extends AppCompatActivity {
private String userToken;
public TextView contentList;
private ContentParser contentParser = new ContentParser();
public static AppDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "townhub").build();
contentList = (TextView) findViewById(R.id.contentList);
loadContents();
SharedPreferences sharedPref = getSharedPreferences(MainActivity.PACKAGE_NAME, Context.MODE_PRIVATE);
userToken = sharedPref.getString("token", null);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
View contentsButton = bottomNavigationView.findViewById(R.id.action_contents);
contentsButton.performClick();
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Toast toast = Toast.makeText(getApplicationContext(), "UNDF", Toast.LENGTH_LONG);
switch (item.getItemId()) {
case R.id.action_towns:
toast = Toast.makeText(getApplicationContext(), "Towns", Toast.LENGTH_LONG);
break;
case R.id.action_channels:
toast = Toast.makeText(getApplicationContext(), "Channels", Toast.LENGTH_LONG);
break;
case R.id.action_contents:
loadContents();
break;
case R.id.action_question:
toast = Toast.makeText(getApplicationContext(), "Questions", Toast.LENGTH_LONG);
break;
case R.id.action_user:
toast = Toast.makeText(getApplicationContext(), "Settings", Toast.LENGTH_LONG);
break;
}
toast.show();
return true;
}
});
}
public void ExecuteInsert(ContentList...lists){
new InsertContents().execute(lists);
}
protected void loadContents() {
String url = MySingleton.BASE_URL + "/contents";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
ContentList list = contentParser.fromContents(response);
ContentList[] lists = new ContentList[1];
lists[0] = list;
ExecuteInsert(lists);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Failed to connect", Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + userToken);
return headers;
}
};
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
}
public static class InsertContents extends AsyncTask<ContentList, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Perform pre-adding operation here.
}
#Override
protected Void doInBackground(ContentList...lists) {
ContentList list = lists[0];
//Insert towns, channels
db.townDao().insertArrayList(list.getTowns());
db.channelDao().insertArrayList(list.getChannels());
db.userDao().insertArrayList(list.getUsers());
db.contentDao().insertArrayList(list.getContents());
//Select data from DB
List<Town> towns = db.townDao().getAll();
List<Channel> channels = db.channelDao().getAll();
List<User> users = db.userDao().getAll();
List<Content> contents = db.contentDao().getAll();
for (int i = 0; i < contents.size(); i++) {
Content content = contents.get(i);
Town contentTown = db.townDao().findById(content.getTownId());
Log.i("Poble: ", contentTown.getName());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//To after addition operation here.
}
}
}
For a quick summary, on method loadContents() I'm making the API call; and the class InsertContents it's where I play with local database.
Finally, the questions:
1) As you can see, I'm using Volley to make API calls. Are there any best practice to put any "api endpoint" on a separated class, and use this class from the Activity? How to separate this code on Android development?
2) Same for Database management. How can I put the code on a separated class and call it from the Activity? This is currently accomplished, but... I'm unable to update my TextView from the AsyncTask (Update the TextView it's only a easy try, my final goal it's to use a ListView or ReciclerView.
Any suggestions for improvement are welcome.
You might try the Repository pattern.
The idea is more or less as follows, lets say you have a Car domain class and you database or api interactions perform tipical CRUD operation like, insert a car, retrieve a list of al card or one by its plate number.
You could create an interface like
public interface CarRepository {
void insertCar(#NonNull Car car);
List<Car> getAllCars();
Car getCarByPlate(#NonNull String plateNumber);
}
Then you can create concrete implementations of said interface depending of which source are you using for storing your data.
For example if using volley you could create a RestCarRepository that extends CarRepository and fetch/ store data from a rest api using Volley. Or a DBCarRepository that uses SQLite (or any other database engine).
Finally you can declare your repository in you activity so you abstract the logic of fetching data.
Disclaimer: There are lots of articles regarding repository pattern (as the posted at the beggining of the answer) and this answer could become more complex when adding more patterns as DI or MVP, this is so you have a grasp of the idea.
Short answer for both cases: It would be better separate the view (activity/fragment) from the model or data. You are mixing everything in the activity and in this small case could be ok but if your app grows will be dificult to read and understand and cause problems with the activity/fragment lifecycle.
There are a lot of different aproaches to separate concerns in android in order to do a cleaner code.
I recommend you this repo talking about clean architecture in android apps https://github.com/android10/Android-CleanArchitecture
Also Google has a relatively new library to implements several patterns
https://developer.android.com/topic/libraries/architecture/adding-components.html
Here you have some help about databases, paging, viewmodel, etc.
EDIT:
Answering more in detail:
1) You can follow the Model View Presenter (MVP) pattern considering the activity/fragment like only a View (a component with an only one responsibility, render components) and creating a class (the Presenter) who has the knowledge of the model/data (your api calls) and act like a bridge between View and Model.
The view will delegate in Presenter the calls to the model (for example if some button is pressed) and the Presenter will return the data to the View and the View will have only the way of paint the screen.
2) You can follow the same approach calling the Presenter in order to retrieve the information and painting the data in a RecyclerView.
You can use a ThreadPoolExecutor in order to decouple the data from the activity.

sending email and SQlite database operation one intent new thread

One of the functions in my app is sending email. The email list is generated by querying from SQLite database table. So sending email and query data from SQLite database at the same activity. It is not working. Sending email code works if I apply the code in a simple app. Query works. It is not working when I put them all together. After reading online, my feeling is that I need to create a new thread that handle the SQLite database query. I am very new for android and java and don't know how to create a new thread (background).
Could somebody help me? Many many thanks!!!!!
my activity code as following:
package jhapps.com.demographics;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class PromotionEmailMonthTop10 extends Activity {
private EditText subjectGroupTop10,bodyGroupTop10;
private Button btnMonthTop10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promotion_email_month_top10);
subjectGroupTop10=(EditText)findViewById(R.id.subjectMonthTop10);
bodyGroupTop10=(EditText)findViewById(R.id.bodyMonthTop10);
btnMonthTop10=(Button)findViewById(R.id.btnMonthTop10);
btnMonthTop10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EmailMonthTop10();
// after sending the email, clear the fields
subjectGroupTop10.setText("");
bodyGroupTop10.setText("");
}
});
}
//get month top 10 email list
protected void EmailMonthTop10() {
DataBaseHelper dataBaseHelper=new DataBaseHelper(PromotionEmailMonthTop10.this);
String[] emailGroupTop10=new String[dataBaseHelper.eMailListMonthTop10().size()];
for(int i=0;i<dataBaseHelper.eMailListMonthTop10().size();i++){
emailGroupTop10[i]=dataBaseHelper.eMailListMonthTop10().get(i);
}
String subjects=subjectGroupTop10.getText().toString();
String bodytext=bodyGroupTop10.getText().toString();
//start email intent
Intent email = new Intent(Intent.ACTION_SENDTO);
// prompts email clients only
email.setType("message/rfc822");
email.setData(Uri.parse("mailto:"));
email.putExtra(Intent.EXTRA_EMAIL,emailGroupTop10 );
// email.putExtra(Intent.EXTRA_EMAIL,new String []{"junrudeng#gmail.com","huangji8#gmail.com"});
email.putExtra(Intent.EXTRA_SUBJECT, subjects);
email.putExtra(Intent.EXTRA_TEXT, bodytext);
try {
// the user can choose the email client
startActivity(Intent.createChooser(email, "Choose an email client from..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(PromotionEmailMonthTop10.this, "No email client installed.",
Toast.LENGTH_LONG).show();
}
}
}
You should never execute database queries or network calls on the main thread. If you want to query a database to display data you probably want to you a AsyncTask for that.
Something like the following should work:
public class PromotionEmailMonthTop10 extends Activity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
btnMonthTop10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new SendEmailTop10Task().execute();
}
});
}
class SendEmailTop10Task extends AsyncTask<Void, Void, Void> {
// This is called on a seperate thread
#Override
protected Void doInBackground(Void... voids) {
EmailMonthTop10();
}
// This is called on the main thread
#Override
protected void onPostExecute(Integer status) {
subjectGroupTop10.setText("");
bodyGroupTop10.setText("");
}
}
}
Please consider renaming your method taking the java naming conventions under consideration

Android store data in a server

I am developing an Android application in which I developed the registration page in which the users details are collected... username, password, mobilenumber etc.. now the details are stored in database in the android application itself... But I need to store this data in a webserver.. when user give all details the data has to be saved in a server... what I have to do for that ... is there any free web server available.. for me to test ... I am giving the code that I developed ..
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 MainActivity extends Activity
{
Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
btnSignIn=(Button)findViewById(R.id.buttonSignIn);
btnSignUp=(Button)findViewById(R.id.buttonSignUP);
if(loginDataBaseAdapter.getUsercount() >= 3)
{
btnSignUp.setVisibility(View.INVISIBLE);
}
else
{
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
startActivity(intentSignUP);
}
});
}
}
public void signIn(View V)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
final EditText editTextMobileNumber = (EditText)dialog.findViewById(R.id.editText1);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String mobileNumber = editTextMobileNumber.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
String sd = getIntent().getStringExtra("number");
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword) && (mobileNumber.equals(sd)))
{
Toast.makeText(MainActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
else
{
Toast.makeText(MainActivity.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();
}
}
I think Wamp server is best option to play with server related utilities.You can use it it even if you are offline. and it provides various option for data storage. It Mainly uses MySql and PHP scripts for fast performance.
For more information Have a look at,
Installing and testing Wamp server
Buddy before the server you will need web service to store data onto the server database which mostly written PHP. Then after there are several free testing servers available just google it
Good luck..

Categories

Resources