Android TextView setText with Getter return - java

I just try my first Android app and have encountered a problem where I do not really get ahead. In my app I create an ArrayList which will filled with Objects. Each Object has four attributes. Now I´d like to write each attribute for each Object in its own specific TextView. But there is my Problem. If the same Code is run in a normal Java Application and I use System.out.Print("getter method") I get the Value I would like, but if I use .setText("getter method") I get what you can see on the screenshot.
ActivityClass:
public class ShowBeaconActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showbeacons);
setUpShowBeacons();
}
public void setUpShowBeacons(){
//
//Beacon 1
//
TextView beaconOneUUID = (TextView)findViewById(R.id.txtBeaconOneUUIDValue);
beaconOneUUID.setText(BeaconListe.getBeacon(0,"UUID"));
TextView beaconOneMajor = (TextView)findViewById(R.id.txtBeaconOneMajorValue);
beaconOneMajor.setText(BeaconListe.getBeacon(0,"Major"));
TextView beaconOneMinor = (TextView)findViewById(R.id.txtBeaconOneMinorValue);
beaconOneMinor.setText(BeaconListe.getBeacon(0,"Minor"));
TextView beaconOneRSSI = (TextView)findViewById(R.id.txtBeaconOneRSSIValue);
beaconOneRSSI.setText(BeaconListe.getBeacon(0,"RSSI"));
//
//Beacon 2
//
TextView beaconTwoUUID = (TextView)findViewById(R.id.txtBeaconTwoUUIDValue);
beaconTwoUUID.setText(BeaconListe.getBeacon(1,"UUID"));
...
}
}
BeaconClass:
public class Beacon {
private String UUID;
private String Major;
private String Minor;
private int RSSI;
public Beacon(String UUID, String Major,String Minor, int RSSI){
this.UUID = UUID;
this.Major = Major;
this.Minor = Minor;
this.RSSI = RSSI;
}
//
//Getter
//
public String getUUID(){
return UUID;
}
public String getMajor(){
return Major;
}
public String getMinor() {
return Minor;
}
public int getRSSI() {
return RSSI;
}
//
//Setter
//
public void setRSSI(int RSSI){
this.RSSI = RSSI;
}
}
BeaconListeClass
public class BeaconListe {
private static ArrayList<Beacon>Liste = new ArrayList<Beacon>();
//
//Getter
//
public static String getBeacon(int index, String value){
String result = "";
switch(value){
case "UUID": result = Liste.get(index).getUUID();
break;
case "Major": result = Liste.get(index).getMajor();
break;
case "Minor": result = Liste.get(index).getMinor();
break;
case "RSSI": int resultTemp = Liste.get(index).getRSSI();
result = String.valueOf(resultTemp);
break;
}
return result;
}
//
//Setter
//
public static void addBeacon(String UUID, String Major, String Minor, int RSSI){
Liste.add(new Beacon(UUID, Major, Minor, RSSI));
}
}
App Screenshot

It can crash because of null value;
public static String getBeacon(int index, String value)
{
String result = "";
switch(value){
Beacon becon = Liste.get(index);
case "UUID":
result = becon!=null?becon.getUUID():"";
break;
case "Major":
result = becon!=null?becon.getMajor():"";
break;
case "Minor":
result = becon!=null?becon.getMinor():"";
break;
case "RSSI":
resultTemp = becon!=null?becon.getRSSI():0;
result = String.valueOf(resultTemp);
break;
}
return result==null?"":result;
}

try this
TextView beaconOneUUID = (TextView)findViewById(R.id.txtBeaconOneUUIDValue);
if(BeaconListe.getBeacon(0,"UUID") != null){
beaconOneUUID.setText(BeaconListe.getBeacon(0,"UUID"));
}
TextView beaconOneMajor = (TextView)findViewById(R.id.txtBeaconOneMajorValue);
if(BeaconListe.getBeacon(0,"Major") != null){
beaconOneMajor.setText(BeaconListe.getBeacon(0,"Major"));
}
TextView beaconOneMinor = (TextView)findViewById(R.id.txtBeaconOneMinorValue);
if(BeaconListe.getBeacon(0,"Minor") != null){
beaconOneMinor.setText(BeaconListe.getBeacon(0,"Minor"));
}
TextView beaconOneRSSI = (TextView)findViewById(R.id.txtBeaconOneRSSIValue);
if(BeaconListe.getBeacon(0,"RSSI") != null){
beaconOneRSSI.setText(BeaconListe.getBeacon(0,"RSSI"));
}
//
//Beacon 2
//
TextView beaconTwoUUID = (TextView)findViewById(R.id.txtBeaconTwoUUIDValue);
if(BeaconListe.getBeacon(1,"UUID")){
beaconTwoUUID.setText(BeaconListe.getBeacon(1,"UUID"));
}

From what I see, the .setText("getter methods") work just fine. The problem is the text that it sets. Check your function in which you populate the BeaconListe, which you have not shown here.
I tried your code but with the following
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showbeacons);
populateBeaconListe();
setUpShowBeacons();
}
public void populateBeaconListe(){
BeaconListe.addBeacon("B1UUID","B1MAJOR","B1MINOR",1111);
BeaconListe.addBeacon("B2UUID","B2MAJOR","B2MINOR",2222);
BeaconListe.addBeacon("B3UUID","B3MAJOR","B3MINOR",3333);
BeaconListe.addBeacon("B4UUID","B4MAJOR","B4MINOR",4444);
}
and it works just fine. See screenshot

Related

How to get the object properties from a list of objects in my model class so that I can pass the objects through intents?

I successfully parsed and retrieved all the data that I need from an xml document. I have two activities, one activity that shows the main data and other activity that shows an extra data for the recyclerView clicked item. I ma trying to pass all the data needed in the detail activity through intents from the main activity. But I am missing a method in my model class that helps me retrieve the objects themselves from the list to be able to send them into the putExtra(). So what should the method look like?
** The logcat is giving me this error in the detail activity: "Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference".
HERE is my MainAactivity:
public class MainActivity extends AppCompatActivity implements AdsAdapterOnClickHandler {
public static final String URL = "MYURL;
public static List<AdEntry> entryList = new ArrayList<>();
// Declaration
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setting the recyclerView and the adapter
loadPage();
}
public void loadPage() {
new DownloadXmlTask().execute(URL);
System.out.print("Result" + "Succeed");
}
private class DownloadXmlTask extends AsyncTask<String, Void, List<AdEntry>> {
#Override
protected List<AdEntry> doInBackground(String... urls) {
try {
return loadXmlFromNetwork(urls[0]);
} catch (IOException e) {
return null;
} catch (XmlPullParserException e) {
return null;
}
}
#Override
protected void onPostExecute(List<AdEntry> adEntries) {
Toast.makeText(MainActivity.this, "Successfully Processed", Toast.LENGTH_SHORT).show();
mAdsAdapter.setAdData(adEntries);
super.onPostExecute(adEntries);
}
}
public List<AdEntry> loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
InputStream stream = null;
try {
stream = downloadUrl(urlString);
entryList = parse(stream);
} finally {
if (stream != null)
stream.close();
}
return entryList;
}
public InputStream downloadUrl(String urlString) throws IOException {
// Open HttpURLConnection
}
#Override
public void onClick(View view, int position) {
final AdEntry entry = entryList.get(position);
Class destinationClass = DetailActivity.class;
Intent intentToStartDetailActivity = new Intent(this, destinationClass);
intentToStartDetailActivity.putExtra("Product Name", entry.productName);
intentToStartDetailActivity.putExtra("Product Thumbnail", entry.productThumbnail);
intentToStartDetailActivity.putExtra("Product Description", entry.productDescription);
intentToStartDetailActivity.putExtra("Product AppId", entry.appId);
intentToStartDetailActivity.putExtra("Product CallToAction", entry.callToAction);
intentToStartDetailActivity.putExtra("Product Link", entry.proxyLink);
intentToStartDetailActivity.putExtra("Product ImageRating", entry.averageRatingImageURL);
intentToStartDetailActivity.putExtra("Product Category", entry.productCategory);
intentToStartDetailActivity.putExtra("Product Rating", entry.productRating);
intentToStartDetailActivity.putExtra("Product NumberOfRating", entry.numberOfRatings);
startActivity(intentToStartDetailActivity);
}
}
Here is my DetailActivity:
public class DetailActivity extends AppCompatActivity {
// Views Declaration
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
// findViewsById
retrieveData();
}
public void retrieveData() {
String productName = getIntent().getStringExtra("Product Name");
String productThumbnail = getIntent().getStringExtra("Product Thumbnail");
String productDescription = getIntent().getStringExtra("Product Description");
String productAppId = getIntent().getStringExtra("Product AppId");
String productCall = getIntent().getStringExtra("Product CallToAction");
String productLink = getIntent().getStringExtra("Product Link");
String productImageRating = getIntent().getStringExtra("Product ImageRating");
String productCategory = getIntent().getStringExtra("Product Category");
String productNumberOfRatings = getIntent().getStringExtra("Product NumberOfRating");
Picasso.get().load(productThumbnail).into(thumbnail_imageView);
name_textView.setText(productName);
description_textView.setText(productDescription);
numberOfRating_textView.setText(productNumberOfRatings);
link_textView.setText(productLink);
category_textView.setText(productCategory);
rating_textView.setText(productImageRating);
}
}
Here is my ModelClass:
public class AdEntry {
private List<AdEntry> entries;
public String appId;
public String averageRatingImageURL;
public String callToAction;
public String productCategory;
public String proxyLink;
public String productDescription;
public String numberOfRatings;
public String productName;
public String productThumbnail;
public String productRating;
public AdEntry() {
}
public AdEntry(String appId, String averageRatingImageURL, String callToAction, String productCategory, String proxyLink,
String productDescription, String numberOfRatings, String productName, String productThumbnail, String productRating) {
this.appId = appId;
this.averageRatingImageURL = averageRatingImageURL;
this.callToAction = callToAction;
this.productCategory = productCategory;
this.proxyLink = proxyLink;
this.productDescription = productDescription;
this.numberOfRatings = numberOfRatings;
this.productName = productName;
this.productThumbnail = productThumbnail;
this.productRating = productRating;
}
public String getAppId() {
return appId;
}
public String getAverageRatingImageURL() {
return averageRatingImageURL;
}
public String getCallToAction() {
return callToAction;
}
public String getProductCategory() {
return productCategory;
}
public String getProxyLink() {
return proxyLink;
}
public String getProductDescription() {
return productDescription;
}
public String getNumberOfRatings() {
return numberOfRatings;
}
public String getProductName() {
return productName;
}
public String getProductThumbnail() {
return productThumbnail;
}
public String getProductRating() {
return productRating;
}
}
Here is the part where I retrieved my List in the XMLPUllParser class:
private static List readAds(XmlPullParser parser) throws XmlPullParserException, IOException {
List<AdEntry> entries = new ArrayList();
parser.require(XmlPullParser.START_TAG, ns, "ads");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
if (name.equals("ad"))
entries.add(readEntry(parser));
else
skip(parser);
}
System.out.println("entries" + entries);
return entries;
}
private static AdEntry readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "ad");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
switch (name) {
case "appId":
appId = readAppId(parser);
System.out.println("appId" + appId);
break;
case "averageRatingImageURL":
averageRatingImageURL = readRatingImage(parser);
System.out.println("rating" + averageRatingImageURL);
break;
case "callToAction":
callToAction = readCallToAction(parser);
System.out.println("callToAction" + callToAction);
break;
case "categoryName":
categoryName = readCategoryName(parser);
System.out.println("categoryName" + categoryName);
break;
case "clickProxyURL":
clickProxyURL = readProxyLink(parser);
System.out.println("clickProxyURL" + clickProxyURL);
break;
case "productDescription":
productDescription = readProductDescription(parser);
System.out.println("productDescription" + productDescription);
break;
case "numberOfRatings":
numberOfRatings = readNumberOfRatings(parser);
System.out.println("numberOfRatings" + numberOfRatings);
break;
case "productName":
productName = readNameProduct(parser);
System.out.println("productName" + productName);
break;
case "productThumbnail":
productThumbnail = readThumbnail(parser);
System.out.println("productThumbnail" + productThumbnail);
break;
case "rating":
rating = readRating(parser);
System.out.println("rating" + rating);
break;
default:
skip(parser);
break;
}
}
return new AdEntry(appId, averageRatingImageURL, callToAction, categoryName, clickProxyURL, productDescription,
numberOfRatings, productName, productThumbnail, rating);
}

Incompatible types error in ArrayList<Object>

I am trying to put ads in a RecyclerView which is currently parsing a JSON file, the problem is that the ArrayList is throwing a casting error when I try to fill it with ads or the data from JSON.
Errors occur at two places, one in the RecyclerViewAdapter() method body and other one in the BindViewHolder().
Here is my code from RecyclerViewAdapter.java (Error commented in 5th line)
private ArrayList<Object> arrayList = new ArrayList<>();
public RecyclerViewAdapter(Context context, ArrayList<CardSetterGetter> arrayList, ArrayList<String> favouriteItemList, int totalCount) {
this.context = context;
this.arrayList = arrayList; //Incompatible types. Required: ArrayList<java.lang.object>; found: ArrayList<com.comp.app.modal.CardSetterGetter>
this.favouriteItemList = favouriteItemList;
this.totalCount = totalCount;
}
onBindViewHolder() (Error commented in 27th line)
#Override
public void onBindViewHolder(final RecyclerViewHolder holder, final int position) {
int viewType = getItemViewType(position);
switch (viewType){
case AD_VIEW_TYPE:
NativeExpressAdViewHolder nativeExpressHolder = (NativeExpressAdViewHolder)holder;
NativeExpressAdView adView = (NativeExpressAdView)arrayList.get(position);
ViewGroup adCardView = (ViewGroup)nativeExpressHolder.itemView;
adCardView.removeAllViews();
if(adView.getParent() != null){
((ViewGroup)adView.getParent()).removeView(adView);
}
adCardView.addView(adView);
break;
case MENU_ITEM_VIEW_TYPE:
default:
String card_image;
CardSetterGetter cardSetterGetter;
cardSetterGetter = arrayList.get(position); //Incompatible types. Required: ArrayList<com.comp.app.modal.CardSetterGetter>; found: ArrayList<java.lang.object>;
card_image = constants.SERVERIP.concat(cardSetterGetter.getImageurl());
holder.cardSetterGetter = cardSetterGetter;
holder.title.setText(cardSetterGetter.getImagetitle()); //set title
PointF focusPoint = new PointF(0.5f, 0f);
// your app populates the focus point
holder.image // set image
.getHierarchy()
.setActualImageFocusPoint(focusPoint);
holder.image.setImageURI(Uri.parse(card_image));
}
}
Here is my CardSetterGetter.java
public class CardSetterGetter implements Serializable {
private String imagetitle ;
private String imageurl;
private String description;
private String tag;
private boolean isFavorite;
public String getImageId() {
return imageId;
}
public void setImageId(String imageId) {
this.imageId = imageId;
}
public String getFavourite() {
return favourite;
}
public void setFavourite(String favourite) {
this.favourite = favourite;
}
private String imageId ;
private String favourite ;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String category;
public CardSetterGetter(){
}
public String getImagetitle() {
return imagetitle;
}
public void setImagetitle(String imagetitle) {
this.imagetitle = imagetitle;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public CardSetterGetter(String imageurl , String imagetitle , String description , String category , String tag,String imageId ,String favourite){
this.imageurl = imageurl ;
this.imagetitle = imagetitle ;
this.description = description ;
this.tag = tag ;
this.category = category ;
this.isFavorite =false ;
this.imageId = imageId ;
this.favourite = favourite ;
}
public boolean isFavorite() {
return isFavorite;
}
public void setFavorite(String favorite) {
favourite = favorite;
}
}
I tried some of the questions on StackOverFlow like this one (Question), but I am unable to understand the basic concept of the solution, I already changed the datatype to Object (from CardSetterGetter).
Also tell me what happens if this issue of casting is solved and the arrayList returns adView where CardSetterGetter is expected or vice-versa, Do I need to put all such statements in try catch blocks?
Issue : your List is containing two kind of items CardSetterGetter and NativeExpressAdView hence you need to use List of Objects instead of any specific type because both types has no relation plus apply the casting at appropriate places
use this
public RecyclerViewAdapter(Context context, ArrayList<Object> arrayList, ArrayList<String> favouriteItemList, int totalCount) {
and use casting
cardSetterGetter =(CardSetterGetter ) arrayList.get(position);
instead of
public RecyclerViewAdapter(Context context, ArrayList<CardSetterGetter> arrayList, ArrayList<String> favouriteItemList, int totalCount) {
Also tell me what happens if this issue of casting is solved and the
arrayList returns adView where CardSetterGetter is expected or
vice-versa, Do I need to put all such statements in try catch blocks?
getItemViewType(position) is working as per position
// ITEMS_PER_AD = 8
return (position % MainActivity.ITEMS_PER_AD == 0) ? NATIVE_EXPRESS_AD_VIEW_TYPE
: MENU_ITEM_VIEW_TYPE;
mean result of position % 8 == 0 item (0,8,16,24,32...) in your list will be of NATIVE_EXPRESS_AD_VIEW_TYPE type so it's position dependent math.
The problem is in your member definition:
private ArrayList<Object> arrayList = new ArrayList<>();
It probably should be:
private ArrayList<CardSetterGetter> arrayList = new ArrayList<>();
The issue here is that ArrayList<CardSetterGetter> is not assignable to ArrayList<Object> - although CardSetterGetter (and all objects) are assignable to Object.
change arraylist initialization like this
private ArrayList<CardSetterGetter> arrayList = new ArrayList<>();
Change your ArrayList<Object> arrayList in your RecyclerViewAdapter.java
private ArrayList<Object> arrayList = new ArrayList<>();
to
private ArrayList<CardSetterGetter> arrayList = new ArrayList<>();
this will solve your problem

How to pass a class as a parameter to a method as if it were a dynamic variable?

I'm trying to pass classes depending on some conditions of where a method is being called. If a method is called in Albums, use class "album", but if is called in Artists use class "artist".
I'm still new in Java, can't seem to get hold of this.
Here's the method that's suppose to call these different classes.
private int songCounter;
public ArrayList getSongs(Context context, String type, int max, Class cls){
String select;
switch (type) {
case "albums": {
select = IS_MUSIC + " != 0 AND ALBUM NOT NULL) GROUP BY (ALBUM";
break;
}
case "artists": {
select = IS_MUSIC + " != 0 AND ARTIST NOT NULL) GROUP BY (ARTIST";
break;
}
default: {
select = IS_MUSIC + " != 0";
break;
}
}
ArrayList songList = new ArrayList();
Cursor c = context.getContentResolver().query(EXTERNAL_CONTENT_URI,null,select,null,null);
if(c!= null && c.moveToFirst()){
do {
long id = c.getLong(c.getColumnIndex(_ID));
long albumId = c.getLong(c.getColumnIndex(ALBUM_ID));
String artist = c.getString(c.getColumnIndex(ARTIST));
String album = c.getString(c.getColumnIndex(ALBUM));
String title = c.getString(c.getColumnIndex(TITLE));
songCounter++;
if (songCounter < max) {
/////// I'm having a problem here, how do I call "cls"?
songList.add(new cls(id, album, artist, title, getArt(context, albumId)));
}
}
while (c.moveToNext());
}
if (c != null) {
c.close();
}
return songList;
}
Below is a class "Album", an example of the kind of classes that needs to be called.
public class Album {
private long id;
private String title;
private String artist;
private String album;
private String year;
private String genre;
private String duration;
private BitmapDrawable art;
public Album(long songID, String songTitle, String songArtist, String songAlbum, BitmapDrawable songArt) {
id = songID;
title = songTitle;
artist = songArtist;
album = songAlbum;
art = songArt;
}
public long getID(){
return id;
}
public String getTitle(){
return title;
}
public String getArtist(){
return artist;
}
public String getAlbum(){
return album;
}
public String getDuration(){
return duration;
}
public BitmapDrawable getArt(){
return art;
}
}
And how I'm trying to call the "getSongs" method.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
super.onCreateView(inflater,container,savedInstanceState);
View rootView = inflater.inflate(R.layout.library_albums, container, false);
this.mView = rootView;
songView = (ListView) mView.findViewById(R.id.album_list);
songList = new ArrayList<Album>();
this.music = new Music();
This is where I don't know what to do also/////
songList = music.getSongs(mView.getContext(), "albums", 200, "album/artist/song class here);
AlbumAdapter songAdt = new AlbumAdapter(mView.getContext(), songList);
songView.setAdapter(songAdt);
return rootView;
}
Maybe I just need a new kind of architecture for this?
You could make
Album extends SongCollection
and
Artist extends SongCollection
In SongCollection you will have
abstract List<Song> getSongs();
and in Artist and Album you will override getSongs() returning a proper query results.
For the query you may want to have a singleton class MusicDatabase with the method List<Song> query(String queryText, String... params)
Ignoring the many alternative designs that exist for your code , and focussing on your question title alone , you could do something like this :
( This is off my head , untested code written directly into a browser, so may need tweaks to compile )
public <T extends BaseSongs> ArrayList<T> getSongs(Context context, int max, Class<T> cls){
String select;
switch (cls. getName()) {
case "Albums": {
select = IS_MUSIC + " != 0 AND ALBUM NOT NULL) GROUP BY (ALBUM";
break;
}
case "Artists": {
select = IS_MUSIC + " != 0 AND ARTIST NOT NULL) GROUP BY (ARTIST";
break;
}
default: {
select = IS_MUSIC + " != 0";
break;
}
}
ArrayList<BaseSongs> songList = new ArrayList<>(); // java 7
if (songCounter < max) {
/////// Use Reflection
Constructor ctr = cls.getConstructor(<list the types for ctr args here>);
songList.add(ctr.newInstance(id, album, artist, title, getArt(context, albumId)));
}
return songList;
The way you call your getSongs() would be :
songList = music.getSongs(mView.getContext(), 200, Albums.class);

How do I pass ArrayList to another Activity using intent?

In Activity A, I pass array using this code
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
Intent i=new Intent(getApplication(),B.class);
i.putExtra("results", results);
startActivity(i);
In Activity B, receive results
ArrayList result;
result = (ArrayList<SearchResults>)getIntent().getSerializableExtra("results");
Toast.makeText(getApplicationContext(),result+"",Toast.LENGTH_LONG).show();
SearchResult
public class SearchResults {
private String weather = "";
private String date = "";
private String status = "";
private String timeIn="";
private String timeOut="";
private String project="";
private String description="";
private String progress="";
public void setWeather(String weather) {
this.weather = weather;
}
public String getWeather() {
return weather;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public String getTimeIn() {
return timeIn;
}
public void setTimeOut(String timeOut){
this.timeOut=timeOut;
}
public String getTimeOut()
{
return timeOut;
}
public void setProject(String project){
this.project=project;
}
public String getProject()
{
return project;
}
public void setProgress(String progress){
this.progress=progress;
}
public String getProgress()
{
return progress;
}
public void setDescription(String description){
this.description=description;
}
public String getDescription()
{
return description;
}
}
Error LogCat
Process: com.example.project.myapplication, PID: 2698
java.lang.RuntimeException: Parcel: unable to marshal value com.example.project.myapplication.bean.SearchResults#94c2757
at android.os.Parcel.writeValue(Parcel.java:1397)
at android.os.Parcel.writeList(Parcel.java:738)
at android.os.Parcel.writeValue(Parcel.java:1344)
And this line
startActivity(i);
How do I use serializable for passing bean objects and also make the bean class implements serializable ? Thanks a lot.
In the same activity, I want the results saved to database.
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WD.insertWorkDetails(result,a); //a is pass from Activtity a too
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Toast.makeText(getApplication(),"DONE",Toast.LENGTH_LONG).show();
}
});
WorkDetails
public long insertWorkDetails(ArrayList<SearchResults> listItems, long id)
{
database=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
for(SearchResults s:listItems) {
String Project = s.getProject();
String temp = s.getDescription();
String[] ReceiveDescription = temp.split(":");
String Progress = s.getProgress();
String[] ReceiveProgress = Progress.split(":");
String TimeIn = s.getTimeIn();
String[] ReceiveTimeIn = TimeIn.split(":");
String TimeOut = s.getTimeOut();
String[] ReceiveTimeOut = TimeOut.split(":");
values.put(MyDatabaseHelper.Project,Project);
values.put(MyDatabaseHelper.WorkDescription,ReceiveDescription[1]);
values.put(MyDatabaseHelper.Percentage,ReceiveProgress[1]);
values.put(MyDatabaseHelper.TimeIn,ReceiveTimeIn[1]);
values.put(MyDatabaseHelper.TimeOut,ReceiveTimeOut[1]);
values.put("Twd_id",id);
database.insert(MyDatabaseHelper.TABLE_WORKDETAILS, null, values);
}
database.close();
return 0 ;
}
When I check my db, no listView item is added.
java.lang.RuntimeException: Parcel: unable to marshal value
com.example.project.myapplication.bean.SearchResults#94c2757
you are using getSerializableExtra to retrieve your ArrayList. This implies that SearchResults implements Serializable which is not the case. If you want an easy fix just let SearchResults implement the Serializable interface. In the case of SearchResults serialization will work out of the box. Or you could learn about Parcelable (read more about it here) and use it instead of Serializable. If you don't need to save the objects on your permanent storage, Parcelable is way more efficient than Serializable

Instance of class in Java can't be tested for null

I'm trying to troubleshoot a null-pointer exception that keeps me from populating an array adapter. I've traced it down to the point at which I create an instance of the class, and so to try to troubleshoot, I created the following toast:
private void showSplits() {
// populate the split line
Split s = new Split();
s = mTransaction.getSplit();
int duration = Toast.LENGTH_SHORT;
if (s != null) {
Toast toast = Toast.makeText(getActivity(), s.getCategory(), duration);
Toast toast2 = Toast.makeText(getActivity(), s.getDescription(), duration);
Toast toast3 = Toast.makeText(getActivity(), s.getAmount(), duration);
toast.show();
toast2.show();
toast3.show();
} else {
Toast toast4 = Toast.makeText(getActivity(), "S was null.", duration);
toast4.show();
}
....
}
When run, the result of this method is to neatly print out the content of each field of the split, then neatly print out "S was null." I've verified that I'm calling the method only once, so I can't see how s could both be null and not null.
Here's the detail of the class...
public class Split implements Serializable {
private static final long serialVersionUID = 1L;
private static final String JSON_CATEGORY = "category";
private static final String JSON_AMOUNT = "amount";
private static final String JSON_DESCRIPTION = "description";
private UUID mId;
private String mCategory;
private String mAmount;
private String mDescription;
public Split(String category, String amount, String description) {
mCategory = category;
mAmount = amount;
mDescription = description;
}
public Split() {
mId = UUID.randomUUID();
mCategory = "none";
}
public Split(JSONObject json) throws JSONException {
if (json.has(JSON_CATEGORY)) {
mCategory = json.getString(JSON_CATEGORY);
}
if (json.has(JSON_AMOUNT)) {
mAmount = json.getString(JSON_AMOUNT);
}
if (json.has(JSON_DESCRIPTION)) {
mDescription = json.getString(JSON_DESCRIPTION);
}
}
public JSONObject toJSON() throws JSONException {
JSONObject json = new JSONObject();
// if (mCategory != null) {
json.put(JSON_CATEGORY, mCategory);
// }
// if (mAmount != null) {
json.put(JSON_AMOUNT, mAmount);
// }
// if (mDescription != null) {
json.put(JSON_DESCRIPTION, mDescription);
// }
return json;
}
// Factory method to convert an array of JSON objects into a list of objects
// User.fromJson(jsonArray);
public static ArrayList<Split> fromJson(JSONArray jsonObjects) {
ArrayList<Split> splits = new ArrayList<Split>();
for (int i = 0; i < jsonObjects.length(); i++) {
try {
splits.add(new Split(jsonObjects.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
return splits;
}
public String getCategory() {
return mCategory;
}
public void setCategory(String category) {
mCategory = category;
}
public String getAmount() {
return mAmount;
}
public void setAmount(String amount) {
mAmount = amount;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String description) {
mDescription = description;
}
}
To the best of my abilities to tell, showSplits is called only once in the fragment I'm working in.
In the first line you are referencing s variable to a new Split Object, And in the second line you are changing the reference of s to mTransaction.getSplit(). If the object is returned by mTransaction.getSplit() is null then your s will reference to null. Means value of s will be null.
Split s = new Split();
s = mTransaction.getSplit();
your mTransaction.getSplit() may be returning null value , Try to debug it

Categories

Resources