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?
Related
my problem is cant display all the data i call from my database to my textview when i click the button , but i can only display 1 data at the time , and i read the other question like this but still i dont get it.
This is my Code to call the data from database
public WordObject getPOSbyWords(String wordd){
WordObject wordObject2 = null;
String query2 = "SELECT pos FROM wordbank WHERE words in ("+wordd+")";
Cursor cursor = this.getDbConnection1().rawQuery(query2,null);
if (cursor.moveToFirst()){
do {
//=
String pos1=cursor.getString(cursor.getColumnIndexOrThrow("pos"));
//String pos2 = cursor.getString(cursor.getColumnIndexOrThrow("words"));
wordObject2 = new WordObject(pos1,null);
}while (cursor.moveToNext());
}
cursor.close();
return wordObject2;
}
This my Code in main activity
public class GrammarActivity extends AppCompatActivity {
TextView postv, wordtv;
Button btngo;
MultiAutoCompleteTextView multiple;
Listview listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grammar);
wordtv = (TextView) findViewById(R.id.grammar);
multiple = (MultiAutoCompleteTextView) findViewById(R.id.MultipleAuto);
btngo = (Button) findViewById(R.id.check);
postv = (TextView) findViewById(R.id.Partofspeech);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Welcome user
builder.setMessage("Welcome to the Grammar Checker")
.setIcon(R.mipmap.ic_launcher)
.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create();
builder.show();
//Space Tokenizer splitting the words
final String[] words = getResources().getStringArray(R.array.autocomplete);
multiple.setTokenizer(new SpaceTokenizer());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, words);
multiple.setAdapter(adapter);
btngo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String space = "";
String foo = " ";
String foo1 = ",";
String sentences = null;
String red = multiple.getText().toString();
if (red.isEmpty()) {
Toast.makeText(getApplicationContext(), " Input text please ", Toast.LENGTH_SHORT).show();
multiple.setBackgroundColor(Color.RED);
}else
Toast.makeText(getApplicationContext(), "THanks ", Toast.LENGTH_SHORT).show();
//Splitting the sentence into words
sentences = multiple.getText().toString().toLowerCase();
String[] splitwords = sentences.trim().split("\\s+");
for (String biyak : splitwords) {
foo = (foo + "'" + biyak + "'" + foo1);
String fot = foo.replaceAll(",$", " ");
wordtv.setText(fot);
Db1Backend db1Backend = new Db1Backend(GrammarActivity.this);
WordObject DisplayPOS = db1Backend.getPOSbyWords(fot);
postv.setText(DisplayPOS.getWord());
}
World Class
public class WordObject {
private String word;
private String pos;
public WordObject(String word, String definition) {
this.word = word;
this.pos = definition;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPOS() {
return pos;
}
public void setPOS(String definition) {
this.pos = definition;
}
}
Try this one.
public String getPOSbyWords(String wordd)
{
String myPos = "";
String query2 = "SELECT pos FROM wordbank WHERE words in ("+wordd+")";
Cursor cursor = this.getDbConnection1().rawQuery(query2,null);
try
{
if (cursor != null && cursor.getCount() > 0)
{
while (cursor.moveToNext())
{
String pos1=cursor.getString(cursor.getColumnIndexOrThrow("pos"));
myPos = pos1;
}
}
}
catch (Exception e)
{
// Handle Exception here
}
finally
{
// release cursor
if (cursor != null && !cursor.isClosed())
cursor.close();
}
return myPos;
}
Now in your GrammarActivity inside for loop do this.
// Taking String Builder to append all the String in one.
StringBuilder sb = new StringBuilder();
for (String biyak : splitwords)
{
foo = (foo + "'" + biyak + "'" + foo1);
String fot = foo.replaceAll(",$", " ");
wordtv.setText(fot);
Db1Backend db1Backend = new Db1Backend(GrammarActivity.this);
// Append all your position into StringBuilder
sb.append(db1Backend.getPOSbyWords(fot));
}
postv.setText(sb.toString());
Replace your method with this.
public ArrayList<WordObject> getPOSbyWords(String wordd){
WordObject wordObject2 = null;
String query2 = "SELECT pos FROM wordbank WHERE words in ("+wordd+")";
Cursor cursor = this.getDbConnection1().rawQuery(query2,null);
ArrayList<WordObject> words = new ArrayList<>();
if (cursor.moveToFirst()){
do {
//=
String pos1=cursor.getString(cursor.getColumnIndexOrThrow("pos"));
//String pos2 = cursor.getString(cursor.getColumnIndexOrThrow("words"));
wordObject2 = new WordObject(pos1,null);
words.add(wordObject2);
}while (cursor.moveToNext());
}
cursor.close();
return words;
}
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();
}
}
});
I'm new to android and using sqlite rawquery dynamic where clause condition for the first time and didn't know how to use it. I want to give dynamic value to where clause to get the listview according to particular "mid". How to provide the mid value from SubjectActivty
Here is my code:
TestTable:
public long insert(String id, String time, int mid, String cmarks, String nmarks,
String questions, String testType, String test,String marks) {
log("insert test : " + test);
ContentValues values = new ContentValues();
values.put(KEY_TESTID, id);
values.put(KEY_MID,mid);
values.put(KEY_TEST, test);
values.put(KEY_TIME, time);
values.put(KEY_CMARK, cmarks);
values.put(KEY_NMARK, nmarks);
values.put(KEY_TESTTYPE, testType);
values.put(KEY_QUESTION, questions);
values.put(KEY_Total_Marks, marks);
return db.insert(TABLE_NAME2, null, values);
}
public ArrayList<NotificationListItem> getAllList(
ArrayList<NotificationListItem> privateArrayList) {
openToRead();
privateArrayList.clear();
Cursor cursor = null;
String sql ="SELECT * FROm test_list WHERE mid=?";
cursor= db.rawQuery(sql, null);
log("getAlllist() cursor : " + cursor.getCount());
if (cursor != null) {
log("getAlllist() cursor not null ");
int index = 0;
cursor.moveToFirst();
while (index < cursor.getCount()) {
NotificationListItem item = new NotificationListItem();
int idIndex = cursor.getColumnIndex(TestTable.KEY_TESTID);
int subid= cursor.getColumnIndex(TestTable.KEY_MID);
int nameIndex = cursor.getColumnIndex(TestTable.KEY_TEST);
int idTime = cursor.getColumnIndex(TestTable.KEY_TIME);
int cMarks = cursor.getColumnIndex(TestTable.KEY_CMARK);
int nMarks = cursor.getColumnIndex(TestTable.KEY_NMARK);
int testTypeIndex = cursor.getColumnIndex(TestTable.KEY_TESTTYPE);
int questions = cursor.getColumnIndex(TestTable.KEY_QUESTION);
item.name = cursor.getString(nameIndex);
item.testID = cursor.getString(idIndex);
item.mid=cursor.getInt(subid);
item.time = cursor.getString(idTime);
item.cmark = cursor.getString(cMarks);
item.nmark = cursor.getString(nMarks);
item.testType = cursor.getString(testTypeIndex);
item.questions = cursor.getString(questions);
index++;
privateArrayList.add(item);
cursor.moveToNext();
}
log(" query(): cursor closing");
cursor.close();
db.close();
db = null;
}
return privateArrayList;
}
SubjectActvity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject);
privateListLV = (ListView) findViewById(R.id.privateListLV);
privatelistTable = new SubjectTable(SubjectActivity.this);
testTableStatic = new StaticTestTable(this);
testTable = new TestTable(SubjectActivity.this);
privatelistTable.openToWrite();
privatelistTable.deleteAll();
privatelistTable.insert(10, "Biology");
privatelistTable.insert(20, "Chemistry");
privatelistTable.insert(30, "English");
privatelistTable.insert(40, "Maths");
privatelistTable.insert(50, "GK");
testTable.openToWrite();
testTable.deleteAll();
testTable.insert("1", "10", 10, "5", "2", "2", "Both", "Anatomy", "10");
testTable.insert("2", "10", 20, "5", "2", "2", "Both", "Paper1", "10");
privateArrayList = new ArrayList<NotificationListItem>();
listAdapter = new SubjectCustomListAdapter(this, privateArrayList,
privatelistTable);
privateListLV.setAdapter(listAdapter);
privateListLV.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> adapter, View arg1,
int position, long arg3) {
NotificationListItem selection = (NotificationListItem) adapter
.getItemAtPosition(position);
String item = selection.getName();
System.out.println("item" +item);
if (!item.contentEquals(" ")) {
subjectid = privatelistTable.getSinlgeEntry(item);
Log.e("selected Value", " " + subjectid);
Intent testact = new Intent(getApplicationContext(),
TestsActivity.class);
testact.putExtra("subject", item);
testact.putExtra("mid",subjectid);
startActivity(testact);
} else {
return;
}
}
});
}
#Override
protected void onResume() {
super.onResume();
updateList();
}
private void updateList() {
privatelistTable.getAllList(privateArrayList);
listAdapter.notifyDataSetChanged();
}
Do as #Der Golem answer OR another way is
Cursor c =db.rawQuery("SELECT * FROM " + tableName + " where mid=" + mid , null);
I have created a custom list view with 6 colomns. Each row is populated.
the first 3 fields are textviews,which are filled from db. Then a spinner and the last two edittexts.
i want to enter values to edittexts and spinner.. this much is ok.
The problem is when i enter values in edittext and after that if i scroll the list, the values entered in edittext changes in position. if i entered in first row, after scrolling it will be in last row or any other.. how i can solve this.. Need help pls..
My adapter class is given below.
public class CustomTransAdapter extends BaseAdapter {
public ArrayList<retrieveTrans> ret_arrArrayList;
private List<retrieveTrans> ret_translist;
private LayoutInflater inflater;
ArrayAdapter<String> adapterspin;
String time, currntdate, status;
String Maxcramnt, balamount;
double Mamount, Bamount, actualamnt;
String idpref, str_agent_id2, accno;
int trcheck;
int d = 0;
String tramnt = "", remarks = "";
Context context;
int count;
public CustomTransAdapter(NewTransactionSheet newTransactionSheet,
int transListPop, List<retrieveTrans> translist) {
// TODO Auto-generated constructor stub
super();
this.ret_translist = translist;
inflater = LayoutInflater.from(newTransactionSheet);
this.ret_arrArrayList = new ArrayList<retrieveTrans>();
this.ret_arrArrayList.addAll(translist);
this.context = newTransactionSheet;
String[] items = new String[] { "Type", "credit", "debit" };
final ArrayAdapter<String> adapterspin = new ArrayAdapter<String>(
newTransactionSheet, android.R.layout.simple_spinner_item,
items);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return ret_translist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return ret_translist.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder {
TextView acc_txt, name_txt, balAmnt_txt;
Spinner trans_spinner;
EditText transAmnt_edittxt, remarks_edittxt;
Button save;
}
#Override
public View getView(final int pos, View cv, ViewGroup arg2) {
// TODO Auto-generated method stub
try {
final ViewHolder holder;
View row = cv;
int p = pos;
Log.e("position of getview:", "" + p);
if (cv == null) {
cv = inflater.inflate(R.layout.trans_pop_list, null);
holder = new ViewHolder();
holder.acc_txt = (TextView) cv
.findViewById(R.id.txtTransAccNo_pop);
holder.name_txt = (TextView) cv
.findViewById(R.id.txtTransName_pop);
holder.balAmnt_txt = (TextView) cv
.findViewById(R.id.txtTransBalAmnt_pop);
holder.trans_spinner = (Spinner) cv
.findViewById(R.id.spinTrans_Type);
holder.transAmnt_edittxt = (EditText) cv
.findViewById(R.id.editTransAmnt_pop);
holder.save = (Button) cv.findViewById(R.id.save);
holder.remarks_edittxt = (EditText) cv
.findViewById(R.id.editRemarks_pop);
cv.setTag(holder);
} else {
holder = (ViewHolder) cv.getTag();
}
holder.acc_txt.setText("" + ret_translist.get(pos).getRetAccNo());
String hari = holder.acc_txt.getText().toString();
holder.name_txt.setText("" + ret_translist.get(pos).getRetName());
holder.balAmnt_txt.setText(""
+ ret_translist.get(pos).getRetBalAmnt());
String[] items = new String[] { "Type", "credit", "debit" };
final ArrayAdapter<String> adapterspin = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, items);
final String haris = holder.name_txt.getText().toString();
holder.trans_spinner.setAdapter(adapterspin);
/* ******************* Save button Click **************** */
holder.save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int position = pos;
final String accno = holder.acc_txt.getText().toString();
final String tramnt = holder.transAmnt_edittxt.getText()
.toString();
String remarks = holder.remarks_edittxt.getText()
.toString();
final String spinner = holder.trans_spinner
.getSelectedItem().toString();
Log.e("accno:", "" + accno);
Log.e("name :", "" + tramnt);
Log.e("position:", "" + position);
Log.e("remark:", "" + remarks);
Log.e("spinner:", "" + spinner);
/****************** time and date **********************/
// ----------Time----------
Calendar c = Calendar.getInstance();
time = (c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE)
+ ":" + c.get(Calendar.SECOND));
Log.e("Current Time", " " + time);
// -----------Date---------
Date now = new Date();
Date alsoNow = Calendar.getInstance().getTime();
currntdate = new SimpleDateFormat("M-d-yyyy").format(now);
Log.e("Date ", " " + currntdate);
status = new String("y");
if (tramnt.equals("")) {
Toast.makeText(arg0.getContext(),
"enter Transaction amount", 5000).show();
Log.e("if cndition", " " + tramnt);
} else if (spinner.equals("type")) {
Toast.makeText(arg0.getContext(),
"enter Transaction type", 5000).show();
Log.e("if cndition", " " + tramnt);
}
else {
if (remarks.equals("")) {
remarks = "null";
}
/************ declaration for dbcall *********************/
AccountDBAdapter db = new AccountDBAdapter(context);
NewTransactionSheet ts = new NewTransactionSheet();
try {
db.open();
String accid = db.getAccID(accno);
String Maxcramnt = db.getMaxCrAmnt(accno);
db.close();
Mamount = Double.parseDouble(Maxcramnt);
Bamount = Double.parseDouble(tramnt);
actualamnt = Mamount - Bamount;
balamount = "" + actualamnt;
db.open();
db.close();
/* Log.e("c value", " " +actualamnt); */
Log.e("tramnt", " " + tramnt);
Log.e("if cndition out", " " + tramnt);
db.open();
db.update_MaxCrAmnt(balamount, accid);
db.close();
actualamnt = 0;
db.open();
String userId = "" + 2;
db.insertTransactionTable(accid.toString(),
currntdate.toString(), spinner.toString(),
tramnt.toString(), userId.toString(),
time.toString(), remarks.toString(),
status.toString());
db.close();
holder.save.setText("SAVED");
holder.save.setBackgroundColor(Color.DKGRAY);
// }
} catch (Exception e) {
Log.e("error", e.getMessage());
}
}
}
});
} catch (Exception c) {
Log.e("adapter error", "" + c.getMessage());
}
return cv;
}
}
Working on this for many days... need help.. Thanks in advance.