I was trying to display my data dynamically in a listview. I first insert data into db then displaying them in listview. I don't understand why but I created db and listview, it doesn't show data when I try to display it.
I'm getting data from EditText fields but I insert and display the data in another activity. I first thought I coludn't get the data from first activity, but I'm sure that I wrote the right code.
The field for the data in listview always empty. I should create a new entry when I press a "Add" button. I can see that it creates a new row in the list with a new id but the rest is empty.
Why I don't see data there? This is how I get data and put inside db and list:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
String name = "";
String email = "";
String phone = "";
String address = "";
Bundle extras = getIntent().getExtras();
if (extras != null) {
name = extras.getString("name");
email = extras.getString("email");
phone = extras.getString("phone");
address = extras.getString("address");
}
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.COLUMN_NAME, SQLiteAdapter.COLUMN_EMAIL,SQLiteAdapter.COLUMN_PHONE, SQLiteAdapter.COLUMN_ADDRESS};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2,R.id.text3, R.id.text4};
cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
mySQLiteAdapter.insert(name,email,phone,address);
updateList();
}
This is my main activity
Button next = (Button) findViewById(R.id.add);
EditText nametext = (EditText) this.findViewById(R.id.NameText);
final String nt = nametext.getText().toString();
EditText emailtext = (EditText) this.findViewById(R.id.MailText);
final String et = emailtext.getText().toString();
EditText phonetext = (EditText) this.findViewById(R.id.PhoneText);
final String pt = phonetext.getText().toString();
EditText addresstext = (EditText) this.findViewById(R.id.AddressText);
final String at = addresstext.getText().toString();
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(getApplicationContext(), Activity2.class);
myIntent.putExtra("name",nt);
myIntent.putExtra("email",et);
myIntent.putExtra("phone",pt);
myIntent.putExtra("address",at);
startActivity(myIntent);
}
});
Here is my queueAll function:
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, COLUMN_NAME,
COLUMN_EMAIL,COLUMN_PHONE,COLUMN_ADDRESS};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
Related
I created an app that shows a list of places and i created a search dialog wherein the user will type in edittext so he/she will find the desired place. First, search is working when its only place and I try to add spinner with values which are the region of the places and I got problem on the line which i will post below.
GetSearchPlace = dbhelper.getPlaceSearch(placeLocationEditText.getText().toString(),dbhelper.getPlaceSearch(placeRegion.getSelectedItem().toString()));
It says getPlaceSearch (String, string) in DatabaseHelper cannot be applied to (String)
This is my database helper
public List<PlaceModel> getPlaceSearch(String location, String region) {
List<PlaceModel> search = new ArrayList<PlaceModel>();
String selectQuery = "SELECT * FROM listing_place where province_name like '" + location + "' and region = '"+region+"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
PlaceModel pm = new PlaceModel();
pm.setlisting_title(cursor.getString(cursor.getColumnIndex(KEY_PLACE)));
search.add(pm);
}
while (cursor.moveToNext());
}
cursor.close();
return search;
}
This is my main activity
final Spinner placeRegion = (Spinner) dialog.findViewById(R.id.spinnerregion);
ArrayAdapter<String> RegionAdapter = new ArrayAdapter<String>(MainActivity.this,R.layout.spinner_layout, db.getAllRegion());
RegionAdapter.setDropDownViewResource(R.layout.spinner_layout);
placeRegion.setAdapter(RegionAdapter);
placeLocationEditText = (EditText)dialog.findViewById(R.id.placelocation);
Button button = (Button) dialog.findViewById(R.id.btnplacesearch);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
PlaceListView = findViewById(R.id.placelayout);
ViewGroup parent = (ViewGroup) PlaceListView.getParent();
parent.removeView(PlaceListView);
PlaceSearchView = getLayoutInflater().inflate(R.layout.searchresult_place, parent, false);
parent.addView(PlaceSearchView);
GetSearchPlace = dbhelper.getPlaceSearch(placeLocationEditText.getText().toString(),dbhelper.getPlaceSearch(placeRegion.getSelectedItem().toString()));
lv2 = (ListView) findViewById(R.id.searchplace_list);
lv2.setAdapter(new ViewAdapterSearchPlace());
ok replace your code to below..
GetSearchPlace = dbhelper.getPlaceSearch(placeLocationEditText.getText().toString(),placeRegion.getSelectedItem().toString());
I have to display SMS messages from a given number in ListView.
I have displayed messages from a number that i described in program.
Now i have to get number using EditText and display messages from that number.
My MainActivity.java is
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.listView);
List<String> msgList=getSMS();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,msgList);
listView.setAdapter(adapter);
}
public List<String> getSMS(){
List<String>sms=new ArrayList<String>();
final String SMS_URI_INBOX="content://sms/inbox";
try {
Uri uri=Uri.parse(SMS_URI_INBOX);
String[] projection=new String[]{"_id","address","person","body","date","type"};
Cursor cursor=getContentResolver().query(uri,projection,"address='+918870346164'",null,null);
if (cursor.moveToFirst()){
int index_Address = cursor.getColumnIndex("address");
int index_Person = cursor.getColumnIndex("person");
int index_Body = cursor.getColumnIndex("body");
int index_Date = cursor.getColumnIndex("date");
int index_Type = cursor.getColumnIndex("type");
do {
String strAddress = cursor.getString(index_Address);
int intPerson = cursor.getInt(index_Person);
String strBody = cursor.getString(index_Body);
String longDate = cursor.getString(index_Date);
int intType = cursor.getInt(index_Type);
sms.add("\n"+strBody+"\n");
}while (cursor.moveToNext());
if (!cursor.isClosed()){
cursor.close();
cursor=null;
}
}
}catch (SQLiteException e){
Log.d("SQLiteException",e.getMessage());
}
return sms;
}
In this line i have defined the number i want to use
Cursor cursor=getContentResolver().query(uri,projection,"address='+918870346164'",null,null);
Here i have to get the number from user via TextView.
Please help
i think you need to get track with Android Training
But any way EditText getText()
EditText et = (EditText) findViewById(R.id.edit_text_id);
String address="address='"+et.getText().toString()+"'";
cursor=getContentResolver().query(uri,projection,address,null,null);
My current application has a Listview which pulls and displays data from a sqlite DB. Data in the first column of the DB is displayed in the listview and when clicked, an activity starts showing the rest of the column associated with the first column. When the data is edited, the DB updates but the listview does not show the updates unless the application is restarted. I am trying to implement startActivityForResult() in my onResume method but am unsuccessful. I am trying to refresh my listview after the DB has been updated. How can I accomplish this.
ListView Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_listview);
loginList = (ListView)
findViewById(R.id.loginlist);
loginList.setOnItemClickListener(this);
webLogin = (Button)
findViewById(R.id.button3);
webLogin.setOnClickListener(this);
loginArrayList = new ArrayList<LoginDetails>();
loginListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
loginList.setAdapter(loginListAdapter);
}
#Override
public void onClick (View v) {
Intent webLoginIntent = new Intent (this, LoginPlusActivity.class);
startActivity(webLoginIntent);
}
public List<String> populateList (){
List<String> webNameList = new ArrayList<String>();
dataStore openHelperClass = new dataStore (this);
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
Cursor cursor = sqliteDatabase.query(dataStore.TABLE_NAME_INFOTABLE, null, null, null, null, null, dataStore.COLUMN_NAME_SITE, null);
startManagingCursor(cursor);
while (cursor.moveToNext()){
String sName = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_SITE));
String wUrl = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_ADDRESS));
String uName = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_USERNAME));
String pWord = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_PASSWORD));
String lNotes = cursor.getString(cursor.getColumnIndex(dataStore.COLUMN_NAME_NOTES));
LoginDetails lpDetails = new LoginDetails();
lpDetails.setsName(sName);
lpDetails.setwUrl(wUrl);
lpDetails.setuName(uName);
lpDetails.setpWord(pWord);
lpDetails.setlNotes(lNotes);
loginArrayList.add(lpDetails);
webNameList.add(sName);
}
sqliteDatabase.close();
return webNameList;
}
#Override
protected void onResume() {
super.onResume();
Intent i = new Intent(LoginList.this, UpdateDeleteLoginList.class);
LoginList.this.startActivityForResult(i, 1);
loginList.setAdapter(loginListAdapter);
loginListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
loginList.setAdapter(loginListAdapter);
}
update Activity:
#Override
public void onClick(View v){
loginSitetext = sName.getText().toString();
loginAddresstext = wUrl.getText().toString();
loginUsertext = uName.getText().toString();
loginpassWordtext = pWord.getText().toString();
loginNotestext = lNotes.getText().toString();
LoginDetails loginDetails = new LoginDetails();
loginDetails.setsName(bundledWebSite);
loginDetails.setwUrl(bundledWebAddress);
loginDetails.setuName(bundledUserName);
loginDetails.setpWord(bundledPassWord);
loginDetails.setlNotes(bundledNotes);
if(v.getId()==R.id.rucBttn){
finish();
}else if(v.getId()==R.id.ruuBttn){
updateLoginDetails(loginDetails);
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
}else if(v.getId()==R.id.rudBttn){
deleteLoginDetails(loginDetails);
}
}
private void updateLoginDetails(LoginDetails loginDetails){
dataStore androidOpenDbHelper = new dataStore(this);
SQLiteDatabase sqliteDatabase = androidOpenDbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(dataStore.COLUMN_NAME_SITE, loginSitetext);
contentValues.put(dataStore.COLUMN_NAME_ADDRESS, loginAddresstext);
contentValues.put(dataStore.COLUMN_NAME_USERNAME, loginUsertext);
contentValues.put(dataStore.COLUMN_NAME_PASSWORD, loginpassWordtext);
contentValues.put(dataStore.COLUMN_NAME_NOTES, loginNotestext);
String[] whereClauseArgument = new String[1];
whereClauseArgument[0] = loginDetails.getsName();
System.out.println("whereClauseArgument[0] is :" + whereClauseArgument[0]);
sqliteDatabase.update(dataStore.TABLE_NAME_INFOTABLE, contentValues, dataStore.COLUMN_NAME_SITE+"=?", whereClauseArgument);
sqliteDatabase.close();
finish();
You can refresh the listview by calling notifyDataSetUpdated on the adapter. That forces the entire listview to refresh, and getView will be called on all views refreshing it.
The problem you're asking about has a standard solution, that is (unfortunately) more complex than a few lines of code. It is accomplished by a combination of Content Provider, Data Loader and Cursor Adapter.
I've put a little demo on GitHub that has a skeleton containing all the components and can be modified to accomplish what you need. It also handles one-pane / two-pane layouts on tablets (and newer phones as well).
Content provider is the module that serves as an interface to your database table and notifies your ListView about the changes, thus taking care of immediate refreshing of the list. Just grep for 'getContentResolver().notifyChange()' calls, these take care of refreshing your list. As long as you use Content Provider for all access to your data (CRUD - query,insert,delete,update,...), all your actions will be immediately reflected in the ListView.
There is a lot of info about this by Wolfram Rittmeyer, Lars Vogel, Alex Lockwood, ... if you want to get educated about the problem.
Good Luck
I am making an application to Store textfield values to database.After entering values when I press the button to submit it, it just hanged and give no response.
my onCreate code is given below:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final DBAdapter db = new DBAdapter(this);
//---add 2 titles---
db.open();
final long d_id ;
final EditText input1 = (EditText) findViewById(R.id.isbn);
final String isbn = input1.getText().toString();
final EditText input2 = (EditText) findViewById(R.id.titleText);
final String tText = input2.getText().toString();
final EditText input3 = (EditText) findViewById(R.id.publisherText);
final String pText = input3.getText().toString();
this.btn = (Button)this.findViewById(R.id.button1);
this.btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
db.insertTitle(isbn, tText, pText);
}
});
db.close();
}
}
isbn,titleText and publisherText are my id for Textfield.
insertTitle is function to insert the values.
Whats wrong with my code?
thanks.
You are reading the values of your text fields as the app is being created, not when the button is pushed. You will always enter the initial values of your EditTexts with your current code. Try this:
db.insertTitle(input1.getText().toString(), input2.getText().toString(), input3.getText().toString());
You will have to move where you close your database, otherwise you will get an error for attempting to access a closed database. Try putting it in onPause() or onDestroy().
If this isn't the solution please post your logcat errors so we don't have to guess what is happening.
try this
this.btn = (Button)this.findViewById(R.id.button1);
this.btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
final EditText input1 = (EditText) findViewById(R.id.isbn);
final String isbn = input1.getText().toString();
final EditText input2 = (EditText) findViewById(R.id.titleText);
final String tText = input2.getText().toString();
final EditText input3 = (EditText) findViewById(R.id.publisherText);
final String pText = input3.getText().toString();
db.insertTitle(isbn, tText, pText);
}
});
I think your problem is open() and close() they are in onclick method or about your insertTitle() method. Check your values and types.
ContentValues cv = new ContentValues();
cv.put(KEY_WORK_OUT, workout);
cv.put(KEY_NAME, name);
cv.put(KEY_REP,rep);
cv.put(KEY_WEIGHT, weight);
ourDataBase.insert(DATABASE_TABLE, null, cv);
I have a page with a number edit texts, i want to populate these with columns of a raw with the row id equaling a textview value... this is what i have so far in the edit text page.
public class CBCreate extends Activity {
EditText EditRecipe,EditRecipe2,EditRecipe3;
Button Rname;
CBDataBaseHelper entry;
TextView RowIDText;
Cursor c;
String name;
String category;
String description;
//final String SQL_STATEMENT = "SELECT Recipe_Name, Recipe_Category, Recipe_Description FROM RecipeData WHERE _id = " + RowIDText ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create); // sets the content view to main
EditRecipe = (EditText) findViewById(R.id.editText1);
EditRecipe2 = (EditText) findViewById(R.id.editText2);
EditRecipe3 = (EditText) findViewById(R.id.editText3);
RowIDText = (TextView) findViewById(R.id.RowID);
Rname = (Button) findViewById(R.id.RecipeName);
String RowID;
try{
Bundle extras = getIntent().getExtras();
if (extras != null) {
RowID = extras.getString("SELECTED");
RowIDText.setText(RowID);
}
if (RowIDText != null){
entry = new CBDataBaseHelper(this);
String s = RowIDText.getText().toString();
int ID = Integer.parseInt(s);
entry.open();
Cursor cursor = entry.fetchRow(ID);
if (cursor.moveToFirst()){ // data?
name = cursor.getString(cursor.getColumnIndex(CBDataBaseHelper.KEY_NAME));
}
entry.close();
EditRecipe.setText(name);
EditRecipe2.setText(category);
EditRecipe3.setText(description);
}
}catch (Exception e){
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("darn");
TextView tv = new TextView(this);
tv.setText(name);
d.setContentView(tv);
d.show();
}
}
public void doIt(View view) {
String Name = EditRecipe.getText().toString();
String description = EditRecipe.getText().toString();
String category = EditRecipe.getText().toString();
entry = new CBDataBaseHelper(CBCreate.this);
entry.open();
entry.createEntry(Name, description, category);
entry.close();
EditRecipe.setText("");
EditRecipe2.setText("");
EditRecipe3.setText("");
}
public void goBack(View view){
Intent myIntent = new Intent(this, CBFilter.class);
startActivity(myIntent);
}
}
and then this is what i have within the database helper class... i think i want to call this method?
public Cursor fetchRow(long rowId) throws SQLException {
Cursor mCursor = mydatabase.query(true, DATABASE_TABLE, new String[] { KEY_ROWID,
KEY_CATEGORY, KEY_DESCRIPTION }, KEY_ROWID + "="
+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
I would use mydatabase.rawquery(QUERY) instead of the cursors query method. Its easier for SQL developers I think. Anyways, once you have your values in the cursor, you can do this
EditRecipe.setText(cursor.getString(0));
EditRecipe2.setText(cursor.getString(1));
Where 0 represents the first column in your returned table. You would put that code after your mCursor.moveToFirst();