I take input in an edittext, that is in a popup window. On dismiss of that popup, the string in edittext should be updated in db at required postion.
Popup Window code:
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popl,(ViewGroup)findViewById(R.id.pop));
final PopupWindow pw = new PopupWindow(layout, 700 * (metrics.widthPixels/1080) , 300 * (metrics.heightPixels/1080) , true);
int coord[]= new int[2];
v.getLocationOnScreen(coord);
pw.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(getApplicationContext(), android.R.color.transparent)));
pw.setOutsideTouchable(true);
pw.showAtLocation(v, Gravity.NO_GRAVITY, coord[0] + 50 ,coord[1]+100);
Button del = (Button) layout.findViewById(R.id.del);
Button viewImage = (Button) layout.findViewById(R.id.view);
final EditText notes = (EditText) layout.findViewById(R.id.note);
notes.setText(data[6]);
notedata = data[6];
del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SQLiteDatabase db = dBcontract.getWritableDatabase();
if ((thisimageuri!=null)&&(thisimageuri.toString().charAt(0)!='a'))
deleteimage(thisimageuri);
Log.d("delete operaiton",String.valueOf(db.delete(eventDBcontract.ListofItem.tableName,eventDBcontract.ListofItem.columnID+" = "+data[4],null)));
recreate(); //add option to delete files as well
}
});
viewImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (thisimageuri!=null)
{
Intent intent = new Intent(getApplicationContext(),showPic.class);
intent.putExtra("photo uri",thisimageuri);
notedata = notes.getText().toString();
pw.dismiss();
startActivity(intent);
}
}
});
pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
notedata = notes.getText().toString();
Log.d("popop window", "onDismiss: " + notedata);
interact.savenote(data[4],notedata);
}
});
} catch (Exception e) {
e.printStackTrace();
}
Method to save in database:
public void savenote(String id , String note)
{
ContentValues values = new ContentValues();
SQLiteDatabase db = dBcontract.getWritableDatabase();
values.put(eventDBcontract.ListofItem.columnnotes,note);
db.update(eventDBcontract.ListofItem.tableName,values,"id=?",new String[]{id});
Log.d("Interact","add note complete " + note);
}
The code works correctly,i.e note is saved correctly in db, when i click on view image but not when I click outside of popup to dismiss it.
Log:
04-14 00:12:24.569 9517-9517/lcukerd.com.stufflist D/popop window: onDismiss: Yu
04-14 00:12:24.569 9517-9517/lcukerd.com.stufflist D/Interact: add note complete Yu
Help me spot the issue. This is eating my brain.
EDIT 1:
data[4] is the id of entry in db to be updated.
data[6] is the old value of "note" as saved in db.
Related
enter image description herehow can i add multiple TextView and their inside relative layout dynamically which is already created? Also I have to call the values of those text boxes from database sqlite.
public class DownloadPackagesActivity extends Activity implements AdapterView.OnItemSelectedListener{
private SQLiteDatabase db;
DBHelper dbHelper;
String newFolder = "";
int SId = 1;
TextView subjects;
List<String> categories = new ArrayList<String>();
String FilePart = "";
DownloadManager dManager;
long did;
// private static String file_url = "http://mobileteacher.in/audio/demo/2725.mp3";
String urlString ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_packages);
// Get DownloadManager instance
dManager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
subjects = (TextView)findViewById(R.id.subjects);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinnerPackage);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Add textview
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c = db.rawQuery("select * from DownloadSubject", null);
while (c.moveToNext()) {
categories.add(c.getString(1));
}
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, categories);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
spinner.setAdapter(dataAdapter1);
showPart();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
SId = position + 1;
showPart();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void showPart()
{
int j=1;
int ii=0;
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
TableLayout stk = (TableLayout) findViewById(R.id.tbl);
stk.removeAllViews();
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c;
if (SId==8 || SId==9)
{
c = db.rawQuery("select * from DownloadSubject", null);
}
else
{
c = db.rawQuery("select * from DownloadSubject where Id = '"+ SId +"'", null);
}
while (c.moveToNext())
{
subjects.clearComposingText();
String[] part = c.getString(2).split(",");
for(int i = 0;i<part.length;i++)
{
TableRow tr1 = new TableRow(this);
Button button = new Button(this);
button.setBackgroundColor(Color.TRANSPARENT);
button.setText(part[i] +"\u00A0 \u00A0 \u00A0 \u00A0 Download");
button.setTextColor(Color.BLUE);
button.setPadding(20, 0, 0, 0);
button.setOnClickListener(downloads());
button.setId(i);
// button.setHint(part[i]);
tr1.addView(button);
stk.addView(tr1);
}
stk = (TableLayout) findViewById(R.id.tbl);
int N = 1;
TextView[] TextViews = new TextView[N]; // create an empty array;
// for (int i = 0; i < N; i++) {
//if(ii!=0) {
// subjects.setText(c.getString(j));
// Toast.makeText(this, c.getString(j), Toast.LENGTH_LONG).show();
// save a reference to the textview for later
// TextViews[j] = TextView;
//}
if(ii==0)
{
subjects.setText(c.getString(j));
ii=ii+1;
}
else
{
final TextView TextView = new TextView(this);
TextView.setText(c.getString(j));
TextView.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TextView.setPadding(0, 20, 0, 20);
TextView.setTextSize(getResources().getDimension(R.dimen.textsize));
TextView.setTextColor(Color.parseColor("#800080"));
// add the textview to the layout
stk.addView(TextView);
}
}
}
public String part;
View.OnClickListener downloads()
{
return new View.OnClickListener()
{
public void onClick(View v) {
//Button b1 = (Button)v;
//int i = b1.getId();
// Toast.makeText(getApplicationContext(),"Ide = " + i,Toast.LENGTH_LONG).show();
part ="";
TextView subjects = (TextView)findViewById(R.id.subjects);
if(subjects.getText().toString().equals("Modern History (500 MB)"))
{
part = "modern_history";
}
else if(subjects.getText().toString().equals("Polity (250 MB)"))
{
part = "polity";
}
else if(subjects.getText().toString().equals("Economy (100 MB)"))
{
part = "economy";
}
else if(subjects.getText().toString().equals("Ancient History (500 MB)"))
{
part = "ancient_history";
}
else if(subjects.getText().toString().equals("English Grammar (500 MB)"))
{
part = "english_grammar";
}
else if(subjects.getText().toString().equals("Vocabulary (560 MB)"))
{
part = "vocabulary";
}
else if(subjects.getText().toString().equals("Maths (100 MB)"))
{
part = "maths";
}
else if(subjects.getText().toString().equals("One Day Complete(Vol.1(2GB))"))
{
part = "oneday_complete";
}
else if(subjects.getText().toString().equals("Civil Complete (Vol.1 (2GB))"))
{
part = "civil_complete" ;
}
newFolder = "/voice";
subjects = (TextView)findViewById(R.id.subjects);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + newFolder);
//File f = new File(myNewFolder);
myNewFolder.mkdir();
Button b = (Button)v;
FilePart = b.getText().toString();
String RemoveSpace = FilePart.split("\u00A0")[0].replace(" ","");
try {
urlString = "http://mobileteacher.in/DealerPackage/" + part + "/" + RemoveSpace + ".zip";
downloadFile();
Toast.makeText(getApplicationContext(), "Download Started", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Please Connect Internet", Toast.LENGTH_LONG).show();
}
}
};
}
public void downloadFile() {
// String urlString = "http://mobileteacher.in/audio/demo/2725.mp3";
if (!urlString.equals("")) {
try {
// Get file name from the url
String fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
// Create Download Request object
DownloadManager.Request request = new DownloadManager.Request(Uri.parse((urlString)));
// Display download progress and status message in notification bar
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Set description to display in notification
// request.setDescription("Download " + fileName + " from " + urlString);
request.setDescription("Download " + fileName + " from mobileteacher.in");
// Set title
request.setTitle("Mobile Teacher");
// Set destination location for the downloaded file
request.setDestinationUri(Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/voice/"+fileName.split("\u00A0")[0].replace(" ","")));
// Download the file if the Download manager is ready
did = dManager.enqueue(request);
} catch (Exception e) {
}
}
}
// BroadcastReceiver to receive intent broadcast by DownloadManager
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(did);
Cursor cursor = dManager.query(q);
if (cursor.moveToFirst()) {
String message = "";
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
message = "Download successful";
} else if (status == DownloadManager.STATUS_FAILED) {
message = "Download failed";
}
//query.setText(message);
}
}
};
protected void onResume() {
super.onResume();
// Register the receiver to receive an intent when download complete
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Unregister the receiver
unregisterReceiver(downloadReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_download_packages, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void back(View view)
{
finish();
}
public void Create(View view)
{
String newFolder = "/voice";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(ext[enter image description here][1]StorageDirectory + newFolder);
myNewFolder.mkdir();
}
}
this is the image
create relative layout object from it layout id, then you can add it as below
relativeLayout = findViewById(R.id.yourRelativeLayoutId);
relativeLayout.addView(yourView);
Listview or recyclerview is best for practice but as you want to use textview, you can use like this in your code:
RelativeLayout relativeLayout =
(RelativeLayout) findViewById(R.id.rootlayout);
TextView textView = new TextView(this);
textView.setText("Hey, I am TextView");
relativeLayout.addView(textView);
appending a textview to relativelayout is pretty simple.
just use
TextView textview = new TextView(this);
textview.setText("Text");
relativelayoutobject.addView(textview);
to setup the position use
textview.setLayoutParams(thelayoutparams)
But if you use big database, please, use 'TableLayout' instead of your method due to performance reasons.
Define relative layout in your xml layout. Add multiple textview programmatic ally like this-
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
//use a for loop to define multiple textView in RelativeLayout
//length is no. of textView you required
for (int i = 0; i < length; i++) {
TextView tv = new TextView(relativeLayout.getContext());
tv.setText("Text from sqlite database");
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
relativeLayout.addView(tv);
}
How can I move a question on single page on Android for quiz app using sqllite ?
I have used this code for the next button:
Cursor cus = db.rawQuery("select * from java", null);
cus.moveToNext();
que = cus.getString(0);
question.setText(que);
A = cus.getString(1);
a.setText(A);
B = cus.getString(2);
b.setText(B);
C = cus.getString(3);
c.setText(C);
D = cus.getString(4);
d.setText(D);
but it is not working.
If you want to insert a new question on the click of next button then do someththing like this-
final Cursor cus = db.rawQuery("select * from java", null);
cus.moveToPosition(-1);
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (cus.moveToNext()) {
que = cus.getString(0);
question.setText(que);
A = cus.getString(1);
a.setText(A);
B = cus.getString(2);
b.setText(B);
C = cus.getString(3);
c.setText(C);
D = cus.getString(4);
d.setText(D);
} else {
Toast.makeText(context, "No questions left",Toast.LENGTH_SHORT).show();
}
}
});
TextView desc,details,responsibility,status,txtdate;
EditText equipment_id;
DBController controller = new DBController(this,null,null,1);
ImageButton btnupdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_update_equiments);
equipment_id = (EditText)findViewById(R.id.txtequipmentid);
desc = (TextView)findViewById(R.id.txtdescription);
details = (TextView)findViewById(R.id.txtdetails);
status = (TextView)findViewById(R.id.txtstatus);
txtdate = (TextView)findViewById(R.id.txtdate);
responsibility = (TextView)findViewById(R.id.txtresponsibilitycenter);
btnupdate = (ImageButton)findViewById(R.id.btnupdate);
//desc.setVisibility(View.GONE);
//details.setVisibility(View.GONE);
// responsibility.setVisibility(View.GONE);
// btnupdate.setVisibility(View.GONE);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
txtdate.setText(formattedDate);
//update data
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//String status = "1";
controller = new DBController(getApplicationContext(), null, null ,1);
SQLiteDatabase database = controller.getWritableDatabase();
ContentValues data = new ContentValues();
data.put("description", desc.getText().toString());
data.put("details", details.getText().toString());
data.put("responsibility_center",responsibility.getText().toString());
data.put("status", status.getText().toString());
data.put("date_taken", txtdate.getText().toString());
database.update("tbl_equipments", data, "equipment_id=" + equipment_id.getText().toString(), null);
//database.update("tbl_equipments", data, "equipment_id=" + equipment_id.getText().toString(), null);
Toast.makeText(Search_Equipments.this, "Updated successfully", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
Toast.makeText(Search_Equipments.this,ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
//search equipment
public void searchEquipment(View view){
if (equipment_id.getText().toString().equals("")){
Toast.makeText(Search_Equipments.this,"Please Enter Equipement No.",Toast.LENGTH_LONG).show();
} else {
controller = new DBController(this, null, null , 1);
Equipment equipment = controller.getEquipment(equipment_id.getText().toString());
if (equipment != null){
desc.setText(String.valueOf(equipment.get_description()));
details.setText(String.valueOf(equipment.get_details()));
responsibility.setText(String.valueOf(equipment.get_responsibility()));
desc.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
responsibility.setVisibility(View.VISIBLE);
btnupdate.setVisibility(View.VISIBLE);
}else {
Toast.makeText(Search_Equipments.this,"Not Found",Toast.LENGTH_LONG).show();
}
}
}
can someone help my code. if passed the condition that data successfully updated but when i display the updated data from database data has not updated, can someone help me to fix this. . . . . . because i dont where is my error there. see my update code. thanks :)
You forgot to commit the transaction.
database.setTransactionSuccessful();
database.endTransaction();
I will go straight to the point. I have 1 class where I have 6 buttons. Each button saves to an SQLiteDatabase some parameters and then it launches an Activity.
The new Activity takes the parameters and queries the database to pull data accordingly. When the activity launches I clear the parameters in order to save them again if I press another or the same button.
If 1 table(which is linked to the button) is empty it returns the message I want. The problem is that if 1 is empty then all the tables return the message even if they have data!!
My 1st class
public class HRecords extends Activity {
SQLiteDatabase myDB=null;
Button tes,con,al,me,pr,va;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.records);
tes=(Button) findViewById(R.id.testbut);
con=(Button) findViewById(R.id.condbut);
al=(Button) findViewById(R.id.albut);
me=(Button) findViewById(R.id.medbut);
pr=(Button) findViewById(R.id.procbut);
va=(Button) findViewById(R.id.vacbut);
Database openHelper = new Database(this);//create new Database to take advantage of the SQLiteOpenHelper class
myDB = openHelper.getWritableDatabase(); // or getWritableDatabase();
myDB=SQLiteDatabase.openDatabase("data/data/com.example.login2/databases/aeglea", null, SQLiteDatabase.OPEN_READWRITE);//set myDB to aeglea
doclicks();
}
private void doclicks(){
tes.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Tests");
values.put("tazle","user_test");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
con.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Medical Conditions");
values.put("tazle","user_cond");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
al.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Allergies");
values.put("tazle","user_all");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
me.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Medication");
values.put("tazle","user_med");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
pr.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Medical Procedures");
values.put("tazle","user_proc");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
va.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Vaccinations");
values.put("tazle","user_vacc");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
}
}
The second class which as you can see it pulls data from the SQLite database(you can also see the message for empty results "Nothing Added here. Go to the site to add more.")
public class Record extends Activity{
SQLiteDatabase myDB=null;
TextView title=null;
Cursor cur,cur2=null;
ListView list=null;
private ArrayAdapter<String> listAdapter ;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.record);
title = (TextView) findViewById(R.id.recordTitle);
list = (ListView) findViewById(R.id.listView1);
Database openHelper = new Database(this);
myDB = openHelper.getReadableDatabase();
myDB=SQLiteDatabase.openDatabase("data/data/com.example.login2/databases/aeglea", null, SQLiteDatabase.OPEN_READONLY);
Database db = new Database(getApplicationContext());
cur = fetchOption("SELECT * FROM history_go");
title.setText(cur.getString(cur.getColumnIndex("ton")));
ArrayList<String> itemlist = new ArrayList<String>();
String[] names=null;
//do query
cur2=fetchOption("SELECT * FROM "+cur.getString(cur.getColumnIndex("tazle")));
//check for results
if (cur2.getCount()==0) {
names = new String[] { "Nothing Added here. Go to the site to add more."};
}else{
names = new String[] {cur2.getString(cur2.getColumnIndex("name"))};
}
//add the array as list to the ArrayList
itemlist.addAll( Arrays.asList(names) );
listAdapter = new ArrayAdapter<String>(this, R.layout.item, itemlist);
//if results add the rest
if(cur2.getCount()!=0){
for(int i=0;i<(cur2.getCount()-1);i++){
cur2.moveToNext();
listAdapter.add(cur2.getString(cur2.getColumnIndex("name")));
}
}
// Set the ArrayAdapter as the ListView's adapter.
list.setAdapter(listAdapter);
//remove the navigation history
db.resetHistoryNavigation();
cur.close();
cur2.close();
}
public Cursor fetchOption(String query) throws SQLException {
Cursor mCursor = myDB.rawQuery(query, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
EDIT
Also, I forgot to mention that if I set the verification conditions as cur2 == null the application crushes because the cursor goes out of bounds(the for loop fires)
I found what was wrong. The empty set was triggering the catch exception and nothing else was received afterwards. So every table was null.
I had to implement multiple try/catch
private void doclicks(){
hr.setOnClickListener(new View.OnClickListener() {
private Database db = new Database(getApplicationContext());
JSONArray allergy,condition,medication,procedure,test,vaccine;
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("uid", cursor.getString(cursor.getColumnIndex("uid"))));
JSONObject response = null;
try {
CustomHttpTask asdf = new CustomHttpTask();
response = asdf.execute("http://192.168.1.4/aeglea/android/history.php", postParameters).get();
if(response.getString("success").equals("1")){
//get JSON Arrays
try{test = response.getJSONArray("test");}catch(Exception e){}
try{allergy = response.getJSONArray("allergy");}catch(Exception e){}
try{condition = response.getJSONArray("condition");}catch(Exception e){}
try{medication = response.getJSONArray("medication");}catch(Exception e){}
try{procedure = response.getJSONArray("procedure");}catch(Exception e){}
try{vaccine = response.getJSONArray("vaccine");}catch(Exception e){}
}
}catch (Exception e) {
Log.e("HHHERPT","YO MAMAA "+e);
}
//temp JSONOnject
JSONObject buffer=null;
//reset older values
db.resetHistory();
//Store values
try{
for(int i=0;i<allergy.length();i++){
buffer=allergy.getJSONObject(i);
db.addRecords("allergy",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
1,
"",
(float) 0.1,
1,
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<condition.length();i++){
buffer=condition.getJSONObject(i);
db.addRecords("condition",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
Integer.parseInt(buffer.getString("year")) ,
"",(float) 0.1,
Integer.parseInt(buffer.getString("current")),
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<medication.length();i++){
buffer=medication.getJSONObject(i);
db.addRecords("medication",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
1,
"",
(float) 0.1,
Integer.parseInt(buffer.getString("current")),
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<procedure.length();i++){
buffer=procedure.getJSONObject(i);
db.addRecords("procedure",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
Integer.parseInt(buffer.getString("year")),
buffer.getString("comments"),
(float) 0.1,
0,
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<vaccine.length();i++){
buffer=vaccine.getJSONObject(i);
db.addRecords("vaccine",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
Integer.parseInt(buffer.getString("year")),
"",
(float) 0.1,
0,
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<test.length();i++){
buffer=test.getJSONObject(i);
db.addRecords("test",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
Integer.parseInt(buffer.getString("year")),
buffer.getString("comments"),
(float) Float.parseFloat(buffer.getString("value")),
1,
1);
}
}catch(Exception e){
}
//create new intent
Intent records = new Intent(getApplicationContext(), HRecords.class);
// Close all views before launching logged
records.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(records);
// Close Login Screen
onPause();
}
});
}
I have a function to find an employee's id number from my sqlite database. The function allows the user to look up by id or name (first and/or last); therefore it creates several dialog boxes and finds the data through an If Else Then tree. Here's the code for those who like that sort of thing:
public String getEmployeeID() {
final CharSequence[] items = {"By ID", "By Name", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(LibraryScreen.this);
builder.setTitle("Find Employee");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("Cancel")) {
dialog.cancel();
empid = "";
} else if(items[item].equals("By ID")) {
dialog.cancel();
final Dialog dialog2 = new Dialog(LibraryScreen.this);
dialog2.setContentView(R.layout.peopledialog);
dialog2.setTitle("Employee ID");
dialog2.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog2.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog2.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee ID");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog2.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00000002);//numbers
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 15;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog2.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog2.findViewById(R.id.txtGeneral);
String newemp = "";
db.open();
Cursor c = db.getEmployee(emplid.getText().toString());
if(c.moveToFirst()) {
empid = c.getString(c.getColumnIndex("employeeid"));
} else {
Toast.makeText(LibraryScreen.this, "No ID Match", Toast.LENGTH_LONG).show();
empid = "";
}
c.close();
db.close();
dialog2.dismiss();
}
});
Button buttonCan = (Button) dialog2.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog2.dismiss();
empid = "";
}
});
dialog2.show();
} else if(items[item].equals("By Name")) {
dialog.cancel();
final Dialog dialog1 = new Dialog(LibraryScreen.this);
dialog1.setContentView(R.layout.peopledialog);
dialog1.setTitle("Employee's Name");
dialog1.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog1.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog1.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee Name");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog1.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00002001);//cap words
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 50;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog1.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog1.findViewById(R.id.txtGeneral);
String firstname = emplid.getText().toString();
String lastname = "";
String matchlist = "";
String temptext = "";
int matchcount = 0;
if(firstname.lastIndexOf(" ") <= 0) {
lastname = firstname;
firstname = "X";
} else {
lastname = firstname.substring(firstname.lastIndexOf(" ") + 1);
firstname = firstname.substring(0, firstname.lastIndexOf(" "));
}
db.open();
Cursor c1, c2;
String titletext = "";
if(firstname.length() > 0) {
c1 = db.getEmployeeByName(lastname, firstname);
if(c1.getCount() == 0) {
c1 = db.getRowByFieldTextOrdered("employees", "lastname", lastname, "lastname, firstname");
if(c1.getCount() == 0) {
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
}
}
if(c1.getCount() > 0) {
do {
c2 = db.getRowByField("orgcodes", "manager", c1.getString(c1.getColumnIndex("employeeid")));
if(c2.moveToFirst()) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(9, 10).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(7, 8).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(5, 6).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(4, 5).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(3, 4).equals("0")) {
titletext = "Top Brass";
} else {
titletext = "Senior VP";
}
} else {
titletext = "VP";
}
} else {
titletext = "Director";
}
} else {
titletext = "Senior Manager";
}
} else {
titletext = "Manager";
}
} else {
titletext = "Employee";
}
matchcount++;
matchlist = matchlist + c1.getString(c1.getColumnIndex("employeeid")) + ": " + c1.getString(c1.getColumnIndex("firstname")) + " " + c1.getString(c1.getColumnIndex("lastname")) + ": " + titletext + "|";
} while(c1.moveToNext());
}
} else {
empid = "";
}
if(matchcount == 0) {
db.close();
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
} else {
final CharSequence[] items = new CharSequence[matchcount + 1];
items[0] = "(Cancel)";
for(int i = 1; i <= matchcount; i++) {
items[i] = matchlist.substring(0, matchlist.indexOf("|"));
matchlist = matchlist.substring(matchlist.indexOf("|") + 1);
}
db.close();
AlertDialog.Builder builder1 = new AlertDialog.Builder(LibraryScreen.this);
builder1.setTitle("Select Employee");
builder1.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("(Cancel)")) {
dialog.cancel();
empid = "";
} else {
String wasted = items[item].toString();
empid = wasted.substring(0, wasted.indexOf(":"));
dialog.cancel();
}
}
});
AlertDialog alert1 = builder1.create();
alert1.show();
}
dialog1.dismiss();
}
});
Button buttonCan = (Button) dialog1.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog1.dismiss();
empid = "";
}
});
dialog1.show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
return empid;
}
I use the employee id for a variety of functions through multiple activities in my program. Up to now, I've simply pasted the code under each listener that needs the id, but that is such a waste of space IMHO.
My question:
Is there a way to put this function somewhere that can be called from many different activities?
If so:
How do I do that?
How do I set the context for the dialog boxes for multiple activities?
How do I get the employee id back to the function that needs it?
I'm sure this has been asked before, but I haven't been able to find it online: actually, I'm not even sure how to word the query right. My attempts have come up woefully short.
A little late to the party - but recorded for posterity:
Read up on the Application class:
Base class for those who need to maintain global application state.
You can provide your own implementation by specifying its name in your
AndroidManifest.xml's tag, which will cause that class
to be instantiated for you when the process for your
application/package is created.
Basically, this would give you the ability to obtain a single object that represents your running application (think of it as a singleton that returns an instance of your running app).
You first start off by creating a class that extends Application base class and defining any common code that is used throughout your application
import android.app.Application;
public class MyApplication extends Application {
public void myGlobalBusinessLogic() {
//
}
}
Then tell your application to use the MyApplication class instead of the default Application class via the <application> node in your app manifest:
<application android:icon="#drawable/icon" android:label="#string/app_name"
android:name="MyApplication">
Finally, when you need to get to your common function just do something like:
MyApplication application = (MyApplication) getApplication();
application.myGlobalBusinessLogic();
If you need to get the context from any part of your application, you can simple return it by calling getApplicationContext() (defined in the base Application class) via a getter method within your custom application class.