For a cookbook app I have a screen with a listview of recipe titles a user has saved. When the user clicks on one of the titles (listview item) it will open a new screen and display the full recipe.
I have stored all the recipe information in a sqlite database. So a row consists of a title, category, imagepath and recipe text. What I can't seem to work out is how I can use the recipe title to display the corresponding recipe text in the new activity.
So this is the onCreate of activity with the title ListView:
// Analyze cursor object: Is there data available on the cursor object?
if (cursor!=null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
// Get information from the cursor object
String imagePath;
String titles;
titles = cursor.getString(0);
imagePath = cursor.getString(1);
// Get the titles and image paths from the database
RecipeDataProvider recipeDataProvider = new RecipeDataProvider(convertSrcToBitmap(imagePath), titles);
// Add them to the listview
adapter.add(recipeDataProvider);
}
while (cursor.moveToNext());
}
}
// Set onclicklistener for the recipe titles.
viewTitlesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get the index of the title in the database
String index = ((TextView) findViewById(R.id.recipeTitle)).getText().toString();
// TODO get corresponding recipe text
Bundle dataBundle = new Bundle();
dataBundle.putString("id", index);
// Go to ShowRecipeActivity
Intent showIntent = new Intent(view.getContext(), ShowRecipeActivity.class);
showIntent.putExtras(dataBundle);
startActivity(showIntent);
}
});
}
This is the activity where I retrieve the data. At the moment it only shows the title of the recipe again:
// Get the recipe title from the previous activity
Bundle extras = getIntent().getExtras();
mRecipeTitle = extras.getString("id");
recipeTitleView.setText(mRecipeTitle);
// TODO: Get the corresponding recipe text from the database
And this is the cursor method in my DatabaseHelper:
public Cursor getRecipeInfo(SQLiteDatabase db){
// Create object of Cursor
Cursor cursor;
// Create some projections: the needed column names.
String[] projections = {RecipeContract.NewRecipeInfo.RECIPE_TITLE,
RecipeContract.NewRecipeInfo.RECIPE_PHOTO, RecipeContract.NewRecipeInfo.RECIPE_TEXT};
cursor = db.query(RecipeContract.NewRecipeInfo.TABLE_NAME, projections, null, null, null, null, null);
return cursor;
}
I have been stuck on this problem for a while now, I hope you can help me!
You should create a another activity to implement this. Once you click on the recipe list your onclick listener should take you to next activity
where you have to pass the recipe id.
#Override
public void onClick(View v) {
Intent intent= new Intent(this, SecondActivity.class);
intent.putExtra("recipeID", "0000002");
}
Related
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
}
}
Hello. There is a table from which data is displayed in ListView by position. Everything works great. But if there are spaces in the table, then this becomes a problem. How can I switch to the desired activity by _id in the table, and not by position?
I ask for help, I will be very grateful.
Thank you all very much!
Below is my code:
This is my code MainActivity.java
this.listView = findViewById(R.id.listView);
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
databaseAccess.open();
List<String> quotes = databaseAccess.getQuotes();
databaseAccess.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, quotes);
this.listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(id==0){
Intent myintent = new
Intent(view.getContext(),MosObl.class);
startActivityForResult(myintent,0);
}
if(id==1){
Intent myintent = new
Intent(view.getContext(),Arhangelsk.class);
startActivityForResult(myintent,1);
}
if(id==2){
Intent myintent = new
Intent(view.getContext(),Astrahan.class);
startActivityForResult(myintent,2);
}
This is my code DatabasesAccess.java
public List<String> getQuotes() {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM regiones where izbrannoe = 1", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return list;
}
With the position of the clicked item (which is the only thing you will be able to get directly), you can get the quote from your list "quotes", using :
final String desiredQuote = quotes.get(position);
Then, making a request to your database you'll be able to get the desired id. Something like:
final Cursor cursor = database.rawQuery("SELECT _id FROM regiones where izbrannoe = 1 AND quote=?",new String [] {desiredQuote});
Is that what you're looking for?
i have a listview that contains relative views on each list item that are populated by a database and contains two buttons.
when one of the buttons in the list view item is pressed i need to get the id of that row in the list view. in other words i am trying to find the same thing as the last argument in the onItemClick methos for the onItemClickListener(), which would return a click for the entire item. however i am just listening for the button in the listview item so i am unable to use onItemClickListener().
i have this method being called when i click the button
public void plusClick(View v)
{
//get the row the clicked button is in
RelativeLayout vwParentRow = (RelativeLayout)v.getParent();
//i need to get the id of this RelativeLayout item in the list view
TextView child = (TextView)vwParentRow.getChildAt(2);
Button btnChild = (Button)vwParentRow.getChildAt(1);
int c = Color.CYAN;
vwParentRow.setBackgroundColor(c);
vwParentRow.refreshDrawableState();
}
it need to find the id of the relative layout which i can pass ass arg for
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
to create a new cursor contiain the data in this listview item
try this code:
private OnItemClickListener itemClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int position,
long id) {
// write your logic here
// position starts from 0
// id starts from 1
}
};
when you set onclicklistener for your button you can set tag for it(tag can be id of row), and then when you click on button get it's tag. (of course if you use custom adapter)
You need some kind of adapter, in getView method you have to declare your event
There is an example:
holder.hMention.setOnClickListener(new VerTweet(mention));
and...
public class VerTweet implements View.OnClickListener
{
Mention mention;
public VerTweet ( Mention mention) {
this.mention = mention;
}
public void onClick( View view ){
Bundle bundle = new Bundle();
//Le ponemos la variable parametro con el contenido test
bundle.putInt("idTrack", mention.getIdTrack());
bundle.putString("Gifo", mention.getGifo());
bundle.putString("From", mention.getFromUser());
bundle.putString("Date", mention.getDateMentions());
bundle.putString("Text", mention.getText());
bundle.putLong("Status", mention.getLastId());
Intent i = new Intent(getContext(), Tweet.class);
i.putExtras(bundle);
getContext().startActivity(i);
}
}
https://github.com/m-alcu/SkoltiAlert/blob/master/src/com/alcubier/skoltialert/mentions/GDMentionsList.java
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.
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