The program compiles without errors. I can not understand why the widget is not displayed.
GreetingServise
#RemoteServiceRelativePath("springGwtServices/greetingService")
public interface GreetingService extends RemoteService {
Greeting getGreeting(String text);
void addGreeting(String author, String text);
void updateGreeting(String author, String text);
void deleteGreeting(String text);
List<Greeting> getGreetings();
}
GreetingServiceAsync
public interface GreetingServiceAsync extends RemoteService {
void getGreeting(String text, AsyncCallback<Greeting> async);
void addGreeting(String author, String text, AsyncCallback<Void> async);
void updateGreeting(String author, String text, AsyncCallback<Void> async);
void deleteGreeting(String text, AsyncCallback<Void> async);
void getGreetings( AsyncCallback<List<Greeting>> callback);
}
HelloGWT
public class HelloGWT implements IsWidget, EntryPoint {
static Logger logger = Logger.getLogger(HelloGWT.class);
private static final GreetingMapper props = GWT.create(GreetingMapper.class);
private static final GreetingServiceImpl impl = GWT.create(GreetingServiceImpl.class);
private ContentPanel panel;
public Widget asWidget() {
if (panel == null) {
ColumnConfig<Greeting, String> nameCol = new ColumnConfig<Greeting, String>(props.author(), 50, SafeHtmlUtils.fromTrustedString("<b>Company</b>"));
ColumnConfig<Greeting, String> symbolCol = new ColumnConfig<Greeting, String>(props.text(), 100, "Symbol");
List<ColumnConfig<Greeting, ?>> columns = new ArrayList<ColumnConfig<Greeting, ?>>();
columns.add(nameCol);
columns.add(symbolCol);
ColumnModel<Greeting> cm = new ColumnModel<Greeting>(columns);
ToolTipConfig config = new ToolTipConfig("Example Info", "This examples includes resizable panel, reorderable columns and grid state. Text selection is allowed.");
config.setMaxWidth(225);
ToolButton info = new ToolButton(ToolButton.QUESTION);
info.setToolTipConfig(config);
ListStore<Greeting> store = new ListStore<Greeting>(props.id());
store.addAll(impl.getGreetings());
final Grid<Greeting> grid = new Grid<Greeting>(store, cm);
grid.setAllowTextSelection(true);
grid.getView().setAutoExpandColumn(nameCol);
grid.getView().setStripeRows(true);
grid.getView().setColumnLines(true);
grid.setBorders(false);
grid.setColumnReordering(true);
// Stage manager, turn on state management
grid.setStateful(true);
grid.setStateId("gridExample");
// Stage manager, load previous state
GridStateHandler<Greeting> state = new GridStateHandler<Greeting>(grid);
state.loadState();
SimpleComboBox<String> typeCombo = new SimpleComboBox<String>(new StringLabelProvider<String>());
typeCombo.setTriggerAction(ComboBoxCell.TriggerAction.ALL);
typeCombo.setEditable(false);
typeCombo.setWidth(100);
typeCombo.add("Row");
typeCombo.add("Cell");
typeCombo.setValue("Row");
// we want to change selection model on select, not value change which fires on blur
typeCombo.addSelectionHandler(new SelectionHandler<String>() {
public void onSelection(SelectionEvent<String> event) {
boolean cell = event.getSelectedItem().equals("Cell");
if (cell) {
CellSelectionModel<Greeting> c = new CellSelectionModel<Greeting>();
c.addCellSelectionChangedHandler(new CellSelectionChangedEvent.CellSelectionChangedHandler<Greeting>() {
public void onCellSelectionChanged(CellSelectionChangedEvent<Greeting> event) {
}
});
grid.setSelectionModel(c);
} else {
grid.setSelectionModel(new GridSelectionModel<Greeting>());
}
}
});
typeCombo.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> event) {
}
});
ToolBar toolBar = new ToolBar();
toolBar.setEnableOverflow(false);
toolBar.add(new LabelToolItem("Selection Mode: "));
toolBar.add(typeCombo);
VerticalLayoutContainer con = new VerticalLayoutContainer();
con.add(toolBar, new VerticalLayoutContainer.VerticalLayoutData(1, -1));
con.add(grid, new VerticalLayoutContainer.VerticalLayoutData(1, 1));
panel = new ContentPanel();
panel.setHeadingText("Basic Grid");
panel.setPixelSize(600, 300);
panel.addTool(info);
final Resizable resizable = new Resizable(panel, Resizable.Dir.E, Resizable.Dir.SE, Resizable.Dir.S);
panel.addExpandHandler(new ExpandEvent.ExpandHandler() {
public void onExpand(ExpandEvent event) {
resizable.setEnabled(true);
}
});
panel.addCollapseHandler(new CollapseEvent.CollapseHandler() {
public void onCollapse(CollapseEvent event) {
resizable.setEnabled(false);
}
});
panel.setWidget(con);
// Enables quicktips (qtitle for the heading and qtip for the
// content) that are setup in the change GridCellRenderer
new QuickTip(grid);
}
return panel;
}
public void onModuleLoad() {
// State manager, initialize the state options
StateManager.get().setProvider(new CookieProvider("/", null, null, GXT.isSecure()));
RootPanel.get().add(asWidget());
BasicConfigurator.configure();
logger.info("Entering application.");
Bar bar = new Bar();
bar.doIt();
logger.info("Exiting application.");
}
}
GreetingMapper
public interface GreetingMapper extends PropertyAccess<Greeting> {
#Select("SELECT * FROM greetings WHERE text = #{text}")
Greeting getGreeting(#Param("text") String text);
#Select("INSERT INTO greetings (author, text) VALUES (#{author}, #{text})")
void addGreeting(#Param("author") String author, #Param("text") String text);
#Select("UPDATE greetings SET author = #{author} where text = #{text}")
void updateGreeting(#Param("author") String author, #Param("text") String text);
#Select("DELETE FROM greetings WHERE text = #{text}")
void deleteGreeting(#Param("text") String text);
#Select("SELECT * FROM greetings")
List<Greeting> getGreetings();
ModelKeyProvider<Greeting> id();
ValueProvider<Greeting, String> author();
ValueProvider<Greeting, String> text();
}
GreetingServiceImpl
#Service("greetingService")
public class GreetingServiceImpl implements GreetingService {
#Autowired
private GreetingMapper greetingMapper;
#Override
public Greeting getGreeting(String text) {
return greetingMapper.getGreeting(text);
}
#Override
public void addGreeting(String author, String text) {
greetingMapper.addGreeting(author, text);
}
#Override
public void updateGreeting(String author, String text) {
greetingMapper.updateGreeting(author, text);
}
#Override
public void deleteGreeting(String text) {
greetingMapper.deleteGreeting(text);
}
#Override
public List<Greeting> getGreetings() {
return greetingMapper.getGreetings();
}
}
Greeting
public class Greeting extends BaseModelData implements Serializable{
private Integer id;
private String author;
private String text;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
Related
This is the generic method through which i am accepting list of
objects and downcasting to a specific object
public Response generate(List<?> list){
List<ClassA> List1 = new ArrayList<ClassA>();
List<ClassB> List2 = new ArrayList<ClassB>();
List<ClassC> List3 = new ArrayList<ClassC>();
if(list instanceof List<?>){
List1=(List<ClassA>) list;//in this line i am getting error
addDataToExcel(List1);
}
else if(list instanceof List<?>){
List2=(List<ClassB>) list;
addDataToExcel(List1);
}
else if(list instanceof List<?>){
List3=(List<ClassC>) list;
addDataToExcel(List1);
}
This is classA
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
#Entity
#Table(name="ClassA")
public class ClassA {
#Id
#Column(name="rollNo")
private int rollNo;
#Column(name="name")
private String name;
#Column(name="english")
private double english;
#Column(name="maths")
private double maths;
#Column(name="science")
private double science;
#Column(name="totalMarks")
private double totalMarks;
#Column(name="percentage")
private double percentage;
#Column(name="status")
private boolean status;
#Lob
#Column(name="file", columnDefinition="BLOB")
private byte[] file;
public ClassA() {
// TODO Auto-generated constructor stub
}
public ClassA(int rollNo, String name, double english, double maths, double science, double totalMarks,
double percentage, boolean status, byte[] file) {
super();
this.rollNo = rollNo;
this.name = name;
this.english = english;
this.maths = maths;
this.science = science;
this.totalMarks = totalMarks;
this.percentage = percentage;
this.status = status;
this.file = file;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getEnglish() {
return english;
}
public void setEnglish(double english) {
this.english = english;
}
public double getMaths() {
return maths;
}
public void setMaths(double maths) {
this.maths = maths;
}
public double getScience() {
return science;
}
public void setScience(double science) {
this.science = science;
}
public double getTotalMarks() {
return totalMarks;
}
public void setTotalMarks(double totalMarks) {
this.totalMarks = totalMarks;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public byte[] getFile() {
return file;
}
public void setFile(byte[] file) {
this.file = file;
}
}
This is the method which accepts List and generate excel
public void add(List<ClassA> classA) {
System.out.println("entering add");
String excelFilePath = "D:/eclipse_neon/StudentInfo.xlsx";
try {
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowNum = 1;
int a=2;
for(ClassA info: classA){
System.out.println("netering loop");
Row row = sheet.getRow(rowNum++);
row.createCell(2).setCellValue(info.getEnglish());
row.createCell(3).setCellValue(info.getMaths());
row.createCell(4).setCellValue(info.getScience());
row.createCell(5).setCellFormula("SUM(C"+a+","+"D"+a+","+"E"+a+")");
row.createCell(6).setCellFormula("("+"F"+a+"*"+"100"+")"+"/"+"300");
row.createCell(7).setCellValue(info.isStatus());
a++;
}
System.out.println("after for loop");
inputStream.close();
FileOutputStream outputStream = new FileOutputStream("D:/eclipse_neon/StudentInfo.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException | EncryptedDocumentException
| InvalidFormatException ex) {
ex.printStackTrace();
}
}
I am not able to downcast to my specific List of class from generic list soo any suggestions are welcomed Thankyou
That's probably because you're sending a list as parameter containing a List and class A is not related to LinkedHashMap (not a subclass for example) and therefore it cannot cast. If you can provide more details what is class A and what is the list you're sending as arguments to your method.
Check https://www.baeldung.com/java-type-casting
How do I insert data from MySQL into Gridview on Fragments? I've tried it with a coding method used for Activity. I've changed a lot but it's still wrong. This is my coding:
/**
* A simple {#link Fragment} subclass.
*/
public class Product extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
GridView grid_product;
SwipeRefreshLayout swipe;
List<ProductData> newsList = new ArrayList<ProductData>();
private static final String TAG = Product.class.getSimpleName();
private static String url_list = Server.URL + "news.php?offset=";
private int offSet = 0;
int no;
ProductAdapter adapter;
public static final String TAG_NO = "no";
public static final String TAG_ID = "id";
public static final String TAG_JUDUL = "judul";
public static final String TAG_TGL = "tgl";
public static final String TAG_ISI = "isi";
public static final String TAG_GAMBAR = "gambar";
Handler handler;
Runnable runnable;
public Product() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
grid_product = (GridView) view.findViewById(R.id.grid_product);
setProduct();
return view;
}
private void setProduct(){
adapter = new ProductAdapter(getActivity(), newsList);
grid_product.setAdapter(adapter);
grid_product.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//pindah activity
startActivity(new Intent(
getActivity(), DetailActivity.class
));
}
});
I don't know where the mistake is:
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
newsList.clear();
adapter.notifyDataSetChanged();
callNews(0);
}
}
);
grid_product.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
swipe.setRefreshing(true);
handler = new Handler();
runnable = new Runnable() {
public void run() {
callNews(offSet);
}
};
handler.postDelayed(runnable, 3000);
}
}
});
}
#Override
public void onRefresh() {
newsList.clear();
adapter.notifyDataSetChanged();
callNews(0);
}
I don't know where the mistake is:
private void callNews(int page){
swipe.setRefreshing(true);
// Creating volley request obj
JsonArrayRequest arrReq = new JsonArrayRequest(url_list + page,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
ProductData news = new ProductData();
no = obj.getInt(TAG_NO);
news.addId(obj.getString(TAG_ID));
news.addJudul(obj.getString(TAG_JUDUL));
if (obj.getString(TAG_GAMBAR) != "") {
news.addGambar(obj.getString(TAG_GAMBAR));
}
news.addDatetime(obj.getString(TAG_TGL));
news.addIsi(obj.getString(TAG_ISI));
// adding news to news array
newsList.add(news);
if (no > offSet)
offSet = no;
Log.d(TAG, "offSet " + offSet);
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(arrReq);
}
}
I am newbie to Android Studio and I am making my final year project.
I made a QR code scanner that can retrieve data from HTTP using Rest API.
My question is: I need to send all the JSON data to other activity, based on my research I need to put intent on my button, because of that I need to pass my JsonRequest data to Btn_BuyClicked method so I can send all those to next activity.
I used AndroidHive MovieTickets so Im not changing so much coding.
Please help me. Thank you.
public class TicketResultActivity extends AppCompatActivity {
private static final String TAG = TicketResultActivity.class.getSimpleName();
private Button btnBuy;
private ImageView imgPoster;
private ProgressBar progressBar;
private TicketView ticketView;
private TextView txtDirector;
private TextView txtYear_created;
private TextView txtError;
private TextView txtType_powder;
private TextView txtApa_number;
private TextView txtLocation;
private TextView txtDate_expired;
private Button signOut;
private FirebaseAuth auth;
private class Movie {
String director;
String year_created;
String type_powder;
#SerializedName("released")
boolean isReleased;
String apa_number;
String poster;
String location;
String date_expired;
private Movie() {
}
public String getApa_number() {
return this.apa_number;
}
public String getDirector() {
return this.director;
}
public String getPoster() {
return this.poster;
}
public String getYear_created() {
return this.year_created;
}
public String getType_powder() {
return this.type_powder;
}
public String getLocation() {
return this.location;
}
public String getDate_expired() {
return this.date_expired;
}
public boolean isReleased() {
return this.isReleased;
}
}
NotificationCompat.Builder notification;
private static final int uniqueID = 250298;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_result);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.txtApa_number = (TextView) findViewById(R.id.apa_number);
this.txtDirector = (TextView) findViewById(R.id.director);
this.txtYear_created = (TextView) findViewById(R.id.year_created);
this.txtLocation = (TextView) findViewById(R.id.location);
this.txtDate_expired = (TextView) findViewById(R.id.date_expired);
this.imgPoster = (ImageView) findViewById(R.id.poster);
this.txtType_powder = (TextView) findViewById(R.id.type_powder);
this.btnBuy = (Button) findViewById(R.id.btn_buy);
this.imgPoster = (ImageView) findViewById(R.id.poster);
this.txtError = (TextView) findViewById(R.id.txt_error);
this.ticketView = (TicketView) findViewById(R.id.layout_ticket);
this.progressBar = (ProgressBar) findViewById(R.id.progressBar);
String barcode = getIntent().getStringExtra("code");
if (TextUtils.isEmpty(barcode)) {
Toast.makeText(getApplicationContext(), "Barcode is empty!", Toast.LENGTH_LONG).show();
finish();
}
searchBarcode(barcode);
}
public void btn_buyClicked(View view) {
notification.setSmallIcon(R.drawable.qrcode);
notification.setTicker("This is the ticker");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Fire Extinguisher Scanner");
Intent intent = new Intent(this, Test.class);
startActivity(new Intent(TicketResultActivity.this, Test.class));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(uniqueID, notification.build());
}
private void searchBarcode(String barcode) {
MyApplication.getInstance().addToRequestQueue(new JsonObjectRequest(Request.Method.GET, barcode, null, new Listener<JSONObject>() {
public void onResponse(JSONObject response) {
Log.e(TicketResultActivity.TAG, "Ticket response: " + response.toString());
if (response.has("error")) {
TicketResultActivity.this.showNoTicket();
} else {
TicketResultActivity.this.renderMovie(response);
}
}
}, new ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e(TicketResultActivity.TAG, "Error: " + error.getMessage());
TicketResultActivity.this.showNoTicket();
}
}));
}
private void showNoTicket() {
this.txtError.setVisibility(View.VISIBLE);
this.ticketView.setVisibility(View.GONE);
this.progressBar.setVisibility(View.GONE);
}
public void renderMovie(JSONObject response) {
try {
Movie movie = (Movie) new Gson().fromJson(response.toString(), Movie.class);
if (movie != null) {
this.txtApa_number.setText(movie.getApa_number());
this.txtDirector.setText(movie.getDirector());
this.txtYear_created.setText(movie.getYear_created());
this.txtType_powder.setText(movie.getType_powder());
this.txtDate_expired.setText(BuildConfig.FLAVOR + movie.getDate_expired());
this.txtLocation.setText(movie.getLocation());
Glide.with(this).load(movie.getPoster()).into(this.imgPoster);
notification.setContentText("Fire Extinguisher "+ movie.getApa_number()+"successfully remind!");
if (movie.isReleased()) {
this.btnBuy.setText(getString(R.string.btn_buy_now));
this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
} else {
this.btnBuy.setText(getString(R.string.btn_buy_now));
this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
}
this.ticketView.setVisibility(View.VISIBLE);
this.progressBar.setVisibility(View.GONE);
return;
}
showNoTicket();
} catch (JsonSyntaxException e) {
Log.e(TAG, "JSON Exception: " + e.getMessage());
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
} catch (Exception e2) {
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
}
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is my TicketResultActivity.java class UPDATED CODE
private static class Movie implements Parcelable {
String director;
String year_created;
String type_powder;
#SerializedName("released")
boolean isReleased;
String apa_number;
String poster;
String location;
String date_expired;
public Movie() {
}
public Movie(Parcel in) {
director = in.readString();
year_created = in.readString();
type_powder = in.readString();
isReleased = in.readByte() != 0;
apa_number = in.readString();
poster = in.readString();
location = in.readString();
date_expired = in.readString();
}
public String getApa_number(){
return this.apa_number;
}
public String getYear_created() {
return year_created;
}
public String getType_powder() {
return type_powder;
}
public String getDirector() {
return director;
}
public String getPoster() {
return poster;
}
public String getLocation() {
return location;
}
public boolean isReleased() {
return isReleased;
}
public String getDate_expired() {
return date_expired;
}
public void setApa_number(String apa_number){
this.apa_number = apa_number;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(director);
dest.writeString(year_created);
dest.writeString(type_powder);
dest.writeByte((byte) (isReleased ? 1 : 0));
dest.writeString(apa_number);
dest.writeString(poster);
dest.writeString(location);
dest.writeString(date_expired);
}
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
#Override
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
#Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
#Override
public int describeContents() {
return 0;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_result);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.txtApa_number = (TextView) findViewById(R.id.apa_number);
this.txtDirector = (TextView) findViewById(R.id.director);
this.txtYear_created = (TextView) findViewById(R.id.year_created);
this.txtLocation = (TextView) findViewById(R.id.location);
this.txtDate_expired = (TextView) findViewById(R.id.date_expired);
this.imgPoster = (ImageView) findViewById(R.id.poster);
this.txtType_powder = (TextView) findViewById(R.id.type_powder);
this.btnBuy = (Button) findViewById(R.id.btn_buy);
this.imgPoster = (ImageView) findViewById(R.id.poster);
this.txtError = (TextView) findViewById(R.id.txt_error);
this.ticketView = (TicketView) findViewById(R.id.layout_ticket);
this.progressBar = (ProgressBar) findViewById(R.id.progressBar);
String barcode = getIntent().getStringExtra("code");
if (TextUtils.isEmpty(barcode)) {
Toast.makeText(getApplicationContext(), "Barcode is empty!", Toast.LENGTH_LONG).show();
finish();
}
searchBarcode(barcode);
}
public void btn_buyClicked(View view) {
// In activity or fragment
Movie movie = new Movie();
movie.setApa_number("xyz");
Intent intent = new Intent(this, Test.class);
intent.putExtra("parcel_data", movie);
startActivity(intent);
}
private void searchBarcode(String barcode) {
MyApplication.getInstance().addToRequestQueue(new JsonObjectRequest(Request.Method.GET, barcode, null, new Listener<JSONObject>() {
public void onResponse(JSONObject response) {
Log.e(TicketResultActivity.TAG, "Ticket response: " + response.toString());
if (response.has("error")) {
TicketResultActivity.this.showNoTicket();
} else {
TicketResultActivity.this.renderMovie(response);
}
}
}, new ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e(TicketResultActivity.TAG, "Error: " + error.getMessage());
TicketResultActivity.this.showNoTicket();
}
}));
}
private void showNoTicket() {
this.txtError.setVisibility(View.VISIBLE);
this.ticketView.setVisibility(View.GONE);
this.progressBar.setVisibility(View.GONE);
}
public void renderMovie(JSONObject response) {
try {
Movie movie = (Movie) new Gson().fromJson(response.toString(), Movie.class);
if (movie != null) {
this.txtApa_number.setText(movie.getApa_number());
this.txtDirector.setText(movie.getDirector());
this.txtYear_created.setText(movie.getYear_created());
this.txtType_powder.setText(movie.getType_powder());
this.txtDate_expired.setText(BuildConfig.FLAVOR + movie.getDate_expired());
this.txtLocation.setText(movie.getLocation());
Glide.with(this).load(movie.getPoster()).into(this.imgPoster);
if (movie.isReleased()) {
this.btnBuy.setText(getString(R.string.btn_buy_now));
this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
} else {
this.btnBuy.setText(getString(R.string.btn_buy_now));
this.btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
}
this.ticketView.setVisibility(View.VISIBLE);
this.progressBar.setVisibility(View.GONE);
return;
}
showNoTicket();
} catch (JsonSyntaxException e) {
Log.e(TAG, "JSON Exception: " + e.getMessage());
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
} catch (Exception e2) {
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
}
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is Test.java Class
public class Test extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Movie movie = (Movie) getIntent().getParcelableExtra("parcel_data");
String apa_number = movie.getApa_number();
TextView textView1 = findViewById(R.id.textView2);
textView1.setText(apa_number);
}
}
Use Parcelable is an interface. A class who implements Parcelable can write to and read from a Parcel.
You need to follow 3 points to create a Parcelable class.
A Class must implement Parcelable interface
A Class must have a non-null static field CREATOR of a type that implements Parcelable.Creator interface.
Override writeToParcel method and write member variable in Parcel. Make sure to read variables in the same sequence in which they are written in Parcel. Order of read and write matters.
private class Movie implements Parcelable{
String director;
String year_created;
String type_powder;
#SerializedName("released")
boolean isReleased;
String apa_number;
String poster;
String location;
String date_expired;
public Movie() {
}
// In constructor you will read the variables from Parcel. Make sure to read them in the same sequence in which you have written them in Parcel.
public Movie(Parcel in) {
director = in.readString();
year_created = in.readString();
release_date = in.readString();
poster = in.readString();
}
public String getApa_number() {
return this.apa_number;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
// This is where you will write your member variables in Parcel. Here you can write in any order. It is not necessary to write all members in Parcel.
#Override
public void writeToParcel(Parcel dest, int flags) {
// Write data in any order
dest.writeString(director);
dest.writeString(year_created);
dest.writeString(release_date);
dest.writeString(poster);
}
// This is to de-serialize the object
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>(){
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
Now you can pass a Parcelable object using Intent.
// In activity or fragment
Movie movie = new Movie();
movie.setDirector("xyz");
// now you can set all values like :year created, is released whatever.
// using context and next component class to create intent
Intent intent = new Intent(this, NextActivity.class);
// using putExtra(String key, Parcelable value) method
intent.putExtra(“parcel_data”, movie);
startActivity(intent);
You can access this data in NextActivity –
public class NextActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// Using getParcelableExtra(String key) method
Movie movie = (Movie) getIntent().getParcelableExtra("parcel_data");
String director = movie.getDirector();
}
}
There are so many ways to send data from one activity to another activity. If you Have Primitive or Json string type data then you can directly put that data into the intent.
But if in case you have Model class and you need to pass it. Then you have two ways:
Serializable
Parcelable
But Android recommend to use Parcelable.
You can also add plugin to android studio to generate the parcelable code.
I try to do recyclerView with retrofit2, but I do in my code: recyclerView Adapter Constructor and I get a error in my MainActivity part of this line -
"(flowersList, this)": I get error: List anonymous retrofit2.Callback
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, this);
my code my MainActivity is:
try {
APIService service = ApiClient.getRetrofit().create(APIService.class);
retrofit2.Call<List<Flower>> call = service.getFlowerData();
call.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(retrofit2.Call<List<Flower>> call, Response<List<Flower>> response) {
List<Flower> flowersList = response.body();
mLinearLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, this);
mRecyclerView.setAdapter(recyclerViewAdapter);
}
and the code in RecyclerViewFlowersAdapter is:
public class RecyclerViewFlowersAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
private List<Flower> mFlowers;
private Context mContext;
public RecyclerViewFlowersAdapter(List<Flower> flowers, Context context) {
mContext = context;
mFlowers = flowers;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.flower_item_card, null);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.mTextViewTitle.setText(mFlowers.get(position).getName());
Picasso.with(mContext)
.load(mFlowers.get(position).getPhoto()).into(holder.mImageViewFlower);
}
#Override
public int getItemCount() {
return mFlowers.size();
}
}
and my code in RecyclerViewHolder is:
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTextViewTitle;
public ImageView mImageViewFlower;
public RecyclerViewHolder(View itemView){
super(itemView);
itemView.setOnClickListener(this);
mTextViewTitle = itemView.findViewById(R.id.title);
mImageViewFlower = itemView.findViewById(R.id.imageViewFlower);
}
#Override
public void onClick(View v) {
}
}
I try to do alot of thing but is still error.
thanks for help :)
You are probably using a wrong context, try using MainActivity.this instead of this. Change this
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, this);
to this
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, MainActivity.this);
I tried the same code as on http://code.google.com/p/struts2-jquery/wiki/TreeTag
It's working fine to generate the tree structure, but I want to assign different URLs to each TreeNode of the tree. How can I do same with JSON response?
A Tree Component with a JSON Data Source.
JSP Code
<s:url var="treeDataUrl" action="json-tree-data"/>
<sjt:tree
id="jsonTree"
href="%{treeDataUrl}"
onClickTopics="treeClicked"
/>
Java Action Code
#ParentPackage(value = "showcase")
public class JsonTreeData extends ActionSupport {
private static final long serialVersionUID = -2886756982077980790L;
private List<TreeNode> nodes = new ArrayList<TreeNode>();
private String id = "";
#Actions( { #Action(value = "/json-tree-data", results = { #Result(name = "success", type = "json", params = {
"root", "nodes" }) }) })
public String execute() {
TreeNode nodeA = new TreeNode();
nodeA.setId("A" + id);
nodeA.setTitle("Node A" + id);
nodeA.setState(TreeNode.NODE_STATE_CLOSED);
TreeNode nodeB = new TreeNode();
nodeB.setId("B" + id);
nodeB.setState(TreeNode.NODE_STATE_CLOSED);
nodeB.setTitle("Node B" + id);
TreeNode nodeC = new TreeNode();
nodeC.setId("C" + id);
nodeC.setState(TreeNode.NODE_STATE_CLOSED);
nodeC.setTitle("Node C" + id);
nodes.add(nodeA);
nodes.add(nodeB);
nodes.add(nodeC);
return SUCCESS;
}
public String getJSON() {
return execute();
}
public List<TreeNode> getNodes() {
return nodes;
}
public void setId(String id) {
this.id = id;
}
}
TreeNode.java
public class TreeNode implements Serializable {
public static final String NODE_STATE_CLOSED = "closed";
public static final String NODE_STATE_OPEN = "open";
private Map<String, Object> attr;
private Collection<TreeNode> children;
private String icon;
private String id;
private String state = TreeNode.NODE_STATE_CLOSED;
private String title;
public TreeNode() {
super();
}
public TreeNode(String title) {
super();
this.title = title;
}
public TreeNode(String id, String title) {
super();
this.id = id;
this.title = title;
}
public TreeNode(String title, Collection<TreeNode> children) {
super();
this.title = title;
this.children = children;
}
public TreeNode(String id, String title, Collection<TreeNode> children) {
super();
this.id = id;
this.title = title;
this.children = children;
}
public Map<String, Object> getAttr() {
return attr;
}
public Collection<TreeNode> getChildren() {
return children;
}
/**
* Get the Tree Node Title
*/
public String getData() {
return title;
}
public String getIcon() {
return icon;
}
public String getId() {
return id;
}
public String getState() {
return state;
}
public String getTitle() {
return title;
}
public void setAttr(Map<String, Object> attr) {
this.attr = attr;
}
/**
* Set the Tree Node Childrens
*
* #param children
*/
public void setChildren(Collection<TreeNode> children) {
this.children = children;
}
/**
* Set the Tree Node Icon
*
* #param icon
*/
public void setIcon(String icon) {
this.icon = icon;
}
/**
* Set the Tree Node Id
*
* #param icon
*/
public void setId(String id) {
this.id = id;
if (this.attr == null) {
attr = new HashMap<String, Object>();
}
if (this.attr.containsKey("id")) {
this.attr.remove("id");
}
this.attr.put("id", id);
}
/**
* Set the Tree Node State open or closed
*
* #param state
*/
public void setState(String state) {
this.state = state;
}
/**
* Set the Tree Node Title
*
* #param title
*/
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("TreeNode [id=").append(id).append(", title=").append(
title).append(", icon=").append(icon).append(", state=")
.append(state).append(", attr=").append(attr).append(
", children=").append(children).append("]");
return builder.toString();
}
}
For Each Node It generates output as
<li id="C0" class="jstree-closed jstree-last">
<ins class="jstree-icon ui-icon ui-icon-triangle-1-e"> </ins>
<a href="#" class="ui-state-default">
<ins class="jstree-icon ui-icon ui-icon-folder-collapsed"> </ins>
Node C0
</a>
</li>
I want to assign each node specific url to corresponding anchor tag generated as above.
Any help appreciated, thanks!