setContentView doesn't allow search to work - java

I have been tryng to get my search function working ever since adopting TabHosts and I have figured out that in my onCreate method for my Search class that when setContentView(R.layout.main); it causes the following error
03-30 09:19:53.301: E/AndroidRuntime(728): android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord#4053c270 is not valid; is your activity running?
When I comment it out though the search dialog pops up when you click on the hardware search button and I can type a value and press search but then I get the next stumbling block
03-30 09:23:37.061: D/PhoneWindow(776): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView#4053ff38 has no id.
Below is my code as it is at the moment for my Search class
public class Search extends ListActivity {
private TextView mTextView;
//protected ListAdapter adapter;
private DxDbAdapter mDbHelper;
DxSimpleCursorAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
//mTextView = (TextView) findViewById(R.id.text1);
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doMySearch(query);
}
}
public void doMySearch(String query_results) {
//SQLiteDatabase db = (new DatabaseHelper(this)).getWritableDatabase();
mDbHelper = new DxDbAdapter(this);
mDbHelper.open();
String[] columns = new String[] {"diagnosis", "diagcode"};
int[] to = new int[] {R.id.diagnosis, R.id.code};
// Add "No Results Found" message
Cursor cursor = mDbHelper.search(query_results.trim());
//Cursor cursor = db.rawQuery("Select _id, diagnosis, diagcode From DiagLookup Where diagnosis Like ? order by diagnosis asc", new String[]{"%"+query_results.trim()+"%"});
/* if (cursor == null) {
mTextView.setText(getString(R.string.no_results, new Object[] {query_results}));
}
else {*/
adapter = new DxSimpleCursorAdapter(this,R.layout.list_detail,cursor,columns,to);
setListAdapter(adapter);
// }
}
public void onListItemClick(ListView parent, View view, int position, long id) {
SQLiteDatabase db = (new DatabaseHelper(this)).getWritableDatabase();
Cursor c = (Cursor) getListAdapter().getItem(position);
String arg = c.getString(c.getColumnIndex("_id"));
Cursor cursor = db.rawQuery("Select category, subcategory From DiagLookup Where _id = ?", new String[]{""+arg});
cursor.moveToFirst();
Context context = getApplicationContext();
CharSequence text = "Category: " + cursor.getString(cursor.getColumnIndex("category")) + "\nSubcategory: " + cursor.getString(cursor.getColumnIndex("subcategory"));
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
Furthermore I created a custom SimpleCursorAdapter so I can do some actions to an imageview. When I originally had entered adapter = new SimpleCursorAdapter(this,R.layout.list_detail,cursor,columns,to); entering a search term and pressing on the search button had populated the listview but my imageview was not functioning so when I just changed the code to adapter = new DxSimpleCursorAdapter(this,R.layout.list_detail,cursor,columns,to); and added on the top DxSimpleCursorAdapter adapter; it no longer worked and caused the couldn't save focus error.
I am using TabActivity and ActivityGroup to create tabs along the top of my app and I think my context is messed up which is causing the focus to be lost...I am not sure though.
Anyone with some guidance on how I can go about solving these issues?
Thanks in advance.

If you are using TabActivity, why use the ListActivity again? If you want to use the ListView inside the Tabs, you can simply define it in the layout xml file.
If you want to use the Tabs inside an activity, then try this out, Android: TabHost without TabActivity
Switch to ViewPager instead of TabActivity Set default page for ViewPager in Android

Related

How to get data from onitemclick and display it on another activity (Android Dev)?

I am very new to Android and Java dev, sorry in advance.
I am making a simple music player app.
Right now my app gets storage data from the phone (it finds mp3 files) and displays both the title and artist in a ListView.
When a song item in the list is clicked it changes screens to the PlaySongActivity.Java via an intent. On the Activity_Play_Song.xml I set up two text views. I want to make it so that whenever an item is clicked the title and artist is transferred into the two text views in the Activity_Play_Song.xml texts.
How can I do this?
Here is my code:
MainActivity
ArrayList<String> arrayList;
ListView listView;
ArrayAdapter<String> adapter;
public void getMusic(){
ContentResolver contentResolver = getContentResolver();
Uri songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor songCursor = contentResolver.query(songUri, null, null, null, null);
if(songCursor != null && songCursor.moveToFirst()){
int songTitle = songCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int songArtist = songCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
do{
String currentTitle = songCursor.getString((songTitle));
String currentArtist = songCursor.getString((songArtist));
arrayList.add(currentTitle+ "\n" + currentArtist);
} while (songCursor.moveToNext());
}
}
public void doStuff(){
listView = (ListView) findViewById(R.id.listView);
arrayList = new ArrayList<>();
getMusic();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, PlaySongActivity.class);
startActivity(i);
}
});
}
Currently, the PlaySongsActivity only contains the default onCreate code and the activity_play_songs.xml has two TextViews where I want the title and artist to go.
Anjali bhardwaj.
To send information from one activity to another using intent do this:
Intent i = new Intent(MainActivity.this, PlaySongActivity.class);
//Here we store the title and author strings using .putExtra("Name", Value)
i.putExtra("ArtistString", currentArtist);
i.putExtra("TitleString", currentTitle);
startActivity(i);
Now it is stored and will be sent over to the activity that you are starting.
To get the information in the receiving activity
/*gets the information from the intent that was passed and casts it to a Intent object*/
Intent intent = getIntent();
//gets the strings from the intent
String artist = intent.getStringExtra("ArtistString");
String title = intent.getStringExtra("TitleString");
Now you can do whatever you want with this string. Hope this helps!
--UPDATE--
Example
public class SomeClass{
//declare them outside of the method so that they can be accessed by any method.
//I just set them to nothing so that you dont get NULLPOINTEREXCEPTIONs
String currentTitle = "nothing";
String currentArtist = "nothing";
public void getMusic(){
//set the value of the strings in here
}
public void doStuff(){
//Access them here
}
}

How can I open A Custom ListView Item in A separate Activity?

I have looked through other Posts as much as I can, and though this may be a simple problem, for the life of me I can't figure out how to make this work. I have a Database of Customers, including their names, address, etc.
I would Like to be able to select one of the customers from my custom ListView, and View all of their Database information in A separate Activity. Currently, I cant make it give me anything past the first record.
Any advice would be very helpful if you can see what I am doing wrong.
I am fairly new to Java so Please take it easy on me :P My best guess right now is that I need to create a new cursor but I'm a bit lost.
Code attached below.
Database Viewer.java
public class DatabaseViewer extends AppCompatActivity{
TextView DisplayName;
TextView DisplayID;
TextView DisplayMarks;
TextView DisplayAddress;
DatabaseHelper mydb = new DatabaseHelper(this);
ListView customerlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database_viewer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
customerlist = (ListView) findViewById(R.id.ListViewCustomers);
populateDatabase();
customerlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
DisplayID = (TextView) findViewById(R.id.TVCUSTOMERNAME);
DisplayMarks = (TextView) findViewById(R.id.TVADDRESS);
DisplayName = (TextView) findViewById(R.id.TVID);
DisplayAddress = (TextView) findViewById(R.id.TVMARKS);
// NEED TO MAKE A CURSOR THAT GETS ALL ROWS NOT COLUMNS LIKE BELOW.
int c1 = mydb.getallrows().getPosition();
// 35 ROWS 4 COLUMNS.
String item = String.valueOf(parent.getItemAtPosition(i));
Intent clientViewIntent = new Intent(DatabaseViewer.this, ClientViewer.class);
clientViewIntent.putExtra("Client ID", c1);
startActivity(clientViewIntent);
}
});
}
private void populateDatabase(){
Cursor c = mydb.getallrows();
customerlist = (ListView) findViewById(R.id.ListViewCustomers);
String[] fromfieldnames = new String[] {DatabaseHelper.COL_1, DatabaseHelper.COL_2, DatabaseHelper.COL_3, DatabaseHelper.COL_4};
int[] tofieldnames = new int[] {R.id.TVCUSTOMERNAME, R.id.TVADDRESS, R.id.TVMARKS, R.id.TVID};
SimpleCursorAdapter adapter;
adapter = new SimpleCursorAdapter(getBaseContext(), R.layout.custom_db_viewer_row, c, fromfieldnames, tofieldnames, 0);
customerlist.setAdapter(adapter);
}
public void OnClientLongPress(){
// Function to Open up Client Information in a new activity.
// Step 1, Use data from Client to pull up Full Client Records.
// Step 2, Send Data in Intent Extras.
Intent clientVIewIntent = new Intent(DatabaseViewer.this, ClientViewer.class);
clientVIewIntent.putExtra("Client ID", customerlist.getSelectedItemId());
startActivity(clientVIewIntent);
}
ClientViewer.java
public class ClientViewer extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_viewer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.inflateMenu(R.menu.menu_invoice_creator);
Bundle NameIntentData = getIntent().getExtras();
if (NameIntentData==null){
return;
}
int IntentDataID = NameIntentData.getInt("Client ID");
String IntentDataName = NameIntentData.getString("Client Name");
String IntentDataAddress = NameIntentData.getString("Client Address");
final TextView IDBar = (TextView) findViewById(R.id.ClientViewerIDTV);
final TextView Namebar = (TextView) findViewById(R.id.ClientViewerNameTV);
final TextView AddressBar = (TextView) findViewById(R.id.ClientViewerAddressTV);
Namebar.setText(Integer.toString(IntentDataID));
IDBar.setText(IntentDataName);
AddressBar.setText(IntentDataAddress);
}
}
Thanks so much for your time and effort guys. Really cant wait to hear back from you.
TextView textview =((TextView)view.findViewById(R.id.tvInVisitorName)).getText().toString();
Use this on onClick and get your text view data like this.
Get the ID of client onClick which is same and unique as stored in DB
Then, pass it to another activity
Pass id parameter and get all the data based on that ID and display..don't pass all the data via intent just pass one key and get all data and display
Hope this will help you
Thanks!!!
SOLVED, Largely in thanks to Anamica!
The code
String a = Long.toString(l);
Intent clientViewIntent = new Intent(DatabaseViewer.this,
ClientViewer.class);
clientViewIntent.putExtra("Client ID", a);
startActivity(clientViewIntent);
Got me where I needed to be.(Shows the Id of Item) Thanks again Guys!

Context menu shows correct data but listview doesn't

I have a really strange problem that I've been trying to solve the last hours but I can't find whats wrong. I have a SQLite database containing names and a small amount of text. A listview who gets populated with the names from it, when i click on the listview I see the text that is connected to the names. But I also have a "Add to favorite" and when i add something to my favorite list it displays on another activity. The displayed info is correct in the new/favorite listview (Names, title and a image) but when i click on it its wrong data that is displayed.
I have 10 rows in my original listview and in my "favorite" listview is it the same order as in the first one. If I add e.g a movie..Casablanca that is on position 7 in my original list,it will place it self on the first position in my new listview (position 0) and it shows correct actors, covers and author. BUT when i click it to see more info(starts new activity). It only shows the info from the the original listview with the info from the movie on position 0.
But if i click on my context menu to check it. It displays all the correct data I want to see. It so strange and I hope there is someone that know what the problem can be? I've tried a lot of different combos and solutions with arrays and strings/stringbuilder and so on. This is the last code i wrote before i came here.
public class Favorites extends ActionBarActivity {
DatabaseHelper dbHelper;
ListView favoritesListView;
Cursor myCursor;
String[] myStringArray = new String[3];
ListViewCursorAdapter myFavsAdapter;
String openBookCmeny = "Öppna boken";
String rmvFavsCmeny = "Ta bort från dina favoriter";
String webSiteCmeny = "Klicka här för mer information på bokens hemsida";
String showWebSiteCmeny;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
dbHelper = DatabaseHelper.getInstance(this);
myCursor = dbHelper.visaFavoriter();
dbHelper.getWritableDatabase();
myFavsAdapter = new ListViewCursorAdapter(this, myCursor);
favoritesListView = (ListView)findViewById(R.id.favoritesListView);
favoritesListView.setAdapter(myFavsAdapter);
registerForContextMenu(favoritesListView);
favoritesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor c = (Cursor)myFavsAdapter.getItem(view.getId());
myStringArray[1]= c.getString(4);
Intent i = new Intent(Favorites.this, VisaBoken.class);
i.putExtra(null, myStringArray);
startActivity(i);
}
});
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
Cursor c = ((Cursor) myFavsAdapter.getItem(info.position));
String cTitle = c.getString(2);
menu.setHeaderTitle(cTitle);
menu.add(0, v.getId(), 0, openBookCmeny);
menu.add(0, v.getId(), 0, rmvFavsCmeny);
menu.add(0, v.getId(), 0, webSiteCmeny);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
Cursor c = ((Cursor) myFavsAdapter.getItem(info.position));
myStringArray[0] = c.getString(0);
myStringArray[1] = c.getString(4);
showWebSiteCmeny = c.getString(6);
if (item.getTitle() == openBookCmeny){
Intent i = new Intent(Favorites.this, VisaBoken.class);
i.putExtra(null, myStringArray);
startActivity(i);
}
else if (item.getTitle() == rmvFavsCmeny){
dbHelper.removeOneFavorite(myStringArray[0]);
recreate();
}
else if (item.getTitle() == webSiteCmeny){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(showWebSiteCmeny));
startActivity(browserIntent);
}
return super.onContextItemSelected(item);
}
The class that gets the intents and info to display it.
public class VisaBoken extends ActionBarActivity implements AdapterView.OnItemClickListener {
ActionBarDrawerToggle myDrawerToggle;
DrawerLayout myDrawerLayout;
ListView myDrawerListView;
ArrayList<DrawerMenuName> myDrawerMenuName = new ArrayList<>();
DatabaseHelper dbHelper;
public static final String COL_ID = "_id";
public static String Tag = "checkIDfromDB";
TextView visaBokenTV;
String[] myStringArray = new String[2];
String[] myStringArray2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visa_boken);
visaBokenTV = (TextView)findViewById(R.id.visaBokenTV);
Bundle extras = getIntent().getExtras();
myStringArray = extras.getStringArray(null);
visaBokenTV.setText(myStringArray[1]);
myDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
dbHelper = DatabaseHelper.getInstance(this);
dbHelper.getWritableDatabase();
Sorry I am not fully understanding your explanation of the problem. However I see a code that is suspect.
Suggestion, change code in public void onItemClick from:
Cursor c = (Cursor)myFavsAdapter.getItem(view.getId());
TO:
Cursor c = (Cursor)myFavsAdapter.getItem( position );
Normally, to use getItem(), you pass the position in the ListView, starting from value 0 is the top. You cannot use view.getId() unless there is an ID set to the various View objects but I don't think you did that, sounds too tricky. Perhaps you should post the Adapter (myFavsAdapter) code.
Let's try that first until I can see some other issue.

Sectioning Listview

can somebody give me an example on how to section the listview?
im using SimpleCursorAdapter to display the datas in the listview..
my code is like this.
private WordDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
this are the codes on the onCreate() method.
dbHelper = new WordDbAdapter(this);
dbHelper.open();
//Clean all data
dbHelper.deleteAllWords();
//Add some data
dbHelper.insertSomeWords();
//Generate ListView from SQLite Database
displayListView();
and this is the code outside the onCreate method.
#SuppressWarnings("deprecation")
private void displayListView() {
Cursor cursor = dbHelper.fetchAllWords();
// The desired columns to be bound
String[] columns = new String[] {
WordDbAdapter.KEY_WORD,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.Word,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.word_info,
cursor,
columns,
to
);
ListView listView = (ListView) findViewById(R.id.Diclist);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the word name from this row in the database.
String wordSelected =
cursor.getString(cursor.getColumnIndexOrThrow("word"));
String wordSyllabication =
cursor.getString(cursor.getColumnIndexOrThrow("syllabication"));
String wordPartofSpeech =
cursor.getString(cursor.getColumnIndexOrThrow("partofspeech"));
String wordMeaning =
cursor.getString(cursor.getColumnIndexOrThrow("meaning"));
EditText TextDic = (EditText) findViewById(R.id.TextDic);
TextDic.setText(wordSelected);
Toast.makeText(getApplicationContext(),
wordSyllabication + "\n" + wordPartofSpeech + "\n" + wordMeaning , Toast.LENGTH_SHORT).show();
}
});
I found a good example of sectioned listview on this blog.It is done by using ArrayAdapter but you can see the concept and try to manipulate the code accordingly to make it work with SimpleCursorAdapter.
I hope it will be helpful !!
This is tricky with a cursor adapter as you have to remap your positions. I've made a library called SectionCursorAdapter to help with this. It's really easy to implement. To get this to work with your data, when you extend the SectionCursorAdapter just do the following.
#Override
protected Object getSectionFromCursor(Cursor cursor) {
int columnIndex = cursor.getColumnIndex("word");
String word = cursor.getString(columnIndex);
return word.toUpperCase().substring(0, 1);
}
Right now you don't have to worry about recycling your views but you do have to bind the data yourself. If this library gets popular enough I will add a SimpleSectionCursorAdapter.

Android - Displaying all SQLite database entries in a ListView

What I am trying to do is display the contents of the database in a ListView. The layout contains a ListView which I have used and implemented but I can't seem to get them working together (or even the cursor), could someone give me a hand and an explanation of why my cursor implementation doesn't work?
I have a method to return the database entries as a Cursor:
public Cursor getAllRecords() {
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TEXT}, null, null, null, null, null);
}
I have the class where I want to insert and display the database entries:
Button add;
EditText tM;
ListView generalList;
DBAdapter dba = new DBAdapter(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_general);
add = (Button) findViewById(R.id.button1);
tM = (EditText) findViewById(R.id.editText1);
generalList = (ListView) findViewById(R.id.generalList);
Cursor c = dba.getAllRecords();
c.moveToFirst();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.id.generalList, c, new String[] {dba.KEY_TEXT}, new int[] {R.id.generalList}, 0);
// This doesn't seem to work for me, I don't know how to fix it
// or how to then get it working with the ListView
generalList.setAdapter(adapter);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
insertIntoDatabase();
}
});
}
public void insertIntoDatabase() {
dba.open();
dba.insertRecord(textMessage.getText().toString());
Toast.makeText(this, "Added:\n" + tM.getText().toString(), Toast.LENGTH_LONG).show();
dba.close();
}
When using a ListView with a CursorAdapter, the Cursor returned from the column must contain a column with the name _id uniquely identifying each row. I'm guessing that the one column you are fetching (dba.KEY_TEXT) is not named "_id". You can either add a column to your table named _id or when you perform your SELECT have the database return the name as _id
i.e.
SELECT col_name as _id FROM my_table;
OR
SELECT col_name _id FROM my_table;
if the list contains only 1 TextView, you can use android.R.layout.simple_list_item_1 instead of your R.id.generalList.
and change the new int[] {R.id.generalList} to new int[] {android.R.id.text1}
like :
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, new String[] {dba.KEY_TEXT}, new int[] {android.R.id.text1}, 0);
on the arguments that receives the simplecursoradapter, remember the layout it receives is the layout for the actual item not the listview. so remove the R.id.generalList from there, cause that is the id that identified the listview not a full layout. so replace that with a layout that contains a textview. now, on the int array goes the id of the textview that will show the text you want and on the string array pass on the names of the fields in the record read from the database. do as mentioned by aprian and know that you can customize items as much as you need.

Categories