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.
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 wish to send data from a fragment to an activity but my present code doesn't work.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
Context ctx = getActivity();
DBoperations db = new DBoperations(ctx);
Cursor cr = db.getInfo(db);
cr.moveToFirst();
long count = id;
while( count > 0){
cr.moveToNext();
count --;
}
String ID = Integer.toString(cr.getInt(0));
String Name = cr.getString(1);
intent.putExtra("extra",ID + " " + Name);
startActivity(getActivity(),LocationInfo.class);
}
This function is inside a class that extends Fragment.
Here the entire last line startActivity(...) is underlined in red and says:
startActivity(android.content.intent, android.os.Bundle) in Fragment
cannot be applied to
(android.support.v4.app.FragmentActivity,java.lang.Class)
So how to I pass data from fragment to an activity?
I didn't write
startActivity(new Intent(getActivity(),LocationInfo.class));
That was the only issue...
Try this:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), LocationInfo.class);
Context ctx = getActivity();
DBoperations db = new DBoperations(ctx);
Cursor cr = db.getInfo(db);
cr.moveToFirst();
long count = id;
while( count > 0){
cr.moveToNext();
count --;
}
String ID = Integer.toString(cr.getInt(0));
String Name = cr.getString(1);
intent.putExtra("extra",ID + " " + Name);
startActivity(intent);
}
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();
}
}
});
I want to store the edit text value every time into my data base when giving a value into the edit text. I dnt know how to update my table. Every time edit text value changes here edit text indicates the quantity of the recipes I want to calculate amount based on the quantity so for that I want to store quantity value in db. please help me. how to store particular row value into db i can write update query but overall table updation happened there.
Thanks in advance
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class YourOrder extends HelperActivity {
private ListView list;
private DataBaseHandler db;
ArrayList<Contact> imageArry = new ArrayList<Contact>();
OrdersImageAdapter adapter;
public static TextView toatalamount;
EditText qtyView,quantityt;
int total;
double recipeamount=0;
public static Button payment;
public Integer id = null;
public String name = null;
public Integer price = null;
public int quantiy;
public String quan;
double ordercount = 0;
private Double orderTotal = 0.00;
static String ordertotalval;
public String setvaluefinal;
int dbcount = 0;
public double editcount=0;
int count = NewBreakfastItems.getVariable();
ImageHolder holder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourorders);
list = (ListView) findViewById(R.id.listView1);
toatalamount = (TextView) findViewById(R.id.rupees);
db = new DataBaseHandler(this);
payment = (Button) findViewById(R.id.buy);
// Reading all contacts from database
List<Contact> contacts = db.getAllContacts();
Log.d("", "------DATABASE CONTACTS-------" + db.getAllContacts());
for (Contact cn : contacts) {
String log = "ID:" + cn.getID() + " Name: " + cn.getName()
+ " ,Image: " + cn.getImage() + "Price :" + cn.getprice();
Log.d("Name: ", log);
Log.i("", "-----ID-------" + cn.getID());
Log.i("", "-----ID-------" + cn.getName());
Log.i("----recipe price---", "-----price----" + cn.getprice());
id = cn.getID();// Here i am getting the id no...
name = cn.getName();
price = cn.getprice();
ordercount = ordercount + price;
Log.e("---ordercount---", "----ordercount----" + ordercount);
toatalamount.setText(String.valueOf(ordercount));
/*
* count=count+price; Log.i("---count----", "-----count----"+count);
*/
// Writing Contacts to log
Log.e("Result:========== ", "=====LOG=====" + log);
imageArry.add(cn);
}
Log.d("", "-----ID-------" + id);
Log.d("", "-----ID-------" + name);
adapter = new OrdersImageAdapter(this, R.layout.orderscart, imageArry);
list.setAdapter(adapter);
dbcount = db.getContactsCount();
Log.e("----dbcount----", "-----dbcount---" + dbcount);
payment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
Payment.class);
//intent.putExtra("count", count);
intent.putExtra("ordertotalval", ordertotalval);
intent.putExtra("name", name);
startActivity(intent);
}
});
footerBlock();
}
public class OrdersImageAdapter extends ArrayAdapter<Contact> {
// Contact contact;
Context context;
public int dltcount;
int layoutResourceId;
int adaptercount = 0;
public int extPrice;
ArrayList<Contact> data = new ArrayList<Contact>();
public OrdersImageAdapter(Context context, int layoutResourceId,
ArrayList<Contact> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
this.data = new ArrayList<Contact>();
this.data.addAll(data);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
DecimalFormat df = new DecimalFormat("0.00##");
Contact product = data.get(position);
View row = convertView;
holder = null;
Contact lContact = (Contact) list.getItemAtPosition(position);
db = new DataBaseHandler(getContext());
if (row == null) {
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
EditText quantity = (EditText) row.findViewById(R.id.quantity);
//attach the TextWatcher listener to the EditText
quantity.addTextChangedListener(new MyTextWatcher(row));
holder = new ImageHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView) row.findViewById(R.id.imgIcon);
holder.dlttxt = (TextView) row.findViewById(R.id.dlt);
holder.quantity = (EditText) row.findViewById(R.id.quantity);
holder.recipeprice=(TextView) row. findViewById(R.id.recipeprice);
row.setTag(holder);
} else {
holder = (ImageHolder) row.getTag();
}
quantityt = (EditText) row.findViewById(R.id.quantity);
quantityt.setTag(product);
if(product.getQuantity() != 0){
quantityt.setText(String.valueOf(product.getQuantity()));
}
else {
quantityt.setText("");
}
TextView ext = (TextView) row.findViewById(R.id.setprice);
if(product.getQuantity() != 0){
ext.setText("$" + df.format(product.getExt()));
}
else {
ext.setText("");
}
holder.recipeprice.setText(String.valueOf(lContact.getprice()+"X"));
/* ====DELETING RECIPE ITEMS==== */
holder.dlttxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.e("---pos---", "----position----" + position);
Contact lContact = (Contact) list
.getItemAtPosition(position);
Log.e("---pos---", "----position----" + lContact);
Log.e("TAG", "" + lContact.getID());
db.deleteContact(lContact.getID());
// db.deleteContact(pos);
Log.e("", "======deleted=====" + lContact.getID());
Log.e("", "====NAME====" + lContact.getName());
quan = lContact.getName();
Log.e("---lcontact price---", "------lcntact price----"
+ lContact.getprice());
adaptercount = lContact.getprice();
Log.e("","quantity---"+quantityt.getText());
Toast.makeText(
getContext(), lContact.getName() + ":"
+ "Deleted Sucessfully", Toast.LENGTH_SHORT)
.show();
//setvaluefinal=qtyView.getText().toString();
//ordercount=Integer.parseInt(setvaluefinal);
Log.e("", "-----order count----"+ordercount);
//editcount=adaptercount * ordercount;
Log.e("", "----edit count----"+editcount);
//Log.e("", "----order total value----"+orderTotal);
//recipeamount=orderTotal-editcount;
//Log.e("", "------recipe amount-------"+recipeamount);
imageArry.remove(lContact);
adapter.notifyDataSetChanged();// updating adapter
count = db.getContactsCount();
Log.d("", "----updated count----" + db.getContactsCount());
HelperActivity.num.setText(String.valueOf(count));
//toatalamount.setText(String.valueOf(recipeamount));
// YourOrder.toatalamount.setText();
}
});
holder.quantity.setText("1");
Contact picture = data.get(position);
holder.txtTitle.setText(picture._name);
// convert byte to bitmap take from contact class
byte[] outImage = picture._image;
ByteArrayInputStream imageStream = new ByteArrayInputStream(
outImage);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
holder.imgIcon.setImageBitmap(theImage);
// db.deleteContact(null);
return row;
}
public class ImageHolder {
ImageView imgIcon;
TextView txtTitle;
TextView dlttxt;
EditText quantity;
TextView recipeprice;
}
private class MyTextWatcher implements TextWatcher{
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//do nothing
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
//do nothing
}
public void afterTextChanged(Editable s) {
DecimalFormat df = new DecimalFormat("0.00##");
String qtyString = s.toString().trim();
int quantity = qtyString.equals("") ? 0:Integer.valueOf(qtyString);
qtyView = (EditText) view.findViewById(R.id.quantity);
// here i am getting the quantity value i want to store thid value into db
Contact contact = (Contact) qtyView.getTag();
// quantityt.setText(qtyView.getText());
if(contact.getQuantity() != quantity){
int currPrice = contact.getExt();
extPrice = quantity * contact.getprice();
Double priceDiff = Double.valueOf(df.format(extPrice - currPrice));
contact.setQuantity(quantity);
contact.setExt(extPrice);
TextView setprice = (TextView) view.findViewById(R.id.setprice);
if(contact.getQuantity() != 0){
setprice.setText("$" + df.format(contact.getExt()));
}
else {
setprice.setText("");
}
if(contact.getQuantity() != 0){
qtyView.setText(String.valueOf(contact.getQuantity()));
}
else {
qtyView.setText("");
}
orderTotal += priceDiff;
toatalamount.setText(df.format(orderTotal));
ordertotalval=toatalamount.getText().toString();
Log.e("----total value----", "------total value-----"+ordertotalval);
}
}
}
}
}
you can update using update method in sqlite,
ContentValues values=new ContentValues();
values.put(update_column_name, value_of_update_column);
db.update(DATABASE_TABLE_NAME, values, condition_field_name+" =?", new String[] {condition_value_});
However to update row you are having id for it in your table. In Where condition use that id for updating particular row.
Try like this
public SQLiteDatabase db;
String UpdateVAlue = editText.getText().toString(); // Getting edittext value
ContentValues updateValues = new ContentValues();
updateValues.put("ColomnFieldName", UpdateVAlue); // adding thevalues in Content view
db.update("TABLE_NAME", updateValues, WHERE,new String[] {
String.valueOf(ConditionValue) });
I'm loading the same page with different data. I've got it so it's listing my items and when I click one, it's sending the correct next page type and ID through. But it's still loading my first pages SQLStatement. The right things are being logged out.
Do I need to clear it down or something first?
Here is my code:
public class LocationListView extends Activity {
String SQLStatement;
String itemID = "1001-0001021";
String Type;
;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_list_view);
Bundle extras = getIntent().getExtras();
String dataType;
String dataID;
if (extras != null) {
dataType = extras.getString("Type");
dataID = extras.getString("ID");
} else {
dataType = "notset";
dataID = "notset";
}
File dbfile = new File(Global.currentDBfull);
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
if(dataType == "notset") {
SQLStatement = "select * from stationobjects where stationid= " + Global.StationID + " and objectid=0";
Type = "Room";
} else if(dataType == "Room") {
SQLStatement = "select * from stationobjects where stationid= " + Global.StationID + " and objectid=1001 and diagramid like '"+ itemID +"%'";
Type = "Area";
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else if(dataType == "Area") {
Type = "Zone";
} else if(dataType == "Zone") {
} else {
SQLStatement = "select * from stationobjects where stationid= " + Global.StationID + " and objectid=0";
Type = "Room";
}
Cursor c = db.rawQuery(SQLStatement, null);
if(c.getCount() != 0) {
Log.e("LocationListView", "Found Items");
c.moveToFirst();
ArrayList<String> mItemName = new ArrayList<String>();
final ArrayList<String> mItemID = new ArrayList<String>();
c.moveToFirst();
while(!c.isAfterLast()) {
mItemName.add(c.getString(c.getColumnIndex("Name")));
mItemID.add(c.getString(c.getColumnIndex("StationObjectID")));
c.moveToNext();
}
final ListView listView = (ListView) findViewById(R.id.lvLocation);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, mItemName);
int[] colors = {0, 0xFFFF0000, 0};
listView.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
listView.setDividerHeight(1);
listView.setAdapter(adapter);
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Object o = listView.getItemAtPosition(position);
String StationObjectID = mItemID.get(position);
Log.e("LocationListView", "" + o);
Log.e("LocationListView", "" + StationObjectID);
startActivityForResult(SwapPage, 0);
}
});
} else {
Log.e("LocationListView", "Not Found Items");
Context context = getApplicationContext();
CharSequence text = "Sorry No data returned";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
db.close();
}
}
The data from your Intent looks correct, the problem is that in Java you must compare Strings like this:
if(dataType.equals("notset"))
not:
if(dataType == "notset")
Detailed explanation: How do I compare strings in Java?