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);
Related
My project used to save products information into shoppingCart on a database with dbSqlite. But, for now it should save information of product from server. According to web service, one variable type is List Array. It was String before. And one of them is double, it was String also. I changed real in dbSqlite but what I should do for Array? How can save it on dbSqlite again?
error: no suitable method found for put(String,List) method
ContentValues.put(String,String) is not applicable
Cart.java
public class Cart {
private List<String> Image;
private String Title;
private double Cost;
private String Market;
public List<String> getImage() {
return Image;
}
public void setImage(List<String> image) {
Image = image;
}
public double getCost() {
return Cost;
}
public void setCost(double cost) {
Cost = cost;
}
private String TotalCost;
private String Description;
public boolean boolExpand = false;
boolean isExpanded;
public boolean isExpanded() {
return this.isExpanded;
}
public void setExpanded(boolean expanded) {
this.isExpanded = expanded;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getMarket() {
return Market;
}
public void setMarket(String market) {
Market = market;
}
public String getTotalCost() {
return TotalCost;
}
public void setTotalCost(String totalCost) {
TotalCost = totalCost;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}
ProductDetailAdapter.java
public class ProductDetailAdapter extends RecyclerView.Adapter<ProductDetailAdapter.ViewHolder> {
btnProductDetail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
// isLogined bilgisi shared preferences'tan alınıyor. eğer true ise username ve password bilgileri alınıyor.
// değil ise empty olarak giriliyor.
isLogined = sharedPreferences.getBoolean("isLogined", false);
if (isLogined) {
saveCartAmount();
db = new DatabaseHelper(mContext);
List<String> img;
double cost;
String title;
String total;
String market;
String description;
img = productPageList.get(position).getProductImages();
cost = productPageList.get(position).getProductPrices().get(position).getShopProductPrice();
title = productPageList.get(position).getProductName();
market = productPageList.get(position).getProductPrices().get(position).getShopName();
total = "";
description = productPageList.get(position).getProductDescription();
// Log.e("amountdb","dasdsa");
// amount = amountdb++;
db.AddToCart(img, title, cost, market, total, description);
cartListener.onProductSelect(productPageList.get(position));
Toast.makeText(mContext, "Ürün sepetinize eklendi.", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(mContext, "Sepete ürün eklemek için üye girişi yapmanız gerekmektedir.", Toast.LENGTH_SHORT).show();
}
}
});
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, "Login.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table cart(Image text, Title text, Cost real, Market text, TotalCost text, Description text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists cart");
}
public void deleteCart(){
SQLiteDatabase db = this.getWritableDatabase();
db.delete("cart", null,null);
}
public void AddToCart(List<String> Image, String Title, Double Cost, String Market, String TotalCost, String Descritpion){
SQLiteDatabase db = getWritableDatabase();
ContentValues data = new ContentValues();
data.put("Image",Image );
data.put("Title",Title);
data.put("Cost",Cost);
data.put("Market",Market);
data.put("TotalCost", TotalCost);
data.put("Description", Descritpion);
db.insert("cart",null,data);
}
public List<Cart> getdata(){
// DataModel dataModel = new DataModel();
List<Cart> data=new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor rs = db.rawQuery( "select * from cart",null);
StringBuffer stringBuffer = new StringBuffer();
Cart dataModel = null;
while (rs.moveToNext()) {
dataModel= new Cart();
List<String> image = Collections.singletonList(rs.getString(rs.getColumnIndexOrThrow("Image")));
String title = rs.getString(rs.getColumnIndexOrThrow("Title"));
Double cost = (rs.getDouble(rs.getColumnIndexOrThrow("Cost")));
String market = rs.getString(rs.getColumnIndexOrThrow("Market"));
String totalCost = rs.getString(rs.getColumnIndexOrThrow("TotalCost"));
String description = rs.getString(rs.getColumnIndexOrThrow("Description"));
dataModel.setImage(image);
dataModel.setTitle(title);
dataModel.setCost(cost);
dataModel.setMarket(market);
dataModel.setTotalCost(totalCost);
dataModel.setDescription(description);
stringBuffer.append(dataModel);
data.add(dataModel);
}
return data;
}
}
You can read the array like this :
String[] myArray = `put your array here`
for (int i = 0; i < myArray.size(); i++)
{
//Here u insert the data by getting what u need from the array
data.put("Cost",myArray.get(i).Cost);
}
You should be fine serializing the list to string. I. e. you could serialize it to json and deserialize it if you need it again.
Here is a small code example for two functions you could use in your DatabaseHelper.
private String serialize(List<String) list) {
JSONArray jsonArray = new JSONArray();
for (String s : list) {
jsonArray.put(s);
}
return jsonArray.toString();
}
private List<String> deserialize(String json) {
JSONArray jsonArray = new JSONArray(json);
List<String> list = new ArrayList<>();
for (int i=0; i<jsonArray.getLength(); ++i) {
list.add(jsonArray.getString(i));
}
return list;
}
And then you can use these functions:
data.put("Image",serialize(Image));
List<String> image = deserialize(rs.getString(rs.getColumnIndexOrThrow("Image")));
(This is only pseudo-code. Maybe you need to adjust it. Furthermore the functions don't handle null-parameters and may throw NullPointerExceptions!)
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.
I am using Parcelable for a custom Song object I have in my class. However, when ever I am trying to get an arraylist extra of type Song I always get a null pointer exception. I have no problem getting string extras from the intent but when I try to get this ArrayList I need I always get null. I am also getting a null when I just try to pass a Song object, so I am assuming there is some issue with it but I cannot figure it out for the life of me.
This is my song class
import android.os.Parcel;
import android.os.Parcelable;
public class Song implements Parcelable {
private String uri;
private String title;
private String artist;
private String album;
private String length;
private int count;
private int source;
public Song () {
}
public Song (String title, String artist, String album, String uri, String length, int count,
int source) {
this.uri = uri;
this.title = title;
this.artist = artist;
this.album = album;
this.length = length;
this.count = count;
this.source = source;
}
public String getUri() {
return uri;
}
public String getArtist() {
return artist;
}
public String getTitle() {
return title;
}
public String getLength() {
return length;
}
public int getCount() {return count;}
#Override
public String toString() {
return title + " - " +artist;
}
#Override
public boolean equals(Object o){
if (o instanceof Song) {
Song song = (Song) o;
if (title.equals(song.title) && length.equals(song.length)) {
return true;
}
}
return false;
}
public int compareTo(Song s) {
if (this.count < s.getCount()) {
return -1;
}
else if(this.count > s.getCount()){
return 1;
}
return 0;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
public int getSource() {
return source;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.uri);
dest.writeString(this.title);
dest.writeString(this.artist);
dest.writeString(this.album);
dest.writeString(this.length);
dest.writeInt(this.count);
dest.writeInt(this.source);
}
protected Song(Parcel in) {
this.uri = in.readString();
this.title = in.readString();
this.artist = in.readString();
this.album = in.readString();
this.length = in.readString();
this.count = in.readInt();
this.source = in.readInt();
}
public static final Creator<Song> CREATOR = new Creator<Song>() {
#Override
public Song createFromParcel(Parcel source) {
return new Song(source);
}
#Override
public Song[] newArray(int size) {
return new Song[size];
}
};
}
This is the line I use to package the arraylist
Intent intent = new Intent();
Log.d("UTILS ", " size: " +queue.size()); // Making sure it is not null before passing
intent.setClass(context, PlayerService.class);
intent.putParcelableArrayListExtra(PlayerService.EXTRA_TRACK_LIST, queue);
context.startService(intent);
This is retrieving the arraylist in PlayerService class
public static final String EXTRA_TRACK_LIST = "EXTRA_TRACK_LIST";
private ArrayList<Song> trackList;
.
.
.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null || intent.getAction() == null) {
Log.d(TAG, "unspecified command");
return START_STICKY;
}
trackList=intent.getParcelableArrayListExtra(PlayerService.EXTRA_TRACK_LIST);
if (trackList == null) {
Log.d("TRACKLIST", "IS NULL");
} else {
Log.d(TAG, "size: "+trackList.size());
}
.
.
.
// more irrelevant code
your parameter is wrong
public static final String EXTRA_TRACK_LIST = "EXTRA_TRACK_LIST";
so change like this
trackList = intent.getParcelableArrayListExtra(PlayerService.EXTRA_TRACK_LIST);
Is queue a Queue/List or similar? Or is it an array? If array, should be queue.length, right? From List to array try this. This should work.
intent.putParcelableArrayListExtra(PlayerService.EXTRA_TRACK_LIST, queue);
If not, let me know to keep trying. Also, you could also pass it as String. You could use GSON to convert it to JSON string. After converted to String, pass it as a single String.
Intent intent = new Intent(ActivityA.this, Service.class);
intent.putExtra(new Gson().toJson(queue), PlayerService.EXTRA_TRACK_LIST);
context.startService(intent);
And to retrieve that object again:
Song song = new Gson().fromJson(intent.getStringExtra(PlayerService.EXTRA_TRACK_LIST), Song.class);
Or, if list (I believe you case):
Type listType = new TypeToken<ArrayList<Song.class>>(){}.getType();
List<Song> songList = new Gson().fromJson(intent.getStringExtra(PlayerService.EXTRA_TRACK_LIST), listType);
addSong(title:String,filePath: String, artist:String):int
adds the song to the play list and returns 0 if added and –1 if the song can not be added because the list is full.
*** I keep on getting errors like method addsong(String, String, String) is not applicable for agrument int and also the getArtist method is not defined. How do I go upon it? Any suggestions or solutions to make it work?
PLaylist Class:
public class Playlist {
//Instance Variables
private int numOfSongs;
private Songs[] songList;
// Constructors
public Playlist(int maxNumofSongs){
this.numOfSongs = 0;
this.songList = new Songs[maxNumofSongs];
}
//Getters
public Songs[] getSongList(){
return songList;
}
//Methods
public void addSong(String title, String filePath, String artist){
Songs p = new Songs(title, filePath, artist);
addSong(p);
}
public void addSong(Songs p){
songList[this.numOfSongs] = p;
this.numOfSongs++;
}
public Songs getSong(int pos){
if (pos <= this.songList.length)
return this.songList[pos];
else
return null;
}
public int getSongByTitle(String title){
int pos = -1;
for (int i = 0; i < this.numOfSongs; i++)
if (this.songList[i].getTitle() == title)
pos = i;
return pos;
}
public String toString(){
String playlistDesc = "";
playlistDesc += "Number of Songs added in Playlist: "+ numOfSongs;
return playlistDesc;
}
}
User CLass:
public class User {
//Instance Variables
private String name;
private String email;
private Playlist favoriteSongs;
Songs[] songs = this.favoriteSongs.getSongList();
//Constructors
public User(String name, String email, Playlist favoriteSongs){
this.name = name;
this.email = email;
this.favoriteSongs = favoriteSongs;
}
public User(String name, String email){
this.name = name;
this.email = email;
}
//Setters
public void setPlayList(Playlist list){
this.favoriteSongs = list;
}
//Get song title by inputting the position in the playlist array
public String getSongTitle(int pos){
if (pos < songs.length){
Songs s = songs[pos];
//you can then get the title of the song using
s.getTitle();
}
return songs[pos].getTitle();
}
//Add new song to the playlist
public int addSong(String title, String filePath, String artist){
for(int i = 0; i < songs.length; i++) {
if (addSong(i) == songs[i].getTitle().getArtist()){ // or what ever you want to compare
return 0;
}
// if you do not found any thing
return -1;
}
}
//Counts how many songs with the same artist
public int artistSongCount(String artist){
int count = 0;
for (int i=0; i < songs.length; i++)
if (this.songs[i].getArtist() == artist)
count++;
return count;
}
//Print out details of user
public String toString(){
String userOutput = "";
userOutput += "Name: "+ name;
userOutput += "Email: "+ email;
return userOutput;
}
}
I have an Parcelable object called Book and another called Author. I can't tell why the object constructor for Book is not working. The first bit of code is where i try to make it so I can send it to a parent activity. The values were checked before, and when I do the .toString() method on book, I get null Price: null
Activity Code
EditText editText = (EditText) findViewById(R.id.search_title);
String title = editText.getText().toString();
editText = (EditText) findViewById(R.id.search_author);
String author = editText.getText().toString();
editText = (EditText) findViewById(R.id.search_isbn);
int isbn = Integer.parseInt(editText.getText().toString());
...
Parcel p = Parcel.obtain();
p.writeInt(isbn);
p.writeString(title);
p.writeString(author);
p.writeString(editText.getText().toString());
p.writeString("$15.00");
Intent intent = new Intent();
Book book = new Book(p);
System.out.println(book.toString());
Book.java
public class Book implements Parcelable {
private int id;
private String title;
private ArrayList<Author> authors = new ArrayList<Author>();
//private int Aflags;
private String isbn;
private String price;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(id);
out.writeString(title);
out.writeTypedList(authors);
out.writeString(isbn);
out.writeString(price);
}
public Book(Parcel in) {
id = in.readInt();
title = in.readString();
in.readTypedList(authors, Author.CREATOR);
isbn = in.readString();
price = in.readString();
}
public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>() {
public Book createFromParcel(Parcel in) {
return new Book(in);
}
public Book[] newArray(int size) {
return new Book[size];
}
};
#Override
public String toString()
{
return title + " Price: " + price;
}
}
Author.java
public class Author implements Parcelable {
// NOTE: middleInitial may be NULL!
public String firstName;
public String middleInitial;
public String lastName;
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(firstName);
if (middleInitial.length() == 0)
out.writeString(middleInitial);
out.writeString(lastName);
}
private Author(Parcel in)
{
firstName = in.readString();
if (in.dataSize() == 2)
middleInitial = in.readString();
if (in.dataSize() == 1)
lastName = in.readString();
}
public static final Parcelable.Creator<Author> CREATOR = new Parcelable.Creator<Author>() {
public Author createFromParcel(Parcel in) {
return new Author(in);
}
public Author[] newArray(int size) {
return new Author[size];
}
};
#Override
public int describeContents() {
return 0;
}
}
Parcel p = Parcel.obtain();
p.writeInt(isbn);
p.writeString(title);
p.writeString(author); // Here i think u need to write list of author and not string
p.writeString(editText.getText().toString());
p.writeString("$15.00");
Intent intent = new Intent();
Book book = new Book(p);
System.out.println(book.toString());
/*****Edited answer ******/
//HERE u go mate this should work, tested code
//You need to parse the author text then
Parcel p = Parcel.obtain();
p.writeInt(23); // isbn
p.writeString("sometitle");
// List<String> data = new List<String>();//parseAuthor(author); // function dependent on what u get
Parcel auth = Parcel.obtain();
auth.writeString("firstname"); // firstname
auth.writeString("middle"); // middle
auth.writeString("lastname"); // lastname
auth.setDataCapacity(3);
auth.setDataPosition(0);
Author a = Author.CREATOR.createFromParcel(auth);
ArrayList<Author> authors = new ArrayList<Author>();
authors.add(a);
p.writeTypedList(authors);
p.writeString("something");
p.writeString("$15.00");
p.setDataPosition(0);
Intent intent = new Intent();
Book book = Book.CREATOR.createFromParcel(p);
System.out.println(book.toString());
Hi so I just gave up and made a new constructor that doesn't use Parcels.
But what was written below p.setDataPosition(0); may work as well for future users