sending email and SQlite database operation one intent new thread - java

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

Related

Implement a callback to avoid force close, while reporting crash and showing a support screen

Instead of the force close dialog I would like to show an Activity with support information to the user and at the same time send error information to bugsnag. I followed this advice (https://trivedihardik.wordpress.com/2011/08/20/how-to-avoid-force-close-error-in-android/) to set up a handler for uncaught exceptions. Reporting to bugsnag with bugsnag.notify obviously takes some time, so I thought I need an AsyncTask to show the "Support Activity" and send the notification. The process shall be killed only after this has been completed. AFAIK, the problem with AsyncTask is that is not capable to update the UI thread when put into a helper class. So how can I can make sure the error is reported to busgnag, the Support Activity is shown and the process is killed afterwards?
Code within MainActivity.java
Bugsnag.init(this);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
ExceptionHandler.java
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import com.bugsnag.android.Bugsnag;
public class ExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler {
private final Activity myContext;
public ExceptionHandler(Activity context) {
myContext = context;
}
public void uncaughtException(Thread thread, Throwable exception) {
new ReportCrashTask().execute();
}
private class ReportCrashTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Intent intent = new Intent(myContext, CrashActivity.class);
myContext.startActivity(intent);
Bugsnag.notify(new RuntimeException("Test error"));
return "done";
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
}

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.

Toast is shown even after finish();

I am new to android and I have found similar question here but none of it could solve my problem. The code below is basically to get two double values(latitude and longitude) from Firebase and plot them on the map. There is a toast that is shown when the user has logged out i.e when the double values have been removed from the database. The problem here is that this toast is shown even after I go back to other activities. How can I stop this. I just want to end the Activity where I have put the finishes at.
Any help would be appreciated. Thanks in advance!
Edit: If I open many instances of this activity (View locations of many people) I would get the toast of every instance as each person logs out. I am concerned this would waste a lot of resources.
Could it be because of the getMapAsync? Have read that Async tasks run on a different thread and does not stop even after finish().
java code:
package com.example.android.managers;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class LocateS extends Activity implements OnMapReadyCallback {
MapView mapView;
GoogleMap googleMap;
String username;
int firstTime=0;
LocationDetails loc;
ChildEventListener listen = null;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Staff");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_locate);
Bundle extras = getIntent().getExtras();
username= extras.getString("user");
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
listen = myRef.child(username).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
loc = dataSnapshot.getValue(LocationDetails.class);
if(loc!=null)
setMap();
else
Toast.makeText(getApplicationContext(),"Location not received yet",Toast.LENGTH_LONG).show();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {
loc = dataSnapshot.getValue(LocationDetails.class);
if(loc!=null)
setMap();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Toast.makeText(getApplicationContext(), username+" logged out", Toast.LENGTH_SHORT).show();
myRef.removeEventListener(listen);
// android.os.Process.killProcess(android.os.Process.myPid());
finish();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
public void setMap(){
if(googleMap!=null){
googleMap.clear();
LatLng coordinate = new LatLng(loc.getLatitude(),loc.getLongitude());
googleMap.addMarker(new MarkerOptions().position(coordinate));
if(firstTime == 0) {
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(coordinate, 17.0f);
googleMap.moveCamera(cameraUpdate);
firstTime++;
}
}
}
#Override
public void onMapReady(GoogleMap map) {
googleMap=map;
map.getUiSettings().setZoomControlsEnabled(true);
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop(){
finish();
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
mapView.onLowMemory();
super.onLowMemory();
}
#Override
public void onBackPressed() {
myRef.removeEventListener(listen);
finish();
// android.os.Process.killProcess(android.os.Process.myPid());
super.onBackPressed();
}
}
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:id="#+id/activity_main2"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.managers.Locate">
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</RelativeLayout>
add finish after in your onDestroy() method
finish();
Your issue is the listener was not removed when you moved to another activity except when you back pressed.
You should put the
myRef.removeEventListener(listen);
Into the onPause/onStop method.
As your toast is still alive and any change to the child, it will trigger the toast.
You can use ActivityName.this.finish();
cancel your toast before calling finish
final Toast testing = Toast.makeText(context, "start.", Toast.LENGTH_SHORT);
testing.show();
and use this when you r calling finish.
testing.cancel();
finish();
toast will display until is will not complete execution no matter activity is closed or not. toast will tack 3 second(sort duration) . make sure you r calling after 3 second or cancel toast and call finish any time
The toast is shown for the duration corresponding to Toast.LENGTH_SHORT which is 3.5 sec according to this, no matter the calling activity is active or not. I think what you want is to show the toast that user had logged out. Wait till it is shown on screen. As soon as it is finished showing, destroy activity. This may be achieved by calling show toast, waiting for 3.5 sec and then destroying the activity.
So, as described here,
Toast.makeText(getApplicationContext(), username+" logged out", Toast.LENGTH_SHORT).show();
Thread thread = new Thread(){
#Override
public void run() {
try {
Thread.sleep(3500);
LocateS.this.finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
might work.
Alternatively, if you want to wait for duration other than 3.5 sec or that corresponding to Toast.LENGTH_LONG, follow this.
Edit:
Sorry I misinterpreted your problem!
I think the problem might be that we cannot detach a listener from its own method. I think putting myRef.removeEventListener(listen); in onDestroy() instead might be helpful.

Android UI Hangs on JDBC Connection - Even though Connection is on another Thread

So, I have a login screen. Upon pressing the 'Login' Button a JDBC Connection is made to check the username and password and then move onto the next Activity if the details are correct. As a result of this, the UI hangs for approximately 5 second. I assumed that this was because the connection was created in the same Thread, so I created a new one. I then created a Handler to interact with the UI depending on what happened with this connection.
The trouble is, the UI still hangs. Below is where the new Runnable is declared in the Activity (h is the custom Handler reference belonging to this Activity);
logInButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
progress.setVisibility(ProgressBar.VISIBLE);
new LoginProcessor(h).run(); // HERE!
}});
Below is the run() method from the LoginProcessor Runnable which includes the code that is causing the hang. The MicroManager class contains simple JDBC database interactions and makes the connection (nothing exciting in there really and I am trying to keep this as short as possible);
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
try{
MicroManager manager = new MicroManager(); // THIS LINE, AND THE LINE BELOW, ARE CAUSING THE HANG!!!!
if(manager.getEmployeeId(h.getLoginName(), h.getPassword())!= 0){
h.sendEmptyMessage(0);
}
}catch(Exception ex){
ex.printStackTrace();
h.sendEmptyMessage(1);
}
}
In the above, there is no direct interaction with the UI. Information is simply sent to the Handler so that it can do it on the UI thread. Lastly, here are the methods of my custom Handler called LogInHandler;
#Override
public void handleMessage(Message msg){
if(msg.what == 0){
activity.startActivity(new Intent(activity, AdvisorsPanelActivity.class));
activity.finish();
}else{
AlertDialog alertDialog = new AlertDialog.Builder(activity).create();
alertDialog.setTitle("Not Working");
alertDialog.show();
activity.setProgressVisible(ProgressBar.GONE);
}
}
public String getLoginName(){
return activity.getLoginName();
}
public String getPassword(){
return activity.getPassword();
}
Sorry to dump so much code on your guys, but I didn't think a complete picture was possible without all the above. I've trimmed it down as much as I can. I've only recently started working with Threading AND Android, so please be gentle with me.
Based on my experience: Use AsyncTask for JDBC and you shall torture no more.
EDIT :
This is a neat example of implementing AsyncTask:
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class AsyncTaskActivity extends Activity implements OnClickListener {
Button btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
// because we implement OnClickListener we only have to pass "this"
// (much easier)
btn.setOnClickListener(this);
}
public void onClick(View view) {
// detect the view that was "clicked"
switch (view.getId()) {
case R.id.button1:
new LongOperation().execute("");
break;
}
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed"); // txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
You may want to create and handle your JDBC connection in
doInBackground(String... params) part of your code.
Good Luck.

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