How to get the real data text, with already substring text? - java

I'm doing create an Catalogue Movie app. I have a ListView which contains an ImageView, title, description, and release date.
In the ListView, I take a substring of the description, because it's too long if showed in a ListView, and now I want to get the real description, in the DetailActivity (setOnItemClickListener).
This is my code:
try {
String title = object.getString("title");
String description = object.getString("overview");
double movieRatet = object.getDouble("vote_average");
String movieRate = new DecimalFormat("#.#").format(movieRatet);
String releaseDate = object.getString("release_date");
String posterUrl = object.getString("poster_path");
posterUrl = POSTER_BASE_URL + "w185" + posterUrl;
description = description.length() > 64 ? description.substring(0,64)+"...":description;
Log.d("movie poster", posterUrl);
Log.d("movie title ", title);
Log.d("movie description ", description);
Log.d("movie release ", releaseDate);
this.title = title;
this.description = description;
this.rate = releaseDate;
this.imgurl = posterUrl;
}catch (Exception e){
e.printStackTrace();
}
This is my OnItemClickListener:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Clicked"+position,Toast.LENGTH_LONG).show();
RelativeLayout listItem = (RelativeLayout) view.findViewById(R.id.rl_item);
TextView clickedItemView = (TextView) listItem.findViewById(R.id.tv_judul);
TextView clickedItemView2 = (TextView) listItem.findViewById(R.id.tv_deskripsi);
TextView clickedItemView3 = (TextView) listItem.findViewById(R.id.tv_rate);
String title = clickedItemView.getText().toString();
String desk = clickedItemView2.getText().toString();
String rate = clickedItemView3.getText().toString();
Intent i = new Intent(getApplicationContext(), DetailActivity.class);
desk.substring(0);
i.putExtra("title", title);
i.putExtra("desk", desk);
i.putExtra("rate", rate);
startActivity(i);
}
});
Picture of the DetailActivity:
I want to get the full description, how?

you can add a params "fullMessage" to storage the all of the message,and "description" to storage some message.Then use i.putExtra("desk", fullMessage) to carry full message to another activity.
Another solution is to add those attribute to your TextView in ListView
<TextView
<!-- other value -->
android:maxLines="3"
android:ellipsize="end"/>
And you can put full message to this TextView,it will folding itself when the message is too long.

Just do not overwrite your description variable. Instead of above have one more variable that holds your truncated value, say overview.
String overview = description.length() > 64 ? description.substring(0,64)+"...":description;
Then your description variable will continue to hold the original value. Just use that where you need.

Try this :
mymodalclass:make class
public class MyModal {
String title ;
String description ;
double movieRatet ;
String movieRate;
String releaseDate;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getMovieRatet() {
return movieRatet;
}
public void setMovieRatet(double movieRatet) {
this.movieRatet = movieRatet;
}
public String getMovieRate() {
return movieRate;
}
public void setMovieRate(String movieRate) {
this.movieRate = movieRate;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public String getPosterUrl() {
return posterUrl;
}
public void setPosterUrl(String posterUrl) {
this.posterUrl = posterUrl;
}
String posterUrl ;
}
//****************************************
while parsing data :
Arraylist list = new ArrayList();
for(int i=0;i<yourjsonarray.length();i++){
JSONObject object = yourjsonarray.getJSONObject(i);
MyModal m = new MyModal();
m.setTitle(object.getString("title"));//like this set all data
//now add this object to list
list.add(m);
}
//now when you click list just get clicked position and by this position get that particular object and pass that to next activity
ex: position = your_clicked_position
MyModal clicked_modal_object = (MyModal) list.get(your_clicked_position);
//now pass this clicked_modal_object to next activity

You can use two variables.(I'm sure this is what #Gautam mentioned) The first is the full description and the second is the shorter description.
String description = object.getString("overview"); // full
String shortDesc = description.length() > 64 ? description.substring(0,64)+"...":description; // add this to listView
Log.d("movie description ", shortDesc);
I want to get the real description, in the DetailActivity
(setOnItemClickListener)
When button clicked, get the description string instead
i.putExtra("desk", description);
Note: Make sure you set description as globally.

Related

Images dissapearing while scrolling Listiew (Android Studio)

guys.
I'm totally new to programming and Android programming and I have a problem. I fetch images from MySQL database as InputStream. Then I have Adapter where I load data, that I got from database, to corresponding objects. Hooray, listView is created and everything looks good! But... When I scroll down/up my images dissapear. I've read that listView recycles objects, but the problem is that I don't know/understand how can I fix this problem :///
Please help me guys !!
SHORT: images dissapear in listView on scroll. Too much newbie to understand how to fix it :/
Event class
public class Event {
private int id;
private String title;
private Date date;
private String place;
private String genre;
private String description;
private Double price;
public Event(int id, String title, Date date, String place, String genre, String description, Double price, InputStream image) {
this.id = id;
this.title = title;
this.date = date;
this.place = place;
this.genre = genre;
this.description = description;
this.price = price;
this.image = image;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public InputStream getImage() {
return image;
}
public void setImage(InputStream image) {
this.image = image;
}
private InputStream image;
}
Adapter Class
public class EventAdapter extends BaseAdapter {
LayoutInflater mInflater;
ArrayList<Event> data;
public EventAdapter(Context c, ArrayList<Event> d){
mInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.data = d;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
// This is where data is assigned to coresponding fields in event_layout
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Hooks
View view = mInflater.inflate(R.layout.event_layout, null);
TextView eventName = (TextView) view.findViewById(R.id.eventName);
TextView dateYear = (TextView) view.findViewById(R.id.dateYear);
TextView dateDay = (TextView) view.findViewById(R.id.dateDay);
ImageView image = (ImageView) view.findViewById(R.id.eventImage);
// Changing date format
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
String date = sdf.format(data.get(position).getDate());
// Extracting date into seprate vars
String year = date.substring(8);
String day = date.substring(0, 1).toUpperCase() + date.substring(1, 3) + "." + date.substring(4, 7) + "d.";
// making Bitmap from InputStream
Bitmap bmp = BitmapFactory.decodeStream(data.get(position).getImage());
eventName.setText(data.get(position).getTitle());
dateYear.setText(year);
dateDay.setText(day);
image.setImageBitmap(bmp);
return view;
}
}
EventsPage class
public class EventsPage extends AppCompatActivity {
private EventAdapter eventAdapter;
private Context thisContext;
private ListView eventsListView;
private TextView progressBar;
private ArrayList<Event> events = new ArrayList<Event>();
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
// Set status bar color to main_green
if(Build.VERSION.SDK_INT >= 21){
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
window.setStatusBarColor(this.getResources().getColor(R.color.main_green_color , this.getTheme()));
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_page);
Resources res = getResources();
eventsListView = (ListView) findViewById(R.id.eventsListView);
progressBar = (TextView) findViewById(R.id.progressBar);
thisContext = this;
progressBar.setText("");
GetData data = new GetData();
data.execute("");
}
public class GetData extends AsyncTask<String, String, String> {
private String msg;
private ArrayList<Event> bkc_events = new ArrayList<>();
private ArrayList<Event> tic_events = new ArrayList<>();
#Override
protected void onPreExecute(){
progressBar.setText("Connecting to database...");
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected String doInBackground(String... strings) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(DBstrings.JDBC_DRIVER);
conn = DriverManager.getConnection(DBstrings.URL, DBstrings.USERNAME, DBstrings.PASSWORD);
// Get BKC events
stmt = conn.createStatement();
String query = "SELECT * from `bkc_event` ORDER by `date` ASC";
ResultSet res = stmt.executeQuery(query);
while(res.next()){
Event temp = new Event(res.getInt("ID"), res.getString("title"),
res.getDate("date"), res.getString("place"),
res.getString("genre"), res.getString("description"),
res.getDouble("price"), res.getBinaryStream("image"));
this.bkc_events.add(temp);
}
res.close();
// Get TIC events
query = "SELECT * from `tic_event` ORDER by `date` ASC";
res = stmt.executeQuery(query);
while(res.next()){
Event temp = new Event(res.getInt("ID"), res.getString("title"),
res.getDate("date"), res.getString("place"),
res.getString("genre"), res.getString("description"),
res.getDouble("price"), res.getBinaryStream("image"));
tic_events.add(temp);
}
res.close();
stmt.close();
conn.close();
msg = "Process Completed";
PutDataTogether(bkc_events, tic_events);
} catch (ClassNotFoundException ex) {
msg = "Class not found ERROR";
Log.e("ClassNotFound", ex.getMessage());
} catch (SQLException ex) {
msg = "SQL exceltion";
Log.e("SQL:", ex.getMessage());
} finally {
try {
if(stmt != null)
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
// Combine data 2 sets into 1 set
#RequiresApi(api = Build.VERSION_CODES.N)
private void PutDataTogether(ArrayList<Event> bkc, ArrayList<Event> tic){
events.addAll(bkc);
for (Event t: tic) {
// counter for showing redundancy
int counter = 0;
for(Event r: events){
// Check if title and date is the same if so - increase counter by 1
if(t.getTitle().toLowerCase().equals(r.getTitle().toLowerCase()) &&
t.getDate().equals(r.getDate()))
counter++;
}
// if counter == 0, then we can add event to final result set
if(counter == 0)
events.add(t);
}
events.sort(Comparator.comparing(Event::getDate));
}
// To show the data
#Override
protected void onPostExecute(String msg){
progressBar.setText(this.msg);
/*new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.INVISIBLE);
}
}, 1500); */
// We have stuff to display
if(events.size() > 0){
eventAdapter = new EventAdapter(thisContext, events);
eventsListView.setAdapter(eventAdapter);
}
}
} // END of GetDataEvents class
} // END of EventsPage
The problem:
Picture before scrolling
Picture after scrolling down and then back up
The issue is within the getView() method of your adapter. Recycling in a ListView means, that there is already an existing View which will be used to display your values, so you must not inflate a new one. Change your code like:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Hooks
View view = convertView;
if (view == null) {
view = mInflater.inflate(R.layout.event_layout, null);
}
TextView eventName = (TextView) view.findViewById(R.id.eventName);
TextView dateYear = (TextView) view.findViewById(R.id.dateYear);
TextView dateDay = (TextView) view.findViewById(R.id.dateDay);
ImageView image = (ImageView) view.findViewById(R.id.eventImage);
// Changing date format
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
String date = sdf.format(data.get(position).getDate());
// Extracting date into seprate vars
String year = date.substring(8);
String day = date.substring(0, 1).toUpperCase() + date.substring(1, 3) + "." + date.substring(4, 7) + "d.";
// making Bitmap from InputStream
Bitmap bmp = BitmapFactory.decodeStream(data.get(position).getImage());
eventName.setText(data.get(position).getTitle());
dateYear.setText(year);
dateDay.setText(day);
image.setImageBitmap(bmp);
return view;
}
Note I only changed the first 4 lines of the method to use the provided View which comes from the ListView and only inflate a new one when there is no existing to reuse.

ListView OnItemClickListener Song

I've created a ListView (myList). By pressing on one of the items on the ListView, the app is supposed to direct the user to the PlaySongActivity page.
I used a searchById function to try to match the ID of the song and the song in my database.( get ID of the song and match the song ID in database to play the same song) However, my teacher told me I am searching by the ID of the ListView, not the song.
So is there any way I can either search by the song title or possibly add an ID to each item in the ListView?
I'm a beginner in coding and have searched for hours and found no solution on the internet :(
private SongCollection mySongCollection = new SongCollection();
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(SearchSong.this, PlaySongActivity.class);
String resourceId = AppUtil.getResourceId(SearchSong.this, myList);
Song selectedSong = mySongCollection.searchById(resourceId);
AppUtil.popMessage(SearchSong.this, "Streaming music: " + selectedSong.getTitle());
intent.putExtra("id", selectedSong.getId());
intent.putExtra("title", selectedSong.getTitle());
intent.putExtra("artiste", selectedSong.getArtiste());
intent.putExtra("fileLink", selectedSong.getFileLink());
intent.putExtra("coverArt", selectedSong.getCoverArt());
startActivity(intent);
}
});
SongCollection.class codes
package com.example.musix;
public class SongCollection {
private Song[] allSongs = new Song[9];
public SongCollection (){
prepareSongs();
}
private void prepareSongs(){
Song theWayYouLookTonight = new Song ("S1001", "The Way You Look Tonight", "Michael Buble", "a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=2afe87a64b0042dabf51f37318616965", 4.66, "michael_buble_collection");
Song billiejean = new Song ("S1002", "Billie Jean", "Michael Jackson", "4eb779428d40d579f14d12a9daf98fc66c7d0be4?cid=2afe87a64b0042dabf51f37318616965", 4.9, "billie_jean");
Song somethingJustLikeThis = new Song("S1003", "Something Just Like This","The Chainsmokers","499eefd42a24ec562c464bd7acfad7ed41eb9179?cid=2afe87a64b0042dabf51f37318616965", 4.13, "something_just_like_this");
Song southOfTheBorder = new Song("S1004", "South of the Border","Ed Sheeran","7b43dd0c94b0af0c0401381a683d2f4833180ba3?cid=2afe87a64b0042dabf51f37318616965", 3.41, "south_of_the_border");
Song oldTownRoad = new Song("S1005", "Old Town Road","Lil Nas X","3bc62106123fcafad475271e72e74cd7f519ab83?cid=2afe87a64b0042dabf51f37318616965", 1.9, "old_town_road");
Song noGuidance = new Song("S1006", "No Guidance", "Chris Brown", "7c3bc7b4d1741a001463b570fe29f922d9c42bd6?cid=2afe87a64b0042dabf51f37318616965", 4.34, "no_guidance");
Song closer = new Song("S1007", "Closer", "The Chainsmokers", "8d3df1c64907cb183bff5a127b1525b530992afb?cid=2afe87a64b0042dabf51f37318616965", 4.08, "closer");
Song sideface = new Song("S1008", "側臉", "于果", "c8cc891a7cacb36857ea15c8fcfc4da6e4b1583d?cid=2afe87a64b0042dabf51f37318616965", 3.63, "sideface");
Song kebukeyi = new Song("S1009", "可不可以", "张紫豪", "2d790215acf7c4e6c5e093255b94a936064f75ed?cid=2afe87a64b0042dabf51f37318616965", 4.01, "kebukeyi");
allSongs[0]= theWayYouLookTonight;
allSongs[1]= billiejean;
allSongs[2]= somethingJustLikeThis;
allSongs[3]= southOfTheBorder;
allSongs[4]= oldTownRoad;
allSongs[5]= noGuidance;
allSongs[6]= closer;
allSongs[7]= sideface;
allSongs[8]= kebukeyi;
}
public Song searchById (String id){
Song selectedSong = null;
for(int index=0; index<allSongs.length; index++){
selectedSong = allSongs[index];
if(selectedSong.getId().equals(id)){
return selectedSong;
}
}
return selectedSong;
}
//create a method to retrieve the next song
public Song getNextSong(String currentSongId){
Song nextSong = null;
for(int x = 0; x < allSongs.length; x++){
String tempSongId = allSongs[x].getId();
if(tempSongId.equals(currentSongId) && (x < allSongs.length -1)){
nextSong = allSongs[x+1];
break;
}
}
return nextSong;
}
//create a method to retrieve the previous song
public Song getPrevSong(String currentSongId){
Song PrevSong = null;
for(int x = 0; x < allSongs.length; x++){
String tempSongId = allSongs[x].getId();
if(tempSongId.equals(currentSongId) && (x > 0)){
PrevSong = allSongs[x-1];
break;
}
}
return PrevSong;
}
//create a method to get random song
public Song getRandomSong(){
Song randomSong = null;
int max = 2;
int min = 0;
int randomNum = (int)(Math.random()*4);
randomSong = allSongs[randomNum];
return randomSong;
}
}
Song.class codes
package com.example.musix;
public class Song {
//private attributes are hidden from other classes/files
private String id;
private String title;
private String artiste;
private String fileLink;
private double songLength;
private String coverArt;
public Song(String _id, String _title, String _artiste, String _fileLink, double _songLength, String _coverArt){
this.id = _id;
this.title = _title;
this.artiste = _artiste;
this.fileLink = _fileLink;
this.songLength = _songLength;
this.coverArt = _coverArt;
}
//encapsulation
//SET methods for setting/changing of the values of the attributes
public void setId(String id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setArtiste(String artiste) {
this.artiste = artiste;
}
public void setFileLink(String fileLink) {
this.fileLink = fileLink;
}
public void setSongLength(double songLength) {
this.songLength = songLength;
}
public void setCoverArt(String coverArt) {
this.coverArt = coverArt;
}
//GET methods allows us to retrieve values of the attributes
public String getId() {
return this.id;
}
public String getTitle() {
return this.title;
}
public String getArtiste() {
return this.artiste;
}
public String getFileLink() {
return this.fileLink;
}
public double getSongLength() {
return this.songLength;
}
public String getCoverArt() {
return this.coverArt;
}
}
codes for getResourceId
public final class AppUtil
{
public static void popMessage(Context context, String message)
{
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
public static String getResourceId(Context context, View view)
{
String id = context.getResources().getResourceEntryName(view.getId());
return id;
}
String resourceId = AppUtil.getResourceId(SearchSong.this, myList);
Song selectedSong = mySongCollection.searchById(resourceId);
resourceId is going to be the id of the element of the list view (eg. first element id = 0, 2nd id = 1 and so on).
public Song searchById (String id){
Song selectedSong = null;
for(int index=0; index<allSongs.length; index++){
selectedSong = allSongs[index];
if(selectedSong.getId().equals(id)){
return selectedSong;
}
}
return selectedSong;
}
Should be:
public Song searchById (String id){
//we are returning the song selected by the index of its Arrays
Song selectedSong = allSongs[Integer.parseInt(id)];
return selectedSong;
}
Why?:
Your returning the actual songid, but in
Song selectedSong = mySongCollection.searchById(resourceId); <-- resourceId is already the Id stored in the database and not the index of mySongCollection.
intent.putExtra("id", selectedSong.getId());
you are using already the actuals song id. This doesen't make sense as you can already identify the actual song.
So either apply these changes or change this line:
intent.putExtra("id", resourceId);

How to pass value to another activity with id of the option clicked from dialog box

I have a ListView which is display several String when i click on a categories it will call and pop out a dialog options menu which has the options of English, Hindi and Cancel. The onClicklistener will be triggered when the user Click one of the category from the Listview such as "Novel", "Book" or "Plays".
What I want to do here is, when the user clicks "Book" and choose language English option, I want to pass category_id and language_id to the next activity.the category_id and language_id are the json object that i got from the server response. So I need to get the category_id selected from listview and pass it to the next activity along with the language_id as seleceted in dialog box.
if this is possible then how? Thanks in advance for your help.
holder.imageView.setImageUrl(Config.TAG_IMAGE_URL+category.getImage(), imageLoader);
holder.textViewName.setText(category.getName());
category_id = category.getId();
language_id = category.getLanguage_id();
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
handleLanguageDialog();
}
});
}
private AlertDialog handleLanguageDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Select Language")
.setItems(R.array.lang, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch(which)
{
case 0:// English
break;
case 1://Bengali
break;
}
}
});
return builder.create().show();
}
categ.java
private String id;
private String name;
private String description;
private String image;
private String parent_id;
private String language_id;
private String created;
private String modified;
#Override
public String toString() {
return "Categ{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
", image='" + image + '\'' +
", parent_id='" + parent_id + '\'' +
", language_id='" + language_id + '\'' +
", created='" + created + '\'' +
", modified='" + modified + '\'' +
'}';
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getParent_id() {
return parent_id;
}
public void setParent_id(String parent_id) {
this.parent_id = parent_id;
}
public String getLanguage_id() {
return language_id;
}
public void setLanguage_id(String language_id) {
this.language_id = language_id;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
}
In your first activity pass data like this
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("CATEGORY_ID", category_id);
intent.putExtra("LANGUAGE_ID", language_id);
startActivity(intent);
Now in your next activity recieve data like this
String cat_id = getIntent().getExtras().getString("CATEGORY_ID");
String cat_id = getIntent().getExtras().getString("LANGUAGE_ID");
Pass like this inside your switch case
case 0:
Intent intent = new Intent(YourCurrentActivity.this, Destination.class);
intent.putExtra("category_key", category_id);
intent.putExtra("language_key", language_id);
startActivity(intent);
Intent intent = new Intent(SourceActivity.this,destinationAvtivity.java);
intent.putExtra("category_id",109);
startActivity(theintent);

Same button outputting different sounds

This is the code I have at the moment.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_earthbound);
int charNo = (Integer)getIntent().getExtras().get(EXTRA_CHARNO);
Earthbound character = Earthbound.chars[charNo];
ImageView photo = (ImageView) findViewById(R.id.photo);
photo.setImageResource(character.getImageResourceId());
photo.setContentDescription(character.getName());
TextView name = (TextView) findViewById(R.id.name);
name.setText(character.getName());
TextView desc = (TextView) findViewById(R.id.desc);
desc.setText(character.getDesc());
Button voice_btn = (Button)this.findViewById(R.id.voice_btn);
voice_btn.setContentDescription(character.getName());
final MediaPlayer mp = MediaPlayer.create(this, R.raw.snd_se_narration_characall_Ness);
final MediaPlayer mmp = MediaPlayer.create(this, R.raw.snd_se_narration_characall_Lucas);
voice_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
mp.start();
mmp.start();
}
});
I essentially have two activities, the first one being that the user can choose the list view option "Earthbound", a Java class which lists the characters, and an activity displaying the characters bio. The second activity has one button, but this button will change sounds depending on which character the user picked. This is where I am stuck.
This is the Java class if it helps:
private String name;
private String desc;
private int imageResourceId;
private int voiceId;
public Earthbound(String name, String desc, int imageResourceId, int voice){
this.name = name;
this.desc = desc;
this.imageResourceId = imageResourceId;
this.voiceId = voiceId;
}
public static final Earthbound[] chars = {
new Earthbound("Ness", "Ness is the silent main protagonist of EarthBound (Mother 2 in Japan), " +
"and is analogous to Ninten and Lucas in their respective games. He greatly enjoys baseball; " +
"not only are most of his weapons various types of baseball bats, " +
"but he can also equip several baseball caps. ", R.drawable.ness, R.raw.snd_se_narration_characall_Ness),
new Earthbound("Lucas", "Lucas is the central character of Mother 3, out of seven main characters total. " +
"(Lucas, Kumatora, Duster, Boney, Claus, Flint, and Salsa). He is from Tazmily Village. " +
"He is the gentle twin of Claus. ", R.drawable.lucas, R.raw.snd_se_narration_characall_Lucas),
};
public String getName() {
return name;
}
public String getDesc() {
return desc;
}
public int getImageResourceId() {
return imageResourceId;
}
#Override
public String toString() {
return this.name;
}
public int getVoiceId() {
return voiceId;
}
Can't you just use an if or switch statement to determine which sound plays?
if ((character.getName().compareTo("Ness")) == 0)
mp.start();
else
mmp.start();
something like this ought to work.
If you just need choose a sound to play, you can set your sound resource to you Earthbound, Others use your code and need not know which resource to selected.
private String name;
private String desc;
private int imageResourceId;
private int voiceId;
public Earthbound(String name, String desc, int imageResourceId, int voice){
this.name = name;
this.desc = desc;
this.imageResourceId = imageResourceId;
this.voiceId = voiceId;
}
public static final Earthbound[] chars = {
new Earthbound("Ness", "Ness is the silent main protagonist of EarthBound (Mother 2 in Japan), " +
"and is analogous to Ninten and Lucas in their respective games. He greatly enjoys baseball; " +
"not only are most of his weapons various types of baseball bats, " +
"but he can also equip several baseball caps. ", R.drawable.ness, R.raw.snd_se_narration_characall_Ness),
new Earthbound("Lucas", "Lucas is the central character of Mother 3, out of seven main characters total. " +
"(Lucas, Kumatora, Duster, Boney, Claus, Flint, and Salsa). He is from Tazmily Village. " +
"He is the gentle twin of Claus. ", R.drawable.lucas, R.raw.snd_se_narration_characall_Lucas),
};
public String getName() {
return name;
}
public String getDesc() {
return desc;
}
public int getImageResourceId() {
return imageResourceId;
}
#Override
public String toString() {
return this.name;
}
public int getVoiceId() {
return voiceId;
}
public int getMediaResourceId() {
return TextUtils.equals(name, "Ness") ? R.raw.snd_se_narration_characall_Ness : R.raw.snd_se_narration_characall_Lucas;
}
Then
final MediaPlayer mp = MediaPlayer.create(this, character.getMediaResourceId());
voice_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
mp.start();
}
});

Android intent extra populate

Fisrt i must mention that i am new to Android and Java. I coded a json http object who populate Serializable class and from them i populate listviews, everything works fine, but now i am trying to populate a textview which is on different xml layout, with one string from Serializable class.
Serializable class
public class FeedItem implements Serializable {
private static final long serialVersionUID = 1L;
private int test1;
private String title;
private String date;
private String attachmentUrl;
private String id;
private String content;
private String url;
private String tiitle = "sfsf";
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAttachmentUrl() {
return attachmentUrl;
}
public void setAttachmentUrl(String attachmentUrl) {
this.attachmentUrl = attachmentUrl;
}
#Override
public String toString() {
return "[ title=" + title + ", date=" + date + "]";
}
public void save(){
FeedItem feed = new FeedItem();
Intent intent = new Intent();
Bundle extras = new Bundle();
intent.putExtra("title", feed);
and the fragment class where i want to populate textview
public void UpdateList(){
TextView infoz = (TextView) getView().findViewById(R.id.infoz);
Intent intent = getActivity().getIntent();
Bundle extras = intent.getExtras();
String title = (String) getActivity().getIntent().getSerializableExtra("title");
Toast.makeText(getActivity(), title, Toast.LENGTH_LONG).show();
}
The toast is empty.
You are putting a Serializable object in your Bundle (in Eclipse, moving your mouse above the method name should show you the signature, which in your case would be putExtra(String name, Serializable extra)). To retrieve the title String, you should first retrieve the FeedItem object, then get the String from it, like so :
intent.putExtra("title", feed);
and
String title = ((FeedItem)getActivity().getIntent().getSerializableExtra("title")).getTitle();
Alternatively, you could just put the title in the extra, if that's all you need, using
intent.putExtra("title", feed.getTitle());
then getting the title like this :
String title = getActivity().getIntent().getStringExtra("title");
This is the code you are using to get the title from the intent:
String title = (String) getActivity().getIntent().getSerializableExtra("title");
This will extract the extra with the key "title" and deserialize it, but you are then casting this to a String. You didn't put a String into the extras Bundle, you put a FeedItem object in there. You need to do this:
FeedItem feedItem = (FeedItem)getActivity().getIntent().getSerializableExtra("title");
String title = feedItem.getTitle();
Also, this code you posted:
public void save(){
FeedItem feed = new FeedItem();
Intent intent = new Intent();
Bundle extras = new Bundle();
intent.putExtra("title", feed);
makes no sense. First, you create a new instance of FeedItem. This new instance will have an empty title. Secondly, you create a Bundle called extras but do nothing with it. And thirdly, are you sure that the Intent you are sending actually has the object you want in the extras? Either check this with a debugger or debug logging.

Categories