Android store data in a server - java

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..

Related

How would you use shared preference in a dashboard activity?

This is the code for an Activity named as Interest Activity. It is a dashboard which consist of four interest/hobbies (gaming, singing, sports, and coding). The user is asked to choose one of the them and then he/she is redirected to the particular activity. I used Cardview to represent the interest they behave like a button. This is the code:
package com.example.meetup;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class InterestActivity extends AppCompatActivity {
CardView cardGame;
CardView cardSports;
CardView cardSing;
CardView cardCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_interest);
cardGame = findViewById(R.id.cardGame);
cardCode = findViewById(R.id.cardCode);
cardSing = findViewById(R.id.cardSing);
cardSports = findViewById(R.id.cardSports);
cardGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Gaming", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(InterestActivity.this,GameActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
cardSports.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Sports", Toast.LENGTH_SHORT).show();
}
});
cardSing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Singing", Toast.LENGTH_SHORT).show();
}
});
cardCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Coding", Toast.LENGTH_SHORT).show();
}
});
}
}
Now the problem is that whenever I am reopening the app, it takes me to the interest activity again even though I chose an interest once. Then I got to know about shared preference as how it stores the user data and intent accordingly.
I saw many tutorials on YouTube as to how could I use it, but they all were taking something as input like text. But in my case I’m not taking any input just pushing a button. How do I use a shared preference in my case? Can you give a shared preference code for if the user chooses gaming?
Define some constants to manage saved selected interest
public class InterestActivity extends AppCompatActivity {
// Define a string key for SharedPreference value
private static final String SP_INTEREST = "interest"
// Define integer codes for each interest
private static final int INTEREST_NONE = 0
private static final int INTEREST_GAME = 1
private static final int INTEREST_SPORTS = 2
private static final int INTEREST_SING = 3
private static final int INTEREST_CODE = 4
SharedPreferences sp;
SharedPreferences.Editor editor;
CardView cardGame;
CardView cardSports;
CardView cardSing;
CardView cardCode;
// Rest of the code
}
Then for saving the choosen interest, repeat it for each on click:
cardGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Gaming", Toast.LENGTH_SHORT).show();
// Here first save the choosen interest
editor.putInt(SP_INTEREST, INTEREST_GAME);
editor.apply();
Intent intent = new Intent(InterestActivity.this,GameActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
And when you restart the app, in on create method check the saved interest code and start the corresponding activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get and init SharedPreferences and editor
SharedPreferences sp = getSharedPreferences(getPackageName(), MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
// INTEREST_NONE is the default value if there no registry.
int savedInterest = sp.getInt(SP_INTEREST, INTEREST_NONE);
if(INTEREST_GAME == savedInterest) {
// Start game activity using intent
Intent intent = new Intent(InterestActivity.this,GameActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
else if(INTEREST_SPORTS == savedInterest) {
// Start sports activity using intent
}
else if(INTEREST_SING == savedInterest) {
// Start sing activity using intent
}
else if(INTEREST_CODE == savedInterest) {
// Start code activity using intent
}
setContentView(R.layout.activity_interest);
// Rest of the onCreate codes
}
If you want to store what the user clicked the last time and do something about it, you can follow this to write/read from shared preferences: https://stackoverflow.com/a/3624358/7365491
Every time the user clicks on one of your CardViews you store a value of the last selected interest.
Every time the user opens the app in the onCreate, check if the preference exists and read the last stored value in it. With that then you can decide what you want to do when the app is opened and the user has previously selected a value.

Android App stops after savedInstanceState is implemented

EDIT: After adding onPause() and onResume(), the app no longer crashes; however, the instance is still not saving, and I lose the text I put inside the EditText. I speculate that I'm supposed to save the instance using onPause(), onStop(), and recall it using onResume() (or maybe using this and onSaveInstanceState(), onRestoreInstanceState() together) - I'm reading up on how to use these three methods now, and I would appreciate any pointers.
I'm currently writing a simple Android App with only a four (maybe five) activities. The app's function is to provide help and advice to students in university, where they are required to add the courses themselves (which appear on the activity_main_page page as buttons) - when the button is pressed, it will take the student to the advice page.
What I'm currently working on is the course adding page: activity_add_course. I'm trying to add a way to save the state of the EditText's text (this is where the user adds the course name) when the activity is paused/stopped (for example when user presses the back button or home button), and to have it recalled when the user returns to the page.
The app worked fine (using dummy intents to connect activities - I havent added an SQL database to actually make the app work) before I tried adding instance state saving to the App. Now that I have added instance state saving and recalling, the app stops running when I click the back button and I have no idea why? or how to fix it? - This issue has been solved. Thanks #peresisUser
This is the code for the back button
btBk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent New = new Intent(AddCourse.this, MainPage.class);
startActivity(New);
}
});
}
And these are the codes I use for instance save and restore.
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//Save instance state
savedInstanceState.putString("edC1", edCourse1.getText()+"");
savedInstanceState.putString("edC2", edCourse2.getText()+"");
savedInstanceState.putString("edC3", edCourse3.getText()+"");
savedInstanceState.putString("edC4", edCourse4.getText()+"");
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//Restore instance state
String edC1 = savedInstanceState.getString("edC1");
edCourse1.setText(edC1+"");
String edC2 = savedInstanceState.getString("edC2");
edCourse2.setText(edC2+"");
String edC3 = savedInstanceState.getString("edC3");
edCourse3.setText(edC3+"");
String edC4 = savedInstanceState.getString("edC4");
edCourse4.setText(edC4+"");
}
edCourse1-4 are all different EditTexts.
From my understanding, the onSaveInstanceState() will save edC1 as the text from edCourse1.getText()+"" and so on, then the onRestoreInstanceState() will restore the String inside edC1 to edCourse1 and so on.
Having trouble on this, I have no idea how I would solve my next issue, which has to save the state of buttons on the page activity_main_page. Here I would have 10 buttons which start off as invisible and nameless, where activity_add_course will add a name to the button and make it visible. I speculate that the issue I will run into is: that all the buttons would become invisible when the app is restarted.
It looks to me that your should just add the super call in onPause() which is probably deleted in your code.
First row of the stack trace:
android.util.SuperNotCalledException: Activity {com.example.user.icecres/com.example.user.icecres.AddCourse} did not call through to super.onPause()
Let me know if that helped.
So I've figured out how to do all of this, next task: doing the same thing for buttons!
Feel free to add/edit anything appropriate to this answer.
This is my final source code:
package com.example.user.icecres;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.view.View;
public class AddCourse extends AppCompatActivity {
private EditText edCourse1, edCourse2, edCourse3,edCourse4;
private Button btConfirm, btReset, btBk;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_add_course);
if(state != null){
//restore state onStop()
SharedPreferences pText = getSharedPreferences(PREFS_NAME,0);
String edC1 = pText.getString("edC1", "");
String edC2 = pText.getString("edC2", "");
String edC3 = pText.getString("edC3", "");
String edC4 = pText.getString("edC4", "");
edCourse1.setText(edC1);
edCourse2.setText(edC2);
edCourse3.setText(edC3);
edCourse4.setText(edC4);
} else {
btConfirm = (Button) findViewById(R.id.btConfirm);
btReset = (Button) findViewById(R.id.btReset);
edCourse1 = (EditText) findViewById(R.id.edCourse1);
edCourse2 = (EditText) findViewById(R.id.edCourse2);
edCourse3 = (EditText) findViewById(R.id.edCourse3);
edCourse4 = (EditText) findViewById(R.id.edCourse4);
btBk = (Button) findViewById(R.id.btBk);
}
btConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// add course to database
edCourse1.setText("");
edCourse2.setText("");
edCourse3.setText("");
edCourse4.setText("");
AlertDialog.Builder d = new AlertDialog.Builder(
AddCourse.this);
d.setTitle("Success");
d.setMessage("Courses have been added");
d.setPositiveButton("OK", null);
}
});
btReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder c = new AlertDialog.Builder(
AddCourse.this);
c.setTitle("Confirmation");
c.setMessage("Would you like to clear all fields?");
c.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
edCourse1.setText("");
edCourse2.setText("");
edCourse3.setText("");
edCourse4.setText("");
}
});
c.setNegativeButton("NO",null);
c.show();
}
});
btBk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent New = new Intent(AddCourse.this, MainPage.class);
startActivity(New);
}
});
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences pText = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = pText.edit();
edit.putString("edC1",edCourse1.getText()+"");
edit.putString("edC2",edCourse2.getText()+"");
edit.putString("edC3",edCourse3.getText()+"");
edit.putString("edC4",edCourse4.getText()+"");
edit.commit();
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences pText = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = pText.edit();
edit.putString("edC1",edCourse1.getText()+"");
edit.putString("edC2",edCourse2.getText()+"");
edit.putString("edC3",edCourse3.getText()+"");
edit.putString("edC4",edCourse4.getText()+"");
edit.commit();
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences pText = getSharedPreferences(PREFS_NAME,0);
String edC1 = pText.getString("edC1", "");
String edC2 = pText.getString("edC2", "");
String edC3 = pText.getString("edC3", "");
String edC4 = pText.getString("edC4", "");
edCourse1.setText(edC1);
edCourse2.setText(edC2);
edCourse3.setText(edC3);
edCourse4.setText(edC4);
}
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
//Save instance state
state.putString("edC1", edCourse1.getText()+"");
state.putString("edC2", edCourse2.getText()+"");
state.putString("edC3", edCourse3.getText()+"");
state.putString("edC4", edCourse4.getText()+"");
}
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
//Restore instance state on crash
String edC1 = state.getString("edC1","");
String edC2 = state.getString("edC2","");
String edC3 = state.getString("edC3","");
String edC4 = state.getString("edC4","");
edCourse2.setText(edC2+"");
edCourse3.setText(edC3+"");
edCourse1.setText(edC1+"");
edCourse4.setText(edC4+"");
}
}
So the onPause() and onStop() are used to save the text inside the EditText fields to the file initialized at the top. The onResume() is used to call the texts saved and apply them to the relevant EditText fields. The onSaveInstanceState() is used to save the state and onRestoreInstanceState() is used to restore the state on crash. The if else in the onCreate(), is used to determine if there was a previous state to be restored or not (by onStop), and the values are called/initialised depending on this condition.
Hope this helps someone with similar problems!

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 - Saving login details

I am struggling in developing a way to have an option for the user to save their details when they login, I have searched on the internet but I have not found a solution... any help will be appreciated...
here is my code
#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 Refference 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 abd Start The Activity
Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
startActivity(intentSignUP);
}
});
}
// Methos to handleClick Event of Sign In Button
public void signIn(View V)
{
final Dialog dialog = new Dialog(LoginActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the Refferences of views
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))
{
startActivity(new Intent("com.example.system.HOMEACTIVITY"));
}
else
{
Toast.makeText(LoginActivity.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();
}
}
Depending on your need, you could use sharedpreference to save all the user details. And wipe it when the user log out. Or you could use a more complicated solution like the Android accountmanager. Here the link to show how it all works together.
https://udinic.wordpress.com/tag/account-manager/

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.

Categories

Resources