I'm having a issue where when I go to the next activity and pass then data with the intent it is only showing me the last entry off the DB and not the clicked items info.
.java
public class TimsFavs extends ListActivity implements OnItemClickListener {
/** Called when the activity is first created. */
ArrayList<String> results = new ArrayList<String>();
// Database results
String col0,col1,col2,col3,col4,col5,col6,col7;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.timsfavs);
DBAdapter db = new DBAdapter(this);
//---get all Locations---
db.open();
Cursor c = db.getAllLocation();
if (c.moveToFirst())
{
do {
col0 = c.getString(c.getColumnIndex(DBAdapter.KEY_ROWID));
col1 = c.getString(1);
col2 = c.getString(2);
col3 = c.getString(3);
col4 = c.getString(4);
col5 = c.getString(5);
col6 = c.getString(6);
col7 = c.getString(7);
results.add(col0);
} while (c.moveToNext());
}
db.close();
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
ListView lv;
lv = getListView();
lv.setTextFilterEnabled(true);
lv.setBackgroundColor(Color.rgb(83, 05, 14));
lv.setOnItemClickListener((OnItemClickListener) this);
}
public void onItemClick(AdapterView<?> TimsFavs, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), TimsFavsMore.class);
i.putExtra("ct_id_pass", col0);
i.putExtra("ct_storeid_pass", col1);
i.putExtra("ct_address_pass", col2);
i.putExtra("ct_city_pass", col3);
i.putExtra("ct_province_pass", col4);
i.putExtra("ct_country_pass", col5);
i.putExtra("ct_pcode_pass", col6);
i.putExtra("ct_phnum_pass", col7);
startActivity(i);
finish();
}
}
and my other activity is
`public class TimsFavsMore extends Activity {
DBAdapter db = new DBAdapter(this);
String rowId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timsfavsmore);
Intent i = getIntent();
Bundle b = i.getExtras();
final String rowId = b.getString("ct_id_pass");
final String phnum = b.getString("ct_phnum_pass");
final String storeid = b.getString("ct_storeid_pass");
final String address = b.getString("ct_address_pass");
final String city = b.getString("ct_city_pass");
final String province = b.getString("ct_province_pass");
final String country = b.getString("ct_country_pass");
final String pcode = b.getString("ct_pcode_pass");
TextView title = (TextView) findViewById(R.id.textview);
title.setText(Html.fromHtml("<br>Row ID: " + rowId + "<br><b><u>Location Address:</u></b><br><br>Store #" + storeid + "<br><br>" + address + "<br>" + city + ", " + province + "<br>" + country +"<br>" + pcode +"<br><br><b><u>Contact Info:</b></u><br><br>" + phnum +"<br>"));
// open to Nav
final Button button1 = (Button) findViewById(R.id.gohere);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String uri = "google.navigation:q=Tim%20Hortons,%20" + address + ",%20" + city + ",%20" + province + ",%20" + pcode + "";
Intent i2 = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i2);
}
});
// open to maps
final Button button2 = (Button) findViewById(R.id.showmap);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String uri2 = "geo:0,0?q=Tim%20Hortons,%20" + address + ",%20" + city + ",%20" + province + ",%20" + pcode + "";
Intent i3 = new Intent(Intent.ACTION_VIEW, Uri.parse(uri2));
startActivity(i3);
}
});
// Add to My Timmies List
final Button button3 = (Button) findViewById(R.id.removefav);
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//---add 2 SQLite---
db.open();
if (db.deleteLocation(rowId))
Toast.makeText(getApplicationContext(), " Delete successful.",
Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Delete failed.",
Toast.LENGTH_LONG).show();
db.close();
Intent i = new Intent(getApplicationContext(), MyTimmies.class);
startActivity(i);
finish();
}
});
final Button button4 = (Button) findViewById(R.id.favsdone);
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i4 = new Intent(getApplicationContext(), MyTimmies.class);
startActivity(i4);
finish();
}
});
}
}`
Any Ideas?
You are iterating through your cursor and assigning the values to your strings. when it completes the iteration, your strings only contain the last value you assigned and then you pass that.
You should bind your list to a SimpleCursorAdapter instead of creating a whole different string array. Then in your onClickListener, you can just pass the key that identifies your row of data in the database.
Related
We can show all records in the DB no issue. When we try to limit the items to show with a sql Select the search and the RecyclerView Adapter populates correctly.
The code fails when the item is selected in the list view. The list view did not get the message about what position this record is at so the view when we navigate to the DetailActivity view from ListActivity is not the item in the ListView
My question is how to manage the position variable that the Adapter is using?
This code flow is as follows a button click on MainActivity sets the search variable goes to ListActivity that makes a call to DBHelper which returns to ListActivity with modelList which is and Array List Yes the design is MVP so we have a Model Class relevant code below
Main Activity btn Click
public void findAllData(View view){
selectSTRING = etFromDate.getText().toString();
Intent intent = new Intent( MainActivity.this, ListActivity.class );
startActivity( intent );
}
ListActivity call to DBHelper commented out line gets all data
helpher = new DBHelper(this);
dbList = new ArrayList<>();
dbList = helpher.getRangeDataFromDB();
//dbList = helpher.getDataFromDB();
DBHelper code to grab the selected record or records eventually
public List<DBModel> getRangeDataFromDB() {
List<DBModel> modelList = new ArrayList<>();
db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_INFO + " WHERE " + Col_PURCHASE_DATE + " ='" + selectSTRING + "'";
Cursor cursor = db.rawQuery(query, null);
//Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_INFO + " WHERE " + Col_PURCHASE_DATE + "='" + str + "'" , null);
String newBACK = selectSTRING;
if (cursor.moveToFirst()) {
DBModel model = new DBModel();
while (!cursor.isAfterLast()) {
if (newBACK == selectSTRING) {
model.setRowid(cursor.getString(0));
model.setStation_Name(cursor.getString(1));
model.setDate_of_Purchase(cursor.getString(2));
model.setGas_Cost(cursor.getString(3));
modelList.add(model);
cursor.moveToNext();
}
}
}
int sz = modelList.size();
System.out.println("========= SIZE "+sz);
db.close();
return modelList;
}
Now we use an intent to go to DetailsActivity and this is the fail
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
static List<DBModel> dbList;
static private Context context;
RecyclerAdapter(Context context, List<DBModel> dbList) {
RecyclerAdapter.dbList = new ArrayList<>();
RecyclerAdapter.context = context;
RecyclerAdapter.dbList = dbList;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {
holder.rowid.setText(dbList.get(position).getRowid());
holder.station.setText(dbList.get(position).getStation_Name());
System.out.println("========== new position "+position);
}
#Override
public int getItemCount() {
return dbList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView station, rowid;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
rowid = (TextView) itemLayoutView.findViewById(R.id.rvROWID);
station = (TextView) itemLayoutView.findViewById(R.id.rvSTATION);
// Attach a click listener to the entire row view
itemLayoutView.setOnClickListener(this);
}
#Override // When an item in DetailsActivity is touched (selected) the RecyclerView has
// a OnClickListener attached in the above Code that implements the method below
public void onClick(View v) {
System.out.println("======RowID "+rowid);
Intent intentN = new Intent(context, DetailsActivity.class);
Bundle extras = new Bundle();
extras.putInt("POSITION", getAdapterPosition());
extras.putString("FROM_LIST_ACTIVITY", "false");
///position = getAdapterPosition();
///position = getLayoutPosition();// Both work the same
intentN.putExtras(extras);
context.startActivity(intentN);
}
}
Thought about sending the data back from the DBHelper not sure how to write an Intent in that Class. This is turning into spaghetti code!
The solution to this issue is the developer had multiple search designs in the DBHelper each being triggered by different buttons on the search Activity this design in the DBHelper lead to multiple ArrayLists all with the same name this drove the RecycleAdapter crazy as it is bound to ArrayList so OLD Mr. Boolean to the rescue! Here is the revised design code features
In the Search Activity declare public static Boolean use = false;
and Import where needed import static com..MainActivity.use;
Here is the code for each search button
public void findAllData(View view){
helper = new DBHelper(this);
helper.getDataFromDB();
use = false;
// Set Mr. Boolean
Intent intent = new Intent( MainActivity.this, ListActivity.class );
// ListActivity shows Results of the Search
startActivity( intent );
}
public void findSelect(View v){
selectSTRING = etFromDate.getText().toString();
// Get your Search variable
helper = new DBHelper(this);
helper.getDataFromDB();
etToDate.setText(sendBACK);
use = true;
Intent intent = new Intent( MainActivity.this, ListActivity.class );
startActivity( intent );
}
Now we do the desired Search in DBHelper
/* Retrive ALL data from database table named "TABLE_INFO" */
public List<DBModel> getDataFromDB(){
//String query = "SELECT * FROM " + TABLE_INFO + " WHERE " + Col_PURCHASE_DATE + " > 0 " + " ORDER BY " + Col_ID + " DESC ";
/* Notice the SPACES before AND after the words WHERE ORDER BY ASC or DESC most of all the condition " > 0 "*/
/* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=*/
Cursor cursor = null;
List<DBModel> modelList = new ArrayList<>();
if(use == true){
String query = "SELECT * FROM " + TABLE_INFO + " WHERE " + Col_PURCHASE_DATE + " ='" + selectSTRING + "'";
db = this.getWritableDatabase();
cursor = db.rawQuery(query,null);
}
if(use == false){
String query = "SELECT * FROM " + TABLE_INFO;
db = this.getWritableDatabase();
cursor = db.rawQuery(query,null);
}
if (cursor.moveToFirst()){
do {
DBModel model = new DBModel();
model.setRowid(cursor.getInt(0));
model.setStation_Name(cursor.getString(1));
model.setDate_of_Purchase(cursor.getString(2));
model.setGas_Cost(cursor.getString(3));
modelList.add(model);
int sz = modelList.size();
int out = model.setRowid(cursor.getInt(0));
String out1 = model.setStation_Name(cursor.getString(1));
String out2 = model.setDate_of_Purchase(cursor.getString(2));
String out3 = model.setGas_Cost(cursor.getString(3));
System.out.println("==============getDataFromDB ID "+out);
System.out.println("==============getDataFromDB Station "+out1);
System.out.println("==============getDataFromDB Date "+out2);
System.out.println("==============getDataFromDB Cost "+out3);
System.out.println("======= ======getDataFromDB SIZE "+sz);
}while (cursor.moveToNext());
}
db.close();
cursor.close();
return modelList;
}
The only stumble with this is that if if you do a search by date and do an add to the DB and jump back to the ListActivity the new record is not displayed
We are working on this Stay Tuned ha ha Good Job James_Duh
You should set your OnClickListener here :
#Override
public void onBindViewHolder(ReportAdapter.ViewHolderReport holder, int position) {
final Object object = objects.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do Something with the object at this position
}
});
}
instead of your ViewHolder because you shouldn't trust the adapter position at a time.
I'm trying to pass the ListView position via intent and not the id. Is there anyway of doing this. When I delete an item, i want to pass the changed position. Currently, both the position and id are the same.
If there's a better way (i.e. if statement in 2nd view), please explain.
public class MyCollection extends Activity {
private ListView listView;
List<MyMovieDataModel> movieList;
MyDatabase database;
MyMovieAdapter myMovieAdapter;
private static final String TAG = "popularmovies";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_collection_main);
database = new MyDatabase(this);
movieList = database.getAllItems();
myMovieAdapter = new MyMovieAdapter(this, R.layout.my_collection_row, movieList);
listView = (ListView) findViewById(R.id.myCollection_listView);
listView.setAdapter(myMovieAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MyCollection.this, MyDetailView.class);
intent.putExtra("movie", position);
Log.d(TAG, "Intent position: " + position);
Log.d(TAG, "Intent id: " + id);
startActivity(intent);
}
});
clickToDetail();
}
public void clickToDetail() {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MyCollection.this, MyDetailView.class);
intent.putExtra("movie", position);
Log.d(TAG, "Intent position: " + position);
Log.d(TAG, "Intent id: " + id);
startActivity(intent);
}
});
}
This is from 2nd view:
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
mPosition = bundle.getInt("movie");
Log.d(TAG, "Bundle mPosition: " + mPosition);
}
moviePosition = (int) (mPosition + 1);
Log.d(TAG, "Bundle moviePosition: " + moviePosition);
MyDatabase myDatabase = new MyDatabase(this);
database = myDatabase.getWritableDatabase();
String selectQuery = "SELECT * FROM " + MyDatabase.DATABASE_TABLE + " WHERE _id = " + moviePosition;
Log.d(TAG, "SQL Query Position: " + moviePosition);
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToFirst()) {
do {
idList.add(cursor.getInt(0));
list.add(cursor.getString(1));
list.add(cursor.getString(2));
list.add(cursor.getString(3));
list.add(cursor.getString(4));
//list.add(cursor.getString(5));
} while (cursor.moveToNext());
}
cursor.moveToFirst();
//Link & Set Detail Views//
detailID = (TextView) findViewById(R.id.detailID);
detailID.setText(cursor.getString(0));
detailTitle = (TextView) findViewById(R.id.detailTitle);
detailTitle.setText(cursor.getString(1));
detailDate = (TextView) findViewById(R.id.detailDate);
detailDate.setText(cursor.getString(2));
detailRating = (TextView) findViewById(R.id.detailRating);
detailRating.setText(cursor.getString(3));
detailSynopsis = (TextView) findViewById(R.id.detailSynopsis);
detailSynopsis.setText(cursor.getString(4));
//detailPoster = (ImageView) findViewById(R.id.detailPoster);
}
I'm guessing you are correctly passing item's position through intent; all you need to do is in your MyDetailView, call
getIntent().getIntExtra("movie", 0);
where "movie" has to be the same String value as you specified when putting extra into intent, and 0 is the default value that will be passed if there is no value associated with the key(in this case "movie"). Then you can receive correct item's position.
I couldn't get corresponds data from list view's item.
here i am using sms and email templates. when i click on sms or any email listviews item then it will open in edit text form db and then could update data and then store. corresponding with email or sms .i create fields into db for email and sms template such as
id, template_name, message, template_code(0,1) i.e. specifies which on i'm using either sms or email.
here is three activity ManageEmailTemplate, ManageSmsTemplate that intents to next activity i.e. SMSTemplateEdit
ManageEmailTemplate.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_email_template);
//-------------------------
dba = new MyDB(this);
dba.open();
mQuery = "Select " +
Constants.KEY_ID_GREET + "," +
Constants.GREETING_NAME + "," +
Constants.GREETING_MESSAGE+ "," +
Constants.KEY_ID_SETUP_GREET +
" from " + Constants.TABLE_NAME_GREETINGS +
" where " + Constants.KEY_ID_SETUP_GREET + " = " + Constants.EMAIL_CODE;
c = dba.getResults( mQuery );
startManagingCursor(c);
String[] resultColumns;
if( c != null && c.moveToFirst()){
}
int[] textviews = new int[] {android.R.id.text1};
resultColumns = new String[] { Constants.GREETING_NAME};
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, resultColumns, textviews);
this.setListAdapter(mAdapter);
getListView().setTextFilterEnabled(true);
//dba.close();
//-------------------------
// Create Email Templates
//setup Create Email Templates Listener
Button createEmailTemplatesButton = (Button) findViewById(R.id.create_email_template_button);
createEmailTemplatesButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
showCreateEmailTemplate();
}
});
}
private void showCreateEmailTemplate(){
Intent i = new Intent(this, CreateNewTemplate.class);
i.putExtra("template_type","email");
//startActivity(i);
startActivityForResult(i, mRequestCode);
}
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
super.onItemClick(parent, v, position, id);
final Cursor c = (Cursor) mAdapter.getItem(position);
String name = c.getString(c.getColumnIndex( Constants.GREETING_NAME ));
final int template_id = c.getInt(c.getColumnIndex( Constants.KEY_ID_GREET ));
temp_id=String.valueOf(template_id);
goForEdit();
//confirm
Toast.makeText(this,
"Name :"+name+" id : " +template_id , Toast.LENGTH_LONG)
.show();
}
public void goForEdit(){
Intent launchSMSTempEdit = new Intent(
ManageEmailTemplate.this,
EmailSMSTempEdit.class);
launchSMSTempEdit.getExtras().get("selection"));
// startActivity(launchSMSTempEdit);
// Toast.makeText(this, temp_id, Toast.LENGTH_LONG).show();
// startActivity(launchSMSTempEdit);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("Temp_id", temp_id);
editor.putString("template_type", "email");
//commits your edits
editor.commit();
startActivity(launchSMSTempEdit);
}
}
ManageSMSTemplate.java
public class ManageSMSTemplate extends
ActionBarListActivity {
private MyDB dba;
private Cursor c;
String temp_id;
private SimpleCursorAdapter mAdapter;
private int mRequestCode = 0000;
ListView lst;
private String mQuery;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState)
{
lst =(ListView)findViewById(android.R.id.list);
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_sms_template);
// -------------------------
dba = new MyDB(this);
dba.open();
mQuery = "Select " + Constants.KEY_ID_GREET + ","
+ Constants.GREETING_NAME + ","
+ Constants.GREETING_MESSAGE + ","
+ Constants.KEY_ID_SETUP_GREET + " from "
+ Constants.TABLE_NAME_GREETINGS
+ " where " + Constants.KEY_ID_SETUP_GREET
+ " = " + Constants.SMS_CODE;
c = dba.getResults(mQuery);
startManagingCursor(c);
String[] resultColumns;
if (c != null && c.moveToFirst()) {
}
int[] textviews = new int[] { android.R.id.text1 };
resultColumns = new String[] { Constants.GREETING_NAME };
mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, c,
resultColumns, textviews);
this.setListAdapter(mAdapter);
getListView().setTextFilterEnabled(true);
// -------------------------
// Create sms Templates
// setup Create SMS Templates Listener
Button createSMSTemplatesButton = (Button) findViewById(R.id.create_sms_template_button);
createSMSTemplatesButton
.setOnClickListener(new OnClickListener() {
public void onClick(View view)
{
showCreateSMSTemplate();
}
});
}
private void showCreateSMSTemplate()
{
Intent i = new Intent(this, CreateNewTemplate.class);
i.putExtra("template_type", "sms");
startActivityForResult(i, mRequestCode);
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode,
data);
Log.v("Crash",
"Returned from template creation in SMStemplate Manager");
if (mAdapter == null)
Log.d("Crash", "SMS-Manager - mAdapter is NULL");
else
Log.d("Crash",
"SMS-Manager - mAdapter is NOT Null");
if (requestCode == mRequestCode) {
if (resultCode == RESULT_OK) {
if (mAdapter.getCursor() != null)
mAdapter.getCursor().requery();
mAdapter.notifyDataSetChanged();
}
}
}
#Override
protected void onDestroy()
{
dba.close();
super.onDestroy();
}
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
super.onItemClick(parent, v, position, id);
final Cursor c = (Cursor) mAdapter
.getItem(position);
String name = c.getString(c
.getColumnIndex(Constants.GREETING_NAME));
final int template_id = c.getInt(c
.getColumnIndex(Constants.KEY_ID_GREET));
temp_id=String.valueOf(template_id);
goForEdit();
// confirm
Toast.makeText(this,
"Name :"+name+" id : " +template_id , Toast.LENGTH_LONG)
.show();
}
public void goForEdit(){
Intent launchSMSTempEdit = new Intent(
ManageSMSTemplate.this,
EmailSMSTempEdit.class);
// Intent i = new Intent(ManageSMSTemplate.this, SMSTempEdit.class);
//i.putExtra("KeyId", temp_id.toString());
// startActivity(i);
// launchSMSTempEdit.putExtra("selection", temp_id.toString());
// Log.d("*** OUTBOUND INTENT: ", "" + launchSMSTempEdit.getExtras().get("selection"));
// startActivity(launchSMSTempEdit);
// Toast.makeText(this, temp_id, Toast.LENGTH_LONG).show();
// startActivity(launchSMSTempEdit);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("userName", temp_id);
editor.putString("template_type", "sms");
//commits your edits
editor.commit();
startActivity(launchSMSTempEdit);
}
}
EmailSMSTempEdit.java
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_template);
// sms_key_id=getIntent().getStringExtra("id");
// String sms_key_id;
// if (savedInstanceState == null) {
// Bundle extras = getIntent().getExtras();
// if(extras == null) {
// sms_key_id= null;
// } else {
// sms_key_id= extras.getString("STRING_I_NEED");
// }
// } else {
// sms_key_id= (String) savedInstanceState.getSerializable("STRING_I_NEED");
// }
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sms_key_id = sharedPref.getString("userName", "Not Available");
mTemplateType=sharedPref.getString("template_type", "Not Available");
Toast.makeText(this, mTemplateType, Toast.LENGTH_LONG).show();
dba = new MyDB(this);
dba.open() ;
//array to hold values to show in spinner
nameTypeArr = new String[]{getString(R.string.insert_name_prompt),
getString(R.string.first_name),
getString(R.string.last_name)};
//get views from xml
mNameBox = (EditText) findViewById(R.id.template_name_box);
mSubjectBox = (EditText) findViewById(R.id.template_subject_box);
mMessageBox = (EditText) findViewById(R.id.template_message_box);
mInsertNameSpinner = (Spinner) findViewById(R.id.insert_name_here_spinner);
//create adapter for the spinner and set it
ArrayAdapter<String> mAdapter1=
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, nameTypeArr);
mAdapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mInsertNameSpinner.setAdapter(mAdapter1);
//listener for the spinner
mInsertNameSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//if the spinner has just been created, ignore this call to onItemSelected
if(spinnerBeingCreated == true){
spinnerBeingCreated = false;
return;
}
//what item did the user click in spinner
String typeOfName = parent.getItemAtPosition(pos).toString();
//based on user choice, insert corresponding placeholder in text
if(typeOfName.equals( getString(R.string.first_name) )){
insertAtCurrentLocation( getString(R.string.first_name_placeholder) );
}else if(typeOfName.equals( getString(R.string.last_name) )){
insertAtCurrentLocation( getString(R.string.last_name_placeholder) );
}
//reset the spinner item selection back to first one
mInsertNameSpinner.setSelection(0);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
//if its a template for sms, hide the subject line
LinearLayout subjectarea = (LinearLayout) findViewById(R.id.template_subject_box_container);
if(mTemplateType.equals("sms")){
subjectarea.setVisibility(View.GONE);
} else if(mTemplateType.equals("email")){
subjectarea.setVisibility(View.VISIBLE);
}
fillData(sms_key_id);
//Save the template
//setup Save Template Listener
Button saveTemplateButton = (Button) findViewById(R.id.save_template_button);
saveTemplateButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
// saveTemplate();
updateTemplate(sms_key_id);
}
});
//Cancel
//Cancel Listener
Button cancelTemplateButton = (Button) findViewById(R.id.cancel_template_button);
cancelTemplateButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
finish();
}
});
}
public void fillData(String sms_key_id) {
Toast.makeText(EmailSMSTempEdit.this, sms_key_id, Toast.LENGTH_LONG).show();
dba.open();
String queryStr =
"Select " +
"*" + " from " +
Constants.TABLE_NAME_GREETINGS +
" where "+ Constants.KEY_ID_GREET+"=" + sms_key_id ;
//Toast.makeText(this, queryStr, Toast.LENGTH_SHORT).show();
c = dba.getResults(queryStr);
startManagingCursor(c);
if(c.moveToFirst()){
do{
mNameBox.setText(c.getString(c.getColumnIndex(Constants.GREETING_NAME)));
mMessageBox.setText(c.getString(c.getColumnIndex(Constants.GREETING_MESSAGE)));
// System.out.println(c.getString(c.getColumnIndex(Constants.KEY_ID_GREET)));
// System.out.println(c.getString(c.getColumnIndex(Constants.GREETING_NAME)));
// System.out.println(c.getString(c.getColumnIndex(Constants.GREETING_MESSAGE)));
// System.out.println(c.getString(c.getColumnIndex(Constants.KEY_ID_SETUP_GREET)));
} while(c.moveToNext());
}
}
public void updateTemplate(String sms_key_id){
String subject = mSubjectBox.getText().toString();
String name = mNameBox.getText().toString();
String message = mMessageBox.getText().toString();
dba.open();
//if name is null or empty, don't save
if(name == null || name.equals("")){
Toast.makeText(this, R.string.empty_template_name_error, Toast.LENGTH_LONG).show();
return;
}
//whether its sms or email, requied fro db query
int messageTypeCode = -1; //for sms, it is 0. For email it is 1
if(mTemplateType.equals("email")){
message = subject + subjectMessageDelimiter + message; //|~| is the delimiter
messageTypeCode = Constants.EMAIL_CODE;
} else if(mTemplateType.equals("sms")){
messageTypeCode = Constants.SMS_CODE;
}
String Stmt = "update " +
Constants.TABLE_NAME_GREETINGS +
" set "+
Constants.GREETING_NAME+"='"+name + "',"+
Constants.GREETING_MESSAGE+"='"+message + "'," +
Constants.KEY_ID_SETUP_GREET+"='"+messageTypeCode +"'" +
" where "+ Constants.KEY_ID_GREET+"=" + sms_key_id ;
dba.execute(Stmt);
dba.close();
Toast.makeText(this, "Successfully updated Template: " + name, Toast.LENGTH_LONG).show();
//finish the activity
// setResult(RESULT_OK, null);
finish();
}
#Override
protected void onDestroy(){
//dba.close();
super.onDestroy();
}
//insert at currnet cursor location in subject or message field
private void insertAtCurrentLocation(String str){
int start, end;
if(mMessageBox.hasFocus()){
start = mMessageBox.getSelectionStart();
end = mMessageBox.getSelectionEnd();
mMessageBox.getText().replace(Math.min(start, end), Math.max(start, end),
str, 0, str.length());
} else if(mSubjectBox.hasFocus()){
start = mSubjectBox.getSelectionStart();
end = mSubjectBox.getSelectionEnd();
mSubjectBox.getText().replace(Math.min(start, end), Math.max(start, end),
str, 0, str.length());
}
}
private boolean alreadyExists(String templateName){
int type_code = -1;
if(mTemplateType.equals("sms")){
type_code = Constants.SMS_CODE;
} else if(mTemplateType.equals("email")){
type_code = Constants.EMAIL_CODE;
}
String query = "Select * from " + Constants.TABLE_NAME_GREETINGS
+ " where " + Constants.GREETING_NAME + " = '" + templateName
+ "' AND " + Constants.KEY_ID_SETUP_GREET + "=" + type_code;
Cursor c = null;
Boolean exists = false;
dba.open();
try {
c = dba.getResults( query );
if (c != null) {
if (c.moveToFirst()) {
exists = (c.getCount() > 0);
} else {
exists = false;
}
}
} catch (Exception e) {
Log.e("CreateNewTemplate", "Error while checking if name already exists. Details: "+e.getMessage(), e);
e.printStackTrace();
} finally {
if (c != null)
c.close();
dba.close();
}
return exists;
}
}
move your cursor to the position of the list view item that you have clicked and then fetch the data from db using that cursor. Below is a small snippet:
yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(cursor!=null){
cursor.moveToPosition(position);
//do your stuff here....
cursor.close();
}
}
});
In this userdetails.java i am creating creating a table by name userdetails and inserting values
public class userdetails extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userdetails);
Button dbsave = (Button)findViewById(R.id.save);
dbsave.setOnClickListener(this);
SQLiteDatabase db;
db = openOrCreateDatabase( "Student.db" , SQLiteDatabase.CREATE_IF_NECESSARY , null );
try {
final String UserDetails = "CREATE TABLE IF NOT EXISTS UserDetails ("
+ "NAME,"
+ "MOB_NO,"
+ "Q_NO,"
+ "Q_ANS,"
+ "MAIL_ID,"
+ "PASSWD);";
db.execSQL(UserDetails);
Toast.makeText(userdetails.this, "table created ", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(userdetails.this, "ERROR "+e.toString(), Toast.LENGTH_LONG).show();
}
}
public void onClick(View view){
SQLiteDatabase db;
if(view.getId()==R.id.save)
{
EditText e1 = (EditText) findViewById(R.id.editText1);
String s1=e1.getText().toString();
EditText e2 = (EditText) findViewById(R.id.editText2);
EditText e3 = (EditText) findViewById(R.id.editText3);
String s3=e3.getText().toString();
EditText e4 = (EditText) findViewById(R.id.editText4);
String s4=e4.getText().toString();
EditText e5 = (EditText) findViewById(R.id.editText5);
String s5=e5.getText().toString();
EditText e6 = (EditText) findViewById(R.id.editText6);
String s6 =e6.getText().toString();
// Toast.makeText(Databasedb.this, "table created ", Toast.LENGTH_LONG).show();
String sql =
"INSERT or replace INTO UserDetails (" +
"Name, " +
"Mob_no, " +
"Q_no, " +
"Q_ans,"+
"Mail_id,"+
"Passwd) " +
"VALUES('"+s1+"','"+e2+"','"+s6+"','"+s3+"','"+s4+"','"+s5+"')" ;
db = openOrCreateDatabase( "Student.db" , SQLiteDatabase.CREATE_IF_NECESSARY , null );
db.execSQL(sql);
AlertDialog alertDialog = new AlertDialog.Builder(userdetails.this).create();
// alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("uservalues are successfully added/updated to the database");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(userdetails.this, Login.class);
userdetails.this.startActivity(intent);
}
});
alertDialog.show();
}}
}
and here is my login.java file from where i need to access the userdetails table
public class Login extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button login = (Button) findViewById(R.id.login);
login.setOnClickListener(this);
Button exit = (Button) findViewById(R.id.exit);
exit.setOnClickListener(this);
TextView txt = (TextView) findViewById(R.id.sub);
txt.setOnClickListener(this);
TextView forgot = (TextView) findViewById(R.id.code);
forgot.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.login)
{
EditText p1 = (EditText)findViewById(R.id.inputpasswd);
String s = p1.getText().toString();
Intent intent1= new Intent(this,homepage.class);
startActivity(intent1);
}
else
if(view.getId()==R.id.sub)
{
Intent intent2 = new Intent(this, userdetails.class);
startActivity(intent2);
}
else
{
Intent intent3 = new Intent(this, Forgotpassword.class);
startActivity(intent3);
}
}
}
please any one help me to retrieve values(from login.java) from the database`and comapare that value from the user entered value
thanx in advance....
You don't.
You execute a query of the general form
SELECT COUNT(*) FROM USERS WHERE USERNAME = ? AND PASSWORD = ?
and see whether the count returned is 1 or 0.
That way it's the database that does the comparing.
Also you don't have to deal with details of the password hashing in your code, as you would if you received and compared yourself.
Also there is much less data movement.
Also this procedure means that you can't leak to the user whether his username or his password was incorrect in the event of a failure, which conforms with good security design practice.
To check whether user have entered the proper credentials or not. Use this following code.
String username="";
String password="";
Cursor c = mydb.rawQuery("select * from Users where Username="+username+ " and Password="+password);
if(c.getCount()>0){
Toast.makeText(getApplicationContext(), "Login Succesful",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_LONG).show();
}
When I try to retrieve some data from SQLite in android, the emulator stops working during the execution. This is my code:
public class StartTest extends Activity {
// Objects And Variables
public HtTester _testclass;
private CommentsDataSource datasource2;
private SQLiteDatabase db;
private String _select;
// User Information Variables
String _c1;
String _c2;
String _c3;
String _c4;
String _c5;
String _c6;
String _pregnant;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.starttest);
// Casting Controls To variables
Button _strattest = (Button) findViewById(R.id.btnsendtest);
final EditText _systolic = (EditText) findViewById(R.id.etsystolic);
final EditText _diastolic = (EditText) findViewById(R.id.etdiastolic);
//CheckBox _pregnant = (CheckBox) findViewById(R.id.cbpregnant);
final TextView _result = (TextView) findViewById(R.id.tvresult);
//Start Test Button Operation
_strattest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
datasource2 = new CommentsDataSource();
db = datasource2.SQLiteDatabaseget(StartTest.this);
_select = "SELECT * FROM USERSTABLE WHERE _id=" + getIntent().getExtras().getString("USERID");
Cursor c1 = db.rawQuery(_select, null);
_c1 = getString(c1.getColumnIndex("USERC1"));
_c2 = getString(c1.getColumnIndex("USERC2"));
_c3 = getString(c1.getColumnIndex("USERC3"));
_c4 = getString(c1.getColumnIndex("USERC4"));
_c5 = getString(c1.getColumnIndex("USERC5"));
_c6 = getString(c1.getColumnIndex("USERC6"));
_result.setText(_c1 + "," +_c2 + "," +_c3 + "," +_c4 + "," +_c5+ "," +_c6 );
}
});
}
}
The error is:
02-25 22:06:43.290: E/AndroidRuntime(850): android.content.res.Resources$NotFoundException: String resource ID #0x8