Constructor ClipData.Item is undefined Android - java

im trying to create a item for a list, to display on a listview some pictures.
The codes is the following:
public static List<Item> getItemList(List<Picture> pictures, Context context)
{
List <Item> items = new ArrayList<Item>();
for (int i = 0; i < pictures.size(); i++) {
Item item = new Item(pictures.get(i).getID(),pictures.get(i).getAddress(),pictures.get(i).getDescription(),pictures.get(i).getPath());
items.add(item);
}
return items;
}
What i'm trying to do in this is to create an item for each picture on database. (getDescription would be to get the picture description from a database handler, same for address and path)
However im getting the following error in the line where i use the "gets"
The constructor ClipData.Item(int, String, String, String) is undefined.
What could this be? Thank you!
Picture Class
public class Picture {
int _id;
String _name;
String _address;
String _description;
String _path;
// Empty constructor
public Picture(){
}
// constructor
public Picture(int id, String name, String _address, String _description, String _path){
this._id = id;
this._name = name;
this._address = _address;
this._description = _description;
this._path = _path;
}
// constructor
public Picture(String name, String _address, String _description){
this._name = name;
this._address = _address;
this._description = _description;
this._path = _path;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
public void setDescription(String description){
this._description = description;
}
public String getDescription(){
return this._description;
}
// getting phone number
public String getAddress(){
return this._address;
}
// setting phone number
public void setAddress(String phone_number){
this._address = phone_number;
}
public String getPath(){
return this._path;
}
public void setPath(String path){
this._path = path;
}
}

try to use for each loop
public static List<Item> getItemList(List<Picture> pictures, Context context)
{
List <Item> items = new ArrayList<Item>();
for (Picture pic:pictures) {
int id = pic.getID();
String address = pic.getAddress();
String desc= pic.getDescription();
String path= pic.getPath();
Item item = new Item(id ,address ,desc,path);
items.add(item);
}
return items;
}

Related

in php, how to retrieve an objects array sent by retrofit

In my android app, with retrofit, I want to send an array of objects to my php script with:
#FormUrlEncoded
#POST(Consts.BACKUP_SCRIPT_UP)
Call<Integer> backupUpload(
#Field("deviceName") String deviceName,
#Field("articles[]") List<backupArticle> articles
);
But, I don't find the way to retrieve my datas.
I get deviceName as attended but how to retrieve datas in the array $_REQUEST["articles"] please?
Dump gives something like:
Array (
[deviceName] => 7cdb101d51bb89ca
[articles] => Array
(
[0] => myapp.backupArticle#f3ee606
[1] => myapp.backupArticle#681f4c7
[2] => myapp.backupArticle#6d40af4
[3] => myapp.backupArticle#57321d
[4] => myapp.backupArticle#5d35c92
...
)
)
But I don't really know if my problem is about java/android or php. I'd like to be sure what I send is really what I want to send, but how to test it if I can't retrieve information in php?
I also tried with:
#POST(Consts.BACKUP_SCRIPT_UP)
Call<Integer> backupUpload(
#Body List<backupArticle> articles
);
but I get empty array in php.
java object Class:
public class backupArticle {
#SerializedName("deviceName") #Expose private String deviceName;
#SerializedName("clistName") #Expose private String clistName;
#SerializedName("name") #Expose private String name;
#SerializedName("ord") #Expose private long ord;
#SerializedName("categName") #Expose private String categName;
#SerializedName("categOrd") #Expose private long categOrd;
#SerializedName("qty") #Expose private int qty;
#SerializedName("selected") #Expose private int selected;
public backupArticle(String deviceName, String clistName, String name, long ord, String categName, long categOrd, int qty, int selected) {
this.deviceName = deviceName;
this.clistName = clistName;
this.name = name;
this.ord = ord;
this.categName = categName;
this.categOrd = categOrd;
this.qty = qty;
this.selected = selected;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getClistName() {
return clistName;
}
public void setClistName(String clistName) {
this.clistName = clistName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getOrd() {
return ord;
}
public void setOrd(long ord) {
this.ord = ord;
}
public String getCategName() {
return categName;
}
public void setCategName(String categName) {
this.categName = categName;
}
public long getCategOrd() {
return categOrd;
}
public void setCategOrd(long categOrd) {
this.categOrd = categOrd;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public int getSelected() {
return selected;
}
public void setSelected(int selected) {
this.selected = selected;
}
}
In fact, it seems that the right way is to NOT use $_REQUEST (or $_POST) but (php):
$articles = json_decode(file_get_contents('php://input'));
$deviceName = $articles[0]->deviceName;
with (java/retrofit):
#POST(Consts.BACKUP_SCRIPT_UP)
Call<Integer> backupUpload(
#Body List<backupArticle> articles
);

Storing an arraylist of custom objects (which have Strings, Dates, Lists, and more as fields) in shared preferences

I am trying to save an arraylist of clients in shared preferences, however I am getting out of memory error. I am new to this and can't figure out how to do this? I looked at a lot of pages on stackoverflow, but couldn't find one that would work for me or that also had an ArrayList of custom objects, where every object contains more ArrayLists with custom objects.
client object:
public class Client implements Serializable, Comparable<Client> {
private int clientID;
private String name;
private String phone;
private String email;
private String url;
private Double turnover;
private String visitAddress;
private String visitCity;
private String visitZipcode;
private String visitCountry;
private String postalAddress;
private String postalCity;
private String postalZipcode;
private String postalCountry;
private Drawable clientImage;
private List<Contact> contactList = new ArrayList<Contact>();
private List<Project> projectList = new ArrayList<Project>();
private List<Task> taskList = new ArrayList<Task>();
private List<Order> orderList = new ArrayList<Order>();
public Client(int clientID, String Name, String Phone, String Email, String URL, Double Turnover,
String VisitAddress, String VisitCity, String VisitZipcode, String VisitCountry,
String PostalAddress, String PostalCity, String PostalZipcode, String PostalCountry,
List contactList, List projectList, List taskList, List orderList){
super();
this.clientID = clientID;
this.name = Name;
this.phone = Phone;
this.email = Email;
this.url = URL;
this.turnover = Turnover;
this.visitAddress = VisitAddress;
this.visitCity = VisitCity;
this.visitZipcode = VisitZipcode;
this.visitCountry = VisitCountry;
this.postalAddress = PostalAddress;
this.postalCity = PostalCity;
this.postalZipcode = PostalZipcode;
this.postalCountry = PostalCountry;
this.contactList = contactList;
this.projectList = projectList;
this.taskList = taskList;
this.orderList = orderList;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
public String getEmail() {
return email;
}
public String getUrl() {
return url;
}
public Double getTurnover() {
return turnover;
}
public String getVisitAddress() {
return visitAddress;
}
public String getVisitCity() {
return visitCity;
}
public String getVisitZipcode() {
return visitZipcode;
}
public String getVisitCountry() {
return visitCountry;
}
public String getPostalAddress() {
return postalAddress;
}
public String getPostalCity() {
return postalCity;
}
public String getPostalZipcode() {
return postalZipcode;
}
public String getPostalCountry() {
return postalCountry;
}
public List<Contact> getContactList(){
return contactList;
}
public List<Project> getProjectList(){
return projectList;
}
public List<Task> getTaskList(){
return taskList;
}
public List<Order> getOrderList() {
return orderList;
}
public void setName(String name) {
this.name = name;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setEmail(String email) {
this.email = email;
}
public void setUrl(String url) {
this.url = url;
}
public void setTurnover(Double turnover) {
this.turnover = turnover;
}
public void setVisitAddress(String visitAddress) {
this.visitAddress = visitAddress;
}
public void setVisitCity(String visitCity) {
this.visitCity = visitCity;
}
public void setVisitZipcode(String visitZipcode) {
this.visitZipcode = visitZipcode;
}
public void setVisitCountry(String visitCountry) {
this.visitCountry = visitCountry;
}
public void setPostalAddress(String postalAddress) {
this.postalAddress = postalAddress;
}
public void setPostalCity(String postalCity) {
this.postalCity = postalCity;
}
public void setPostalZipcode(String postalZipcode) {
this.postalZipcode = postalZipcode;
}
public void setPostalCountry(String postalCountry) {
this.postalCountry = postalCountry;
}
public Drawable getClientImage() {
return clientImage;
}
public void setClientImage(Drawable clientImage) {
this.clientImage = clientImage;
}
public int getClientID() {
return clientID;
}
public void setClientID(int clientID) {
this.clientID = clientID;
}
underlying project object: (also with list of custom objects)
public class Project implements Serializable, Comparable<Project>{
private String clientName;
private String projectName;
private String projectDiscription;
private String projectStatus;
private GregorianCalendar projectDate;
private List<TimeSheet> projectTimeRegestrationList = new ArrayList<>();
private List<WorkOrder> workOrderList = new ArrayList<WorkOrder>();
public Project(String clientName, String projectName, String projectDiscription, String projectStatus, GregorianCalendar projectDate, List projectTimeRegestrationList, List workOrderList) {
this.projectName = projectName;
this.projectDiscription = projectDiscription;
this.projectStatus = projectStatus;
this.projectDate = projectDate;
this.clientName = clientName;
this.projectTimeRegestrationList = projectTimeRegestrationList;
this.workOrderList = workOrderList;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectDiscription() {
return projectDiscription;
}
public void setProjectDiscription(String projectDiscription) {
this.projectDiscription = projectDiscription;
}
public String getProjectStatus() {
return projectStatus;
}
public void setProjectStatus(String projectStatus) {
this.projectStatus = projectStatus;
}
public GregorianCalendar getProjectDate() {
return projectDate;
}
public void setProjectDate(GregorianCalendar projectDate) {
this.projectDate = projectDate;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public List<TimeSheet> getProjectTimeRegestrationList() {
return projectTimeRegestrationList;
}
public List<WorkOrder> getWorkOrderList() {
return workOrderList;
}
now my specific question: is it possible to save this inside shared preferences, if yes, how do i do this, if no, how should i then locally safe this data.
you can use json to store them as a string in sharedpreference
for example if you want to store an object of your client class contaning a url ,country and phone
just write the following
try {
JSONArray jsonArray=new JSONArray();
JSONObject object1=new JSONObject();
object1.put("url","myurl");
object1.put("phone","myphonenumber");
object1.put("country","mycountry");
jsonArray.put(object1);
//adding another object
JSONObject object2=new JSONObject();
object2.put("url","anotherurl");
object2.put("phone","anotherphonenumber");
object2.put("country","anothercountry");
jsonArray.put(object2);
} catch (JSONException e) {
e.printStackTrace();
}
and than simply save it as a string by calling jsonArray.toString() in sharedpreference
and if your object that you want to store contains a list of another object you can easily save like for example if you have a url, country, and phone number which you want to save plus a list of another object containing the first and lastname you can save list as json object itself just like you did for the url,phone number and country as shown below
try {
JSONArray jsonArray=new JSONArray();
JSONObject object1=new JSONObject();
object1.put("url","myurl");
object1.put("phone","myphonenumber");
object1.put("country","mycountry");
//saving a list of another object contaning firstname and lastname
JSONArray listArray=new JSONArray();
//supposing your list contains 10 objects
for(int f=0;f<10;f++){
JSONObject listobject=new JSONObject();
listobject.put("firstname","myfirstname");
listobject.put("lastname","mylastname");
listArray.put(listobject);
}
//now the list array we added as an object of the jsonArray variable
JSONObject object2=new JSONObject(); //object2 containing the list of firstname and lastname
object2.put("list",listArray.toString());
jsonArray.put(object1);//object1 contains the url, phone, and country
jsonArray.put(object2);//object2 contains the list of firstname and lastname
} catch (JSONException e) {
e.printStackTrace();
}

java.lang.IndexOutOfBoundsException: Invalid index 18, size is 18 [duplicate]

This question already has answers here:
Java - IndexOutOfBoundsException: Index: 1, Size: 0
(1 answer)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
int i = 0; //used for getting item position
for (Iterator<CustomObject> iterator = mAdapter.getItemsData().iterator(); iterator.hasNext();) {
if (mAdapter.getItemsData().get(i).getPriceTier() != 1) { //if statement throws error
// Remove the current element from the iterator and the list.
iterator.remove();
mAdapter.removeFromItemsData(i);
}
i++;
}
Using this stackoverflow answer, I iterate through my arraylist of CustomObject. Custom object is just a POJO class with setters and getters. The setters and getters have different data types, such as int, String, double etc.
mAdapter.getItemsData returns the araylist from the adapter class.
//method just notifies the RecyclerView that an item was removed.
public void removeFromItemsData(int position){
notifyItemRemoved(position);
}
Here is the exception
java.lang.IndexOutOfBoundsException: Invalid index 18, size is 18
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308) at
com.test.TestActivity$5.onClick(TestActivity.java:280) at
android.view.View.performClick(View.java:4780) at
android.view.View$PerformClick.run(View.java:19866) at
android.os.Handler.handleCallback(Handler.java:739) at
android.os.Handler.dispatchMessage(Handler.java:95) at
android.os.Looper.loop(Looper.java:135) at
android.app.ActivityThread.main(ActivityThread.java:5254) at
java.lang.reflect.Method.invoke(Native Method) at
java.lang.reflect.Method.invoke(Method.java:372) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
CustomObject class
public class CustomObject{
private String name;
private int distance;
private String category;
private String id;
private double rating;
private String ratingColor;
private String prefix;
private String suffix;
private int priceTier;
private String currency;
private String phone;
private String twitter;
private String url;
private String menu;
String address;
String city;
String state;
String postalCode;
double lat;
double lng;
String review;
int reviewCount;
String firstName;
String lastName;
String userIconPrefix;
String userIconSuffix;
String secondsReview;
public CustomObject() {
this.name = "";
this.distance = 0;
this.setCategory("");
this.id = "";
this.rating = 0;
this.ratingColor = "";
this.prefix = "";
this.suffix = "";
this.priceTier = 0;
this.currency = "";
this.phone = "";
this.twitter = "";
this.url = "";
this.menu = "";
this.address = "";
this.city = "";
this.state = "";
this.postalCode = "";
this.lat = 0;
this.lng = 0;
this.review = "";
this.reviewCount = 0;
this.firstName = "";
this.lastName = "";
this.userIconPrefix = "";
this.userIconSuffix = "";
this.secondsReview = "";
}
public void setSecondsReview(String secondsReview){
this.secondsReview = secondsReview;
}
public String getSecondsReview(){
return secondsReview;
}
public void setUserIconSuffix(String userIconSuffix){
this.userIconSuffix = userIconSuffix;
}
public String getUserIconSuffix(){
return userIconSuffix;
}
public void setUserIconPrefix(String userIconPrefix){
this.userIconPrefix = userIconPrefix;
}
public String getUserIconPrefix(){
return userIconPrefix;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getFirstName(){
return firstName;
//todo if String firstNAme == null, then return "a foursquare user"
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String getLastName(){
return lastName;
}
public void setReviewCount(int reviewCount){
this.reviewCount = reviewCount;
}
public int getReviewCount(){
return reviewCount;
}
public void setReview(String review){
this.review = review;
}
public String getReview(){
return review;
}
public void setLng(double lng){
this.lng = lng;
}
public double getLng(){
return lng;
}
public void setLat(double lat){
this.lat = lat;
}
public double getLat(){
return lat;
}
public void setPostalCode(String postalCode){
this.postalCode = postalCode;
}
public String getPostalCode(){
return postalCode;
}
public void setState(String state){
this.state = state;
}
public String getState(){
return state;
}
public void setCity(String city){
this.city = city;
}
public String getCity(){
return city;
}
public void setAddress(String address){
this.address = address;
}
public String getAddress(){
return address;
}
public void setMenuUrl(String menu){
this.menu = menu;
}
public String getMenuUrl(){
return menu;
}
public void setUrl(String url){
this.url = url;
}
public String getUrl(){
return url;
}
public void setTwitter(String twitter){
this.twitter = twitter;
}
public String getTwitter(){
return twitter;
}
public void setPhone(String phone){
this.phone = phone;
}
public String getPhone(){
return phone;
}
public String getCurrency(){
return currency;
}
public void setCurrency(String currency){
this.currency = currency;
}
public int getPriceTier(){
return priceTier;
}
public void setPriceTier(int priceTier){
this.priceTier = priceTier;
}
public String getSuffix(){
return suffix;
}
public void setSuffix(String suffix){
this.suffix = suffix;
}
public String getPrefix(){
return prefix;
}
public void setPrefix(String prefix){
this.prefix = prefix;
}
public double getRating(){
if(rating > 0){
return rating;
}
return 0; //TODO display symbol if rating not found
}
public void setRating(double rating){
this.rating = rating;
}
public Integer getDistance() {
if (distance >= 0) {
return distance;
}
return 0; //TODO display symbol if distance not found, like N/A
}
public void setDistance(int distance) {
this.distance = distance;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
How data is added
In onCreate of activity, I instantiate Recyclerview. RecyclerView takes an arraylist, so I pass an empty one.
List listTitle = new ArrayList(); //empty arraylist
mAdapter = new Fragment1Adapter(listTitle);
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
Later on in an AsyncTask, I add the items to the Adapter.
for (int i = 0; i < jsonArray.length(); i++) {
CustomObject poi = new CustomObject ();
if (jsonArray.getJSONObject(i).has("venue")) {
poi.setName(jsonArray.getJSONObject(i).getJSONObject("venue").getString("name"));
poi.setId(jsonArray.getJSONObject(i).getJSONObject("venue").getString("id"));
}
mAdapter.addItem(poi);
}
Here is the addItem class
Declared at top of adapter class private final List<FoursquareVenue> itemsData;
public void addItem(FoursquareVenue data) {
itemsData.add(data);
notifyItemInserted(itemsData.size() - 1);
}
Edit
Since you our chat and your edits:
You need to add and remove the items to your ArrayList and them notify adapter of change.
CustomObject poi = new CustomObject ();
if (jsonArray.getJSONObject(i).has("venue")) {
poi.setName(jsonArray.getJSONObject(i).getJSONObject("venue").getString("name"));
poi.setId(jsonArray.getJSONObject(i).getJSONObject("venue").getString("id"));
}
listTitle.addItem(poi);// Add to ListArray
Then loop through your ArrayList to remove items.
You've just muddled yourself up a bit in how you are trying to access your data.
There is a problem that you are creating an iterator of CustomObjects, and parsing it to the data type of mAdapter.getItemsData().
Removing the element from the iterator should remove it from the list.
for (Iterator<CustomObject> iterator = mAdapter.iterator(); iterator.hasNext();) {
CustomObject itemsData = iterator.next();
if (itemsData.getItemsData().get(i).getPriceTier() != 1) { //if statement throws error
// Remove the current element from the iterator and the list.
iterator.remove();
}
i++;
}
CustomObject itemsData = iterator.next();
Let me know if this helps.

Pass List with custom object to another activity android

I have a List<News> new ArrayList<News>(); I need to pass this list to another activity and retrieve object from it to assign it to String values.
News.java
public class News
{
String title;
String description;
String thumbnail;
String newsUrl;
String body;
String newsBigImage ;
String newsComments ;
String newsViews;
String publishedDate;
String articleGuid;
String newsSourceId;
String newsId ;
String publisherName;
String newsSourceTitle;
String color;
News(String title, String description, String thumbnail, String newsUrl, String body, String newsBigImage, String newsComments, String newsViews,
String publishedDate,
String articleGuid,
String newsSourceId,
String newsId ,
String publisherName,
String newsSourceTitle )
{
this.title = title;
this.description = description;
this.articleGuid =articleGuid;
this.thumbnail = thumbnail;
this.newsUrl = newsUrl;
this.body = body;
this.newsBigImage = newsBigImage;
this.newsComments = newsComments;
this.newsViews = newsViews;
this.publishedDate = publishedDate;
this.newsId = newsId;
this.newsSourceId = newsSourceId;
this.publisherName = publisherName;
//this.color = color;
this.newsSourceTitle =newsSourceTitle;
}
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 String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getNewsUrl() {
return newsUrl;
}
public void setNewsUrl(String newsUrl) {
this.newsUrl = newsUrl;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getNewsBigImage() {
return newsBigImage;
}
public void setNewsBigImage(String newsBigImage) {
this.newsBigImage = newsBigImage;
}
public String getNewsComments() {
return newsComments;
}
public void setNewsComments(String newsComments) {
this.newsComments = newsComments;
}
public String getNewsViews() {
return newsViews;
}
public void setNewsViews(String newsViews) {
this.newsViews = newsViews;
}
public String getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(String publishedDate) {
this.publishedDate = publishedDate;
}
public String getArticleGuid() {
return articleGuid;
}
public void setArticleGuid(String articleGuid) {
this.articleGuid = articleGuid;
}
public String getNewsSourceId() {
return newsSourceId;
}
public void setNewsSourceId(String newsSourceId) {
this.newsSourceId = newsSourceId;
}
public String getNewsId() {
return newsId;
}
public void setNewsId(String newsId) {
this.newsId = newsId;
}
public String getPublisherName() {
return publisherName;
}
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
public String getNewsSourceTitle() {
return newsSourceTitle;
}
public void setNewsSourceTitle(String newsSourceTitle) {
this.newsSourceTitle = newsSourceTitle;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
I pass values like:-
myNewsList.add(new News(title, description, thumbnail, newsUrl, body, newsBigImage, newsComments, newsViews, publishedDate, articleGuid, newsSourceId, newsId, publisherName, newsSourceTitle));
Then I pass this list to an ListAdapter to show it in a ListView.
itemsAdapter = new LazyAdapter(myContext, myNewsList);
newsList.setAdapter(itemsAdapter);
Now, When the user clicks a listview item, I want to pass the myNewsList to the new activity and retrieve items from it and assign it to another Strings in that class.
ewsList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0,
View arg1, int position, long arg3)
{
// TODO Auto-generated method stub
myDialog = new ProgressDialog(myContext).show(getActivity(), "Fetching news..", "Just a moment");
//News myMap = myNewsList.get(position);
Intent newsIntent = new Intent(getActivity(),NewsDetails.class);
startActivity(newsIntent);
How can I do this??
implements a parcelable interface so your class will look like
public class News implements Parcelable {
String title;
String description;
String thumbnail;
String newsUrl;
String body;
String newsBigImage ;
String newsComments ;
String newsViews;
String publishedDate;
String articleGuid;
String newsSourceId;
String newsId ;
String publisherName;
String newsSourceTitle;
String color;
protected News(Parcel in) {
title = in.readString();
description = in.readString();
thumbnail = in.readString();
newsUrl = in.readString();
body = in.readString();
newsBigImage = in.readString();
newsComments = in.readString();
newsViews = in.readString();
publishedDate = in.readString();
articleGuid = in.readString();
newsSourceId = in.readString();
newsId = in.readString();
publisherName = in.readString();
newsSourceTitle = in.readString();
color = in.readString();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(description);
dest.writeString(thumbnail);
dest.writeString(newsUrl);
dest.writeString(body);
dest.writeString(newsBigImage);
dest.writeString(newsComments);
dest.writeString(newsViews);
dest.writeString(publishedDate);
dest.writeString(articleGuid);
dest.writeString(newsSourceId);
dest.writeString(newsId);
dest.writeString(publisherName);
dest.writeString(newsSourceTitle);
dest.writeString(color);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<News> CREATOR = new Parcelable.Creator<News>() {
#Override
public News createFromParcel(Parcel in) {
return new News(in);
}
#Override
public News[] newArray(int size) {
return new News[size];
}
};
}
and you can pass now this in intent extra like
intent.putExtra("newsObject", obj);
and for passing arraylist do Intent.putParcelableArrayListExtra("newsList", arr);
and in next activity get like
News news = (News)intent.getParcelableExtra("newsObject");
and for getting arraylist do
ArrayList<News> news = (ArrayList<News>)intent.getParcelableArrayListExtra("newsList");
Use Seriazable or Parceable interface implementation for this.
In NewsDetails class just you want to show the description so call getters method of model class and show there, or else follow above solution
first, create a getter method to retreive your object in adapter.. returning your List then you call your getter in your activity, then you create your intent.

I Can't Update table with ormlite android

The problem is that I have a table product and my update script doesn't work aparently. It allwas return false.
Product.class
#DatabaseTable(tableName = "Product")
public class Product {
#DatabaseField(index = true, generatedId = true)
private int productId;
#DatabaseField
private String name;
#DatabaseField
private int quantity;
//#DatabaseField(canBeNull = true)
//private Integer categorie;
//http://logic-explained.blogspot.com.ar/2011/12/using-ormlite-in-android-projects.html
#DatabaseField
private int categorie;
//#ForeignCollectionField
//private ForeignCollection<Categorie> itemsCategorie;
#DatabaseField
private String description;
#DatabaseField
private String photo;
Product() {
}
public Product(int productId, String name, int quantity, int categorie, String description, String photo) {
super();
this.productId = productId;
this.name = name;
this.quantity = quantity;
this.categorie = categorie;
this.description = description;
this.photo = photo;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return description;
}
public void setAddress(String address) {
this.description = address;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getCategorie() {
return categorie;
}
public void setCategorie(int categorie) {
this.categorie = categorie;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public CharSequence getDesc() {
return null;
}
}
my script updateProduct
public boolean updateProduct(Product p) {
boolean ret = false;
if (productDao != null) {
try {
productDao = getDao(Product.class);
UpdateBuilder<Product, Integer> updateBuilder = productDao
.updateBuilder();
updateBuilder.updateColumnValue("name", p.getName());
updateBuilder.updateColumnValue("quantity", p.getQuantity());
updateBuilder.updateColumnValue("categorie", p.getCategorie());
updateBuilder.updateColumnValue("description", p.getDesc());
updateBuilder.updateColumnValue("photo", p.getPhoto());
// but only update the rows where the description is some value
updateBuilder.where().eq("productId", p.getProductId());
// actually perform the update
String str = updateBuilder.prepareStatementString();
// UPDATE `Product` SET `name` = 'gcd' ,`quantity` = 1
// ,`categorie` = 1 ,`description` = ? ,`photo` = '' WHERE
// `productId` = 0
if (productDao.update(updateBuilder.prepare()) != 1) {
ret = false;
} else {
productDao.refresh(p);
ret = true;
}
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
then I call it with a function like this, but allways return false :(
public boolean updateProduct(Product p) {
boolean ret = false;
try {
ret = getHelper().updateProduct(p);
} catch (Exception e) {
e.printStackTrace();
ret =false;
}
return ret;
}
I can create and delete but I can not update . I tried everything.
If you please take a moment to answer my question I will appreciate.
for other developers, if you come face to face with a problem like this you should ensure the table must have an identity key.
#DatabaseTable(tableName = "User")
public class User {
#DatabaseField(generatedId = true)
public int id;
#DatabaseField
public String ServiceUserId;
#DatabaseField
public boolean IsActive;
#DatabaseField
public String FirstName;
#DatabaseField
public String LastName;
#DatabaseField
public String Key;
#DatabaseField
public String Email;
}
The solution was
Simply get the Instance of the object Product from the DB then modify to finaly send to the updateProduct method.
for example first I need to create any method first to get an objet by ID
// get the Instance calling to the getProductByID
Product p = getHelper().getProductByID(p.getId())
//modify any value of the product
p.setFirstName("asd");
//call the update
ret = getHelper().updateProduct(p);
then my objects is Updated.
Put attention for the object Id(should be the same) and use the natif function update(Product);
In your case, you must override equals and hashCode.

Categories

Resources