It seems that I don't understand inheritance.
I have these classes : PicaAsset, VideoAsset that inherit from a class names Assets.
This is the Assets class declaration :
public class Assets {
protected int book=0;
protected int fromChapter=0;
protected int toChapter=0;
protected int fromVerse=0;
protected int toVerse=0;
protected String creator=null;
protected String discription=null;
protected String source=null;
protected String title=null;
protected String duration=null;
protected String url=null;
public Assets(int book, int fromChapter, int toChapter, int fromVerse,
int toVerse, String creator, String discription, String source,
String title, String duration, String url) {
this.book = book;
this.fromChapter = fromChapter;
this.toChapter = toChapter;
this.fromVerse = fromVerse;
this.toVerse = toVerse;
this.creator = creator;
this.discription = discription;
this.source = source;
this.title = title;
this.duration = duration;
this.url = url;
}
public Assets() {
}
public int getBook() {
return book;
}
public void setBook(int book) {
this.book = book;
}
public int getFromChapter() {
return fromChapter;
}
public void setFromChapter(int fromChapter) {
this.fromChapter = fromChapter;
}
public int getToChapter() {
return toChapter;
}
public void setToChapter(int toChapter) {
this.toChapter = toChapter;
}
public int getFromVerse() {
return fromVerse;
}
public void setFromVerse(int fromVerse) {
this.fromVerse = fromVerse;
}
public int getToVerse() {
return toVerse;
}
public void setToVerse(int toVerse) {
this.toVerse = toVerse;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
PicAsset :
public class PicAsset extends Assets implements IsSerializable {
private int picId=0;
public PicAsset(){
}
public PicAsset(int picId, int book, int fromChapter, int toChapter,
int fromVerse, int toVerse, String creator, String discription,
String source, String title, String duration, String url) {
super( book, fromChapter, toChapter,
fromVerse, toVerse, creator, discription,
source, title, duration, url);
this.picId = picId;
}
public int getIdpic() {
return picId;
}
public void setIdpic(int idpic) {
this.picId = idpic;
}
}
Now I use an RPC call to use methods declared in the server side to get info from my datbase, as you can see the method return a List of PicAsset , List.
rpcService.getPicture((books.getSelectedIndex()+1), (chapters.getSelectedIndex()+1), new AsyncCallback<List<PicAsset>>(){
public void onFailure(Throwable caught) {
Window.alert("Can't connect to database" + books.getSelectedIndex() + chapters.getSelectedIndex());
}
public void onSuccess(List<PicAsset> result) {
int listSize = result.size();
int i;
int flag = 0;
assetPicPanel.clear();
Label frameTitle = new Label("Pictures");
for(i=0;i<listSize;i++)
{
if(flag == 0)
{
assetPicPanel.add(frameTitle);
flag = 1;
}
HorizontalPanel vPanelPic = new HorizontalPanel();
System.out.print("heeeeey" +" " + result.get(i).getFromChapter());
Grid g = result.get(i).AssetGrid(result.get(i));
vPanelPic.add(g);
assetPicPanel.add(vPanelPic);
}
}
});
Now when I print the ..get().getFromChapter() on the server side it brings the right values.
But when I print the values that have been returned to the RPC call I get the default constructor values... and not what have to be sent back.
Here also the getPicture implementation on the server side :
public List<PicAsset> getPicture(int book, int chapter) throws Exception
{
System.out.print("getPicture ok " + book +"," + chapter);
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet result = null;
List<PicAsset> relevantAssets = new ArrayList<PicAsset>();
PicAsset relAsset;
try {
conn = getConnection();
pstmt = conn.prepareStatement("SELECT * FROM picasset WHERE book = ? AND fromChapter <= ? AND toChapter >= ?");
//System.out.print("connection" + conn);
pstmt.setInt(1, book);
pstmt.setInt(2, chapter);
pstmt.setInt(3, chapter);
result = pstmt.executeQuery();
// System.out.print(result);
while (result.next()) {
//System.out.print("in while");
relAsset = new PicAsset(result.getInt("picId"),result.getInt("book"), result.getInt("fromChapter"), result.getInt("toChapter"),result.getInt("fromVerse"),result.getInt("toVerse"),result.getString("creator"),result.getString("discription"),result.getString("source"),result.getString("title"),result.getString("duration"),result.getString("url"));
relevantAssets.add(relAsset);
}
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
finally
{
// Cleanup
result.close();
pstmt.close();
conn.close();
}
System.out.print("In MySql get Chapter " + relevantAssets.get(0).getFromChapter() + " " + relevantAssets.get(0).getIdpic());
return relevantAssets;
}
Within GWT RPC it would be much better to use raw arrays rather than collection interfaces - return from your method PicAsset[] instead of List. This will allow you (a) solve your problem and (b) escape unnecessary classes to be compiled into client code.
See "Raw Types" section at gwtproject.org
Related
I'm trying to get the data from the arrayBundlePack after getting data from enqueue call, I'm trying to use BufferedWriter to the saved data in the arrayBundlePack & write in the txt file, but it just won't get the output I wanted.
I'm not sure if that's the way to output an arrayList model class.
Here's the code
private ArrayList<BundlePack> arrayBundlePack;
Call<BundlePackRepo> call = .............. // api content
call.enqueue(new Callback<BundlePackRepo>() {
#Override
public void onResponse(Call<BundlePackRepo> call, retrofit2.Response<BundlePackRepo> response) {
if (response.isSuccessful()) {
BundlePackRepo repos = response.body();
BundlePackRepo.bundlepacks[] bundlePacksarray;
bundlePacksarray = repos.getBundlePacks();
BundlePack bundlePack;
for (int a = 0; a < bundlePacksarray.length; a++) {
bundlePack = new BundlePack();
bundlePack.setPromotion_kit(bundlePacksarray[a].getPromotion_kit());
bundlePack.setStock_code(bundlePacksarray[a].getStock_code());
bundlePack.setIssue_ref(bundlePacksarray[a].getIssue_ref());
bundlePack.setQuantity(bundlePacksarray[a].getQuantity());
String sysMod = bundlePacksarray[a].getSys_mod();
String modifyDate = bundlePacksarray[a].getModify_dt();
try {
bundlePack.setSys_mod(df.parse(sysMod));
bundlePack.setModify_dt(df.parse(modifyDate));
} catch (java.text.ParseException e) {
e.printStackTrace();
}
bundlePack.setStatus(bundlePacksarray[a].getStatus());
arrayBundlePack.add(bundlePack);
//Trying to put out the data to text file
String filename = "bundlepack.txt";
File txtData = new File(getApplicationContext().getFilesDir(), filename);
FileWriter txtWriter = null;
try {
txtWriter = new FileWriter(txtData);
BufferedWriter fileWriter = new BufferedWriter(txtWriter);
for (BundlePack bdpack : arrayBundlePack) {
fileWriter.write(bdpack.toString());
fileWriter.newLine();
fileWriter.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
BundlePack
#Entity
public class BundlePack{
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "promotion_kit")
private String promotion_kit;
#ColumnInfo(name = "stock_code")
private String stock_code;
#ColumnInfo(name = "issue_ref")
private String issue_ref;
#ColumnInfo(name = "quantity")
private Integer quantity;
#TypeConverters(DateConverter.class)
#ColumnInfo(name = "sys_mod")
private Date sys_mod;
#TypeConverters(DateConverter.class)
#ColumnInfo(name = "modify_dt")
private Date modify_dt;
#ColumnInfo(name = "status")
private String status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPromotion_kit() {
return promotion_kit;
}
public void setPromotion_kit(String promotion_kit) {
this.promotion_kit = promotion_kit;
}
public String getStock_code() {
return stock_code;
}
public void setStock_code(String stock_code) {
this.stock_code = stock_code;
}
public String getIssue_ref() {
return issue_ref;
}
public void setIssue_ref(String issue_ref) {
this.issue_ref = issue_ref;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Date getSys_mod() {
return sys_mod;
}
public void setSys_mod(Date sys_mod) {
this.sys_mod = sys_mod;
}
public Date getModify_dt() {
return modify_dt;
}
public void setModify_dt(Date modify_dt) {
this.modify_dt = modify_dt;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "BundlePack{" +
"id=" + id +
", promotion_kit='" + promotion_kit + '\'' +
", stock_code='" + stock_code + '\'' +
", issue_ref='" + issue_ref + '\'' +
", quantity=" + quantity +
", sys_mod=" + sys_mod +
", modify_dt=" + modify_dt +
", status='" + status + '\'' +
'}';
}
}
BundlePackRepo
public class BundlePackRepo {
private String count;
private bundlepacks[] bundlepacks;
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public bundlepacks[] getBundlePacks() {
return bundlepacks;
}
public void setBundlePacks(bundlepacks[] bundlePacks) {
this.bundlepacks = bundlePacks;
}
public static class bundlepacks {
#SerializedName("promotionkit")
private String promotion_kit;
#SerializedName("stock_code")
private String stock_code;
#SerializedName("iss_ref")
private String issue_ref;
#SerializedName("qty")
private int quantity;
#SerializedName("sys_mod")
private String sys_mod;
#SerializedName("modify_dt")
private String modify_dt;
#SerializedName("status")
private String status;
#SerializedName("id")
private String id;
public String getPromotion_kit() {
return promotion_kit;
}
public void setPromotion_kit(String promotion_kit) {
this.promotion_kit = promotion_kit;
}
public String getStock_code() {
return stock_code;
}
public void setStock_code(String stock_code) {
this.stock_code = stock_code;
}
public String getIssue_ref() {
return issue_ref;
}
public void setIssue_ref(String issue_ref) {
this.issue_ref = issue_ref;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getSys_mod() {
return sys_mod;
}
public void setSys_mod(String sys_mod) {
this.sys_mod = sys_mod;
}
public String getModify_dt() {
return modify_dt;
}
public void setModify_dt(String modify_dt) {
this.modify_dt = modify_dt;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
}
You are calling toString() to convert each bundlepack instance to a string for output. So you need to an override for toString to the bundlepack class. It needs to format the instance in the form that you need for your purposes.
Since you currently haven't overridden that method, your code is currently calling Object.toString() ... which only outputs the object's class name and hashcode.
Your IDE may well have a helper to generate a toString for a class, based on the fields of the class.
Hi I am just started with mvvm with repository pattern I am stuck with the API error
I am using the generic API Response class as per google official repo in java
/**
* Generic class for handling responses from Retrofit
*
* #param <T>
*/
public class ApiResponse<T> {
public ApiResponse<T> create(Throwable error) {
return new ApiErrorResponse<>(error.getMessage().equals("") ? error.getMessage() : "Unknown error\nCheck network connection");
}
public ApiResponse<T> create(Response<T> response) {
if (response.isSuccessful()) {
T body = response.body();
if (body instanceof GithubApiResponse) {
if (AppUtils.isValid((GithubApiResponse) body)) {
String errorMsg = "Empty Response.";
return new ApiErrorResponse<>(errorMsg);
}
}
if (body == null || response.code() == 204) { // 204 is empty response
return new ApiEmptyResponse<>();
} else {
return new ApiSuccessResponse<>(body);
}
} else {
String errorMsg = "";
try {
errorMsg = response.errorBody().string();
} catch (IOException e) {
e.printStackTrace();
errorMsg = response.message();
}
return new ApiErrorResponse<>(errorMsg);
}
}
/**
* Generic success response from api
*
* #param <T>
*/
public class ApiSuccessResponse<T> extends ApiResponse<T> {
private T body;
ApiSuccessResponse(T body) {
this.body = body;
}
public T getBody() {
return body;
}
}
/**
* Generic Error response from API
*
* #param <T>
*/
public class ApiErrorResponse<T> extends ApiResponse<T> {
private String errorMessage;
ApiErrorResponse(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrorMessage() {
return errorMessage;
}
}
/**
* separate class for HTTP 204 resposes so that we can make ApiSuccessResponse's body non-null.
*/
public class ApiEmptyResponse<T> extends ApiResponse<T> {
}
}
and My networkBoundResource as like this
public abstract class NetworkBoundResource<ResultType, RequestType> {
private AppExecutors appExecutors;
private MediatorLiveData<Resource<ResultType>> results = new MediatorLiveData<>();
public NetworkBoundResource(AppExecutors appExecutors) {
this.appExecutors = appExecutors;
init();
}
private void init() {
// update LiveData for loading status
results.setValue((Resource<ResultType>) Resource.loading(null));
// observe LiveData source from local db
final LiveData<ResultType> dbSource = loadFromDb();
results.addSource(dbSource, new Observer<ResultType>() {
#Override
public void onChanged(#Nullable ResultType ResultType) {
results.removeSource(dbSource);
if (shouldFetch(ResultType)) {
// get data from the network
fetchFromNetwork(dbSource);
} else {
results.addSource(dbSource, new Observer<ResultType>() {
#Override
public void onChanged(#Nullable ResultType ResultType) {
setValue(Resource.success(ResultType));
}
});
}
}
});
}
/**
* 1) observe local db
* 2) if <condition/> query the network
* 3) stop observing the local db
* 4) insert new data into local db
* 5) begin observing local db again to see the refreshed data from network
*
* #param dbSource
*/
private void fetchFromNetwork(final LiveData<ResultType> dbSource) {
Timber.d("fetchFromNetwork: called.");
// update LiveData for loading status
results.addSource(dbSource, new Observer<ResultType>() {
#Override
public void onChanged(#Nullable ResultType ResultType) {
setValue(Resource.loading(ResultType));
}
});
final LiveData<ApiResponse<RequestType>> apiResponse = createCall();
results.addSource(apiResponse, new Observer<ApiResponse<RequestType>>() {
#Override
public void onChanged(#Nullable final ApiResponse<RequestType> requestObjectApiResponse) {
results.removeSource(dbSource);
results.removeSource(apiResponse);
/*
3 cases:
1) ApiSuccessResponse
2) ApiErrorResponse
3) ApiEmptyResponse
*/
if (requestObjectApiResponse instanceof ApiResponse.ApiSuccessResponse) {
Timber.d("onChanged: ApiSuccessResponse.");
appExecutors.diskIO().execute(new Runnable() {
#Override
public void run() {
// save the response to the local db
saveCallResult((RequestType) processResponse((ApiResponse.ApiSuccessResponse) requestObjectApiResponse));
appExecutors.mainThread().execute(new Runnable() {
#Override
public void run() {
results.addSource(loadFromDb(), new Observer<ResultType>() {
#Override
public void onChanged(#Nullable ResultType ResultType) {
setValue(Resource.success(ResultType));
}
});
}
});
}
});
} else if (requestObjectApiResponse instanceof ApiResponse.ApiEmptyResponse) {
Timber.d("onChanged: ApiEmptyResponse");
appExecutors.mainThread().execute(new Runnable() {
#Override
public void run() {
results.addSource(loadFromDb(), new Observer<ResultType>() {
#Override
public void onChanged(#Nullable ResultType ResultType) {
setValue(Resource.success(ResultType));
}
});
}
});
} else if (requestObjectApiResponse instanceof ApiResponse.ApiErrorResponse) {
Timber.d("onChanged: ApiErrorResponse.");
results.addSource(dbSource, new Observer<ResultType>() {
#Override
public void onChanged(#Nullable ResultType ResultType) {
setValue(
Resource.error(
((ApiResponse.ApiErrorResponse) requestObjectApiResponse).getErrorMessage(),
ResultType
)
);
}
});
}
}
});
}
private ResultType processResponse(ApiResponse.ApiSuccessResponse response) {
return (ResultType) response.getBody();
}
private void setValue(Resource<ResultType> newValue) {
if (results.getValue() != newValue) {
results.setValue(newValue);
}
}
// Called to save the result of the API response into the database.
#WorkerThread
protected abstract void saveCallResult(#NonNull RequestType item);
// Called with the data in the database to decide whether to fetch
// potentially updated data from the network.
#MainThread
protected abstract boolean shouldFetch(#Nullable ResultType data);
// Called to get the cached data from the database.
#NonNull
#MainThread
protected abstract LiveData<ResultType> loadFromDb();
// Called to create the API call.
#NonNull
#MainThread
protected abstract LiveData<ApiResponse<RequestType>> createCall();
// Returns a LiveData object that represents the resource that's implemented
// in the base class.
public final LiveData<Resource<ResultType>> getAsLiveData() {
return results;
}
}
my Repository looks like this
#Singleton
public class GithubRepository {
private GithubDao githubDao;
private GithubTrendingApiService githubApiService;
public GithubRepository(GithubDao githubDao, GithubTrendingApiService githubApiService) {
this.githubDao = githubDao;
this.githubApiService = githubApiService;
}
public LiveData<Resource<List<GithubEntity>>> getRepositories() {
return new NetworkBoundResource<List<GithubEntity>, GithubApiResponse>(AppExecutors.getInstance()) {
#Override
protected void saveCallResult(#NonNull GithubApiResponse item) {
List<GithubEntity> repositories = item.getItems();
githubDao.insertRepositories(repositories);
}
#Override
protected boolean shouldFetch(#Nullable List<GithubEntity> data) {
// Timber.d("shouldFetch: repo: " + data.toString());
// int currentTime = (int) (System.currentTimeMillis() / 1000);
// Timber.d("shouldFetch: current time: " + currentTime);
// int lastRefresh = data.getTimestamp();
// Timber.d("shouldFetch: last refresh: " + lastRefresh);
// Timber.d("shouldFetch: it's been " + ((currentTime - lastRefresh) / 60 / 60 / 24) +
// " days since this recipe was refreshed. 30 days must elapse before refreshing. ");
// if ((currentTime - data.getTimestamp()) >= Constants.RECIPE_REFRESH_TIME) {
// Timber.d("shouldFetch: SHOULD REFRESH RECIPE?! " + true);
// return true;
// }
// Timber.d("shouldFetch: SHOULD REFRESH RECIPE?! " + false);
return true;
}
#NonNull
#Override
protected LiveData<List<GithubEntity>> loadFromDb() {
return githubDao.getTrendingRepository();
}
#NonNull
#Override
protected LiveData<ApiResponse<GithubApiResponse>> createCall() {
return githubApiService.fetchTrendingRepositories();
}
}.getAsLiveData();
}
}
Can anyone tell me whats I am doing wrong because I am getting an API error? somehow I am not able to get the correct data that's why the database is also not filling up
my GithubAPi response class is this
public class GithubApiResponse {
public GithubApiResponse() {
this.items = new ArrayList<>();
}
public GithubApiResponse(List<GithubEntity> items) {
this.items = items;
}
private List<GithubEntity> items;
public List<GithubEntity> getItems() {
return items;
}
public void setItems(List<GithubEntity> items) {
this.items = items;
}
}
and the Entity class is this
#Entity
public class GithubEntity implements Parcelable {
public GithubEntity(#NonNull Long id, String author, String name, String avatar,
String url, String description, Integer stars, Integer forks, Integer currentPeriodStars, String language, String languageColor) {
this.id = id;
this.author = author;
this.name = name;
this.avatar = avatar;
this.url = url;
this.description = description;
this.stars = stars;
this.forks = forks;
this.currentPeriodStars = currentPeriodStars;
this.language = language;
this.languageColor = languageColor;
}
#NonNull
#PrimaryKey
private Long id;
#SerializedName("author")
#Expose
private String author;
#SerializedName("name")
#Expose
private String name;
#SerializedName("avatar")
#Expose
private String avatar;
#SerializedName("url")
#Expose
private String url;
#SerializedName("description")
#Expose
private String description;
#SerializedName("stars")
#Expose
private Integer stars;
#SerializedName("forks")
#Expose
private Integer forks;
#SerializedName("currentPeriodStars")
#Expose
private Integer currentPeriodStars;
#SerializedName("language")
#Expose
private String language;
#SerializedName("languageColor")
#Expose
private String languageColor;
#NonNull
public Long getId() {
return id;
}
public void setId(#NonNull Long id) {
this.id = id;
}
protected GithubEntity(Parcel in) {
author = in.readString();
name = in.readString();
avatar = in.readString();
url = in.readString();
description = in.readString();
if (in.readByte() == 0) {
stars = null;
} else {
stars = in.readInt();
}
if (in.readByte() == 0) {
forks = null;
} else {
forks = in.readInt();
}
if (in.readByte() == 0) {
currentPeriodStars = null;
} else {
currentPeriodStars = in.readInt();
}
language = in.readString();
languageColor = in.readString();
}
public static final Creator<GithubEntity> CREATOR = new Creator<GithubEntity>() {
#Override
public GithubEntity createFromParcel(Parcel in) {
return new GithubEntity(in);
}
#Override
public GithubEntity[] newArray(int size) {
return new GithubEntity[size];
}
};
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStars() {
return stars;
}
public void setStars(Integer stars) {
this.stars = stars;
}
public Integer getForks() {
return forks;
}
public void setForks(Integer forks) {
this.forks = forks;
}
public Integer getCurrentPeriodStars() {
return currentPeriodStars;
}
public void setCurrentPeriodStars(Integer currentPeriodStars) {
this.currentPeriodStars = currentPeriodStars;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getLanguageColor() {
return languageColor;
}
public void setLanguageColor(String languageColor) {
this.languageColor = languageColor;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(author);
dest.writeString(name);
dest.writeString(avatar);
dest.writeString(url);
dest.writeString(description);
if (stars == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeInt(stars);
}
if (forks == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeInt(forks);
}
if (currentPeriodStars == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeInt(currentPeriodStars);
}
dest.writeString(language);
dest.writeString(languageColor);
}
}
can anyone guide me so that I can fix this issue? stuck here for 2 days
This function returns two objects TMBase.customer#40fb1588, TMBase.customer#40fb1ad8, but I need to return these values emy, samera. I need to know what is the problem?
public ArrayList<TMBase.Customer> GetWorkerNameOfCustomerByID( int LineID)
{
ArrayList<TMBase.Customer> CustomerArr = new ArrayList<TMBase.Customer>();
connecttodatabase qq = new connecttodatabase();
qq.dbconnect();
if (qq.con != null)
{
String result = "";
ResultSet rs = null;
try {
CallableStatement cstmt = null;
Statement st = qq.con.createStatement();
cstmt = qq.con.prepareCall("{CALL GetWorkerNameOfCustomerByID(?)}");
cstmt.setInt(1, LineID);
rs = cstmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next())
{
TMBase.Customer CustomerObj=new TMBase.Customer();
CustomerObj.setWorkerName(rs.getString("WorkerName"));
CustomerArr.add(CustomerObj);
}
} catch (SQLException e) {
e.printStackTrace();
}
qq.closeConnection();
}
return CustomerArr;
}
Customer class:
package TMBase;
public class Customer {
private int ID;
private int LineId;
private int WorkerId;
private Timestamp DateSubscribe;
private String WorkerName;
public int getID() {
return this.ID;
}
public int setID(int ID){
return this.ID = ID;
}
//////////////////////////////////////////////
public int getLineId() {
return this.LineId;
}
public int setLineId(int LineId){
return this.LineId = LineId;
}
//////////////////////////////////////////////
public int getWorkerId() {
return this.WorkerId;
}
public int setWorkerId(int WorkerId){
return this.WorkerId = WorkerId;
}
///////////////////////////////////////////////
public Timestamp getDateSubscribe() {
return this.DateSubscribe;`enter code here`
}
public Timestamp setDateSubscribe(Timestamp DateSubscribe){
return this.DateSubscribe = DateSubscribe;
}
///////////////////////////////////////////////
public String getWorkerName() {
return this.WorkerName;
}
public String setWorkerName(String WorkerName){
return this.WorkerName = WorkerName;
}
}
you need to override the toString() method of your Customer object.
I'm assuming you are using an ArrayAdapter to display these in your ListView, which calls toString() on each item in the dataset to display on the screen.
By overriding toString(), you can return whatever data you want to be displayed in the ListView for example:
public String toString(){
return getWorkerName();
}
can you please help me rectify the code below, I'm trying to create a populated drop down list in struts 2 in Eclipse as my IDE. This is my first time to use 'STRUTS' as well as 'IDE ECLIPSE'.
To be specific by the SELECT statement I do not know how to write the code that, when a user selects the 'Make' of the car, the database extracts the different 'Models' of that make. But other select items like 'Color', should be optional in that a user can proceed to search for the 'Make' minus choosing an option from them.
Please help I'm new in ActionClass and DataBase. Thanx in advance.
package drive;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.opensymphony.xwork2.ActionSupport;
public class CarSearch extends ActionSupport {
private String model;
private String modification;
private String engine;
private String color;
private String bodyType;
private String minPrice;
private String maxPrice;
private String mileage;
private int minYear;
private int maxYear;
private String make;
public String execute () {
String ret = NONE;
Connection conn = null;
try {
String URL = "jdbc:mysql://localhost/Cars";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, "root", "$jademedia247");
String sql = "SELECT make FROM type WHERE";
sql+=" model = ? AND modification = ? ";
PreparedStatement ps = conn.prepareStatement (sql);
ps.setString(1, model);
ps.setString(2, modification);
ResultSet rs = ps.executeQuery();
while (rs.next()){
make = rs.getString(1);
ret = SUCCESS;
}
} catch (Exception e) {
ret = ERROR;
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
return ret;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getModification() {
return modification;
}
public void setModification (String modification) {
this.modification = modification;
}
public String getEngine() {
return engine;
}
public void setEngine (String engine) {
this.engine = engine;
}
public String getColor() {
return color;
}
public void setColor (String color) {
this.color = color;
}
public String getBodyType() {
return bodyType;
}
public void setBodyType(String bodyType) {
this.bodyType = bodyType;
}
public String getMinPrice() {
return minPrice;
}
public void setMinPrice(String minPrice) {
this.minPrice = minPrice;
}
public String getMaxPrice () {
return maxPrice;
}
public void setMaxPrice (String maxPrice) {
this.maxPrice = maxPrice;
}
public String getMileage () {
return mileage;
}
public void setMileage (String mileage) {
this.mileage = mileage ;
}
public int getMinYear() {
return minYear;
}
public void setMinYear(int minYear) {
this.minYear = minYear;
}
public int getMaxYear() {
return maxYear;
}
public void setMaxYear(int maxYear) {
this.maxYear = maxYear;
}
public String getMake() {
return make;
}
public void setMake(String make){
this.make = make;
}
}
PreparedStatement ps = conn.prepareStatement ("SELECT field_name FROM table_name WHERE model = ? AND modification = ? ");
ps.setString(1, model);
ps.setString(2, modification);
ResultSet rs = ps.executeQuery();
//it will help you
I'm trying to retrieve data from my Model class into textfield via GET, although nullpointexception is throwing an error
The code in the View class is =
public View_EditCustomer(Model_Customer cust) {
customer = cust;
txtname.setText(customer.GetFName());
txtSecondName.setText(customer.GetLName());
initComponents();
}
and in another View class it is =
private void btnSelectActionPerformed(java.awt.event.ActionEvent evt) {
ListSelectionModel rowSM = jTable1.getSelectionModel();
int row = rowSM.getMinSelectionIndex();
int Appointment_ID = (Integer)resultModel.getValueAt(row, 0);
Model_Customer cust = null;
try{
cust = Controller_ManageCustomer.GetCustomer(Appointment_ID);
new View_EditCustomer(cust).setVisible(true);
}catch(Exception ex){
JOptionPane.showMessageDialog(this,ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
Model_Customer code parts =
public static Model_Customer QueryID(int Appointment_ID) throws Exception
{
try{
Statement stmt = Model_Customer.conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM appointment WHERE appointmentid="+Appointment_ID+" LIMIT 1;");
if(rs.next())
return new Model_Customer(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8),rs.getString(9),rs.getString(10),rs.getString(11),rs.getString(12));
}catch(Exception e){
throw new Exception(e.getMessage());
}
return null;
}
private Model_Customer(int Appointment_ID, String FName, String LName, String Registration, String Make, String Model, String Engine, String Year, String Mileage, String Type, String Date, String Time)
{
this._Appointment_ID=Appointment_ID;
this._Type=Type;
this._Time=Time;
this._Date=Date;
this._FName=FName;
this._LName=LName;
this._Make=Make;
this._Model=Model;
this._Engine=Engine;
this._Year=Year;
this._Mileage=Mileage;
this._Registration=Registration;
this._inSync=true;
}
public int GetID()
{
return this._Appointment_ID;
}
public String GetFName()
{
return _FName;
}
public String GetLName()
{
return _LName;
}
public String GetRegistration()
{
return _Registration;
}
public String GetMake()
{
return _Make;
}
public String GetModel()
{
return _Model;
}
public String GetEngine()
{
return _Engine;
}
public String GetYear()
{
return _Year;
}
public String GetMileage()
{
return _Mileage;
}
public String GetType()
{
return _Type;
}
public String GetDate()
{
return _Date;
}
public String GetTime()
{
return _Time;
}
In debugging Model_Customer cust is actually populated by data and it actually goes to the end to txtname.setText(customer.GetFName()); goes to Model_Customer GetFName and should retrieve the name but throws an exception (int)0. Would really appreciate your help!!
Shouldn't initComponents(); be called before using TextViews ?
public View_EditCustomer(Model_Customer cust) {
initComponents();
customer = cust;
txtname.setText(customer.GetFName());
txtSecondName.setText(customer.GetLName());
}