how to check which object was clicked? - android-recyclerview

I have a recyclerview.I need to excute code just when ImageView is clicked, the layout have a TextBox and a ImageView, now the code is excuted when TextView or ImageView was clicked indifferently.
public WordViewHolder(View itemView) {
super(itemView);
bicchiereBevuto = (TextView) itemView.findViewById(R.id.bicchierebevuto);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//cancella il database
// aggiungere controllo sull oggetto che è stato cliccato,
// solo se è stata cliccata l'immagine X si deve eseguire il codice
Integer pos = getLayoutPosition();
String text = this.bicchiereBevuto.getText().toString();
text = text.substring(text.length() - 5);
mDB.deleteBicchiere(text);
if (mContext instanceof ActivityMain)
((ActivityMain) mContext).upDate();
}

imageView.setOnClickListener(this);
NOT itemView.setOnClickListener(this);

Related

How to get an item from an array list of objects

So what do I do to "open" my array list of Appointment objects?
I have tried iteration but it gets 2 correct displays, or repeats the last entry. I need to set the text fields to a variable inside an array of objects. How do I go about that? This a calendar that saves your appointments into an array list the catch that the list is of an object type called appointments. I am so close to finishing I just can not get what to do with displaying or setting the information into the text fields.
import java.awt.Color;
import java.util.*;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Calendario extends Application {
private TextField s = new TextField();
private TextField m = new TextField();
private TextField t = new TextField();
private TextField w = new TextField();
private TextField th = new TextField();
private TextField f = new TextField();
private TextField st = new TextField();
private TextField dom = new TextField();
private TextField lun = new TextField();
private TextField mar = new TextField();
private TextField mie = new TextField();
private TextField hue = new TextField();
private TextField vir = new TextField();
private TextField sab = new TextField();
private Label firstd = new Label("Sunday");
private Label secd = new Label("Monday");
private Label thrd = new Label("Tuesday");
private Label fortd = new Label("Wednesday");
private Label fiftd = new Label("Thursday");
private Label sistd = new Label("Friday");
private Label svnd = new Label("Saturday");
private Button submit = new Button();
private Button open = new Button();
private Button clear = new Button();
private ArrayList<Appointment> date = new ArrayList<Appointment>();
public class Appointment{
DayOfWeek day;
String tiempo;
String d;
Appointment(String tiempo,String d){
if(Character.isDigit(tiempo.charAt(0)) && tiempo.endsWith("a") ||
tiempo.endsWith("p")){
this.tiempo = tiempo;
}
else{
throw new IllegalArgumentException("First input must be numeric and a for am"+
"p for pm");
}
this.d = d;
}
}
public void submit(){
for (DayOfWeek day : DayOfWeek.values()){
switch (day){
case SUNDAY:
Appointment sunday = new Appointment(s.getText(),dom.getText());
date.add(sunday);
break;
case MONDAY:
Appointment monday = new Appointment(m.getText(),lun.getText());
date.add(monday);
break;
case TUESDAY:
Appointment tuesday = new Appointment(t.getText(),mar.getText());
date.add(tuesday);
break;
case WEDNESDAY:
Appointment wednesday = new Appointment(w.getText(),mie.getText());
date.add(wednesday);
break;
case THURSDAY:
Appointment thursday = new Appointment(th.getText(),hue.getText());
date.add(thursday);
break;
case FRIDAY:
Appointment friday = new Appointment(f.getText(),vir.getText());
date.add(friday);
break;
case SATURDAY:
Appointment saturday = new Appointment(st.getText(),sab.getText());
date.add(saturday);
break;
default:
System.out.println("Error oh no help master");
break;
}
}
}
public void open(){
}
public void clear(){
date.clear();
}
#Override
public void start(Stage primaryStage) {
submit.setText("Submit");
submit.setStyle("-fx-background-color: #00ff00");
submit.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
submit();
}
});
open.setText("Open");
open.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
open();
}
});
clear.setText("Clear");
clear.setStyle("-fx-background-color: #ff0000");
clear.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
clear();
}
});
HBox frame = new HBox();
VBox sun = new VBox(10);
VBox mon = new VBox(10);
VBox tues = new VBox(10);
VBox wed = new VBox(10);
VBox thur = new VBox(10);
VBox fri = new VBox(10);
VBox sat = new VBox(10);
sun.getChildren().addAll(firstd,s,dom);
mon.getChildren().addAll(secd,m,lun);
tues.getChildren().addAll(thrd,t,mar);
wed.getChildren().addAll(fortd,w,mie);
thur.getChildren().addAll(fiftd,th,hue,clear);
fri.getChildren().addAll(sistd,f,vir,open);
sat.getChildren().addAll(svnd,st, sab,submit);
firstd.setTranslateX(20);
secd.setTranslateX(20);
thrd.setTranslateX(20);
fortd.setTranslateX(10);
fiftd.setTranslateX(20);
sistd.setTranslateX(20);
svnd.setTranslateX(20);
frame.getChildren().addAll(sun,mon,tues,wed,thur,fri,sat);
Scene scene = new Scene(frame, 600, 300);
primaryStage.setTitle("Appoinment Calendar");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
The code is not well written. Just consider how similar the code for all the days is. Why repeat yourself instead of coming up with a suitable data structure that allows you to access the objects more conveniently? Why create 2 x 7 TextFields when you can create 2 and use a loop to repeat the process?
One more thing you need to do is actually store the day of the week in you Appointment.
The open implementation in the following code assumes the content of the date list already contains the proper values even though currently the code only restores the last submitted values, if the user edits the TextFields.
private ArrayList<Appointment> date = new ArrayList<Appointment>();
public static class Appointment {
final DayOfWeek day;
final String tiempo;
final String d;
Appointment(String tiempo, String d, DayOfWeek day) {
if (Character.isDigit(tiempo.charAt(0)) && tiempo.endsWith("a") || tiempo.endsWith("p")) {
this.tiempo = tiempo;
} else {
throw new IllegalArgumentException("First input must be numeric and a for am" + "p for pm");
}
this.d = d;
this.day = day;
}
}
public void submit() {
// add appointment for each entry in the map
inputs.forEach((day, inputs) -> {
date.add(new Appointment(inputs[0].getText(), inputs[1].getText(), day));
});
}
public void open() {
// clear fields
inputs.values().stream().flatMap(Arrays::stream).forEach(TextField::clear);
// set text for all elements of date
date.forEach(appointment -> {
TextField[] fields = inputs.get(appointment.day);
fields[0].setText(appointment.tiempo);
fields[1].setText(appointment.d);
});
}
public void clear() {
date.clear();
}
private final Map<DayOfWeek, TextField[]> inputs = new EnumMap<>(DayOfWeek.class);
#Override
public void start(Stage primaryStage) {
Button submit = new Button("Submit");
submit.setStyle("-fx-background-color: #00ff00");
submit.setOnAction(event -> submit());
Button open = new Button("Open");
open.setOnAction(event -> open());
Button clear = new Button("Clear");
clear.setStyle("-fx-background-color: #ff0000");
clear.setOnAction(event -> clear());
GridPane grid = new GridPane();
grid.setVgap(10);
Locale locale = Locale.ENGLISH;
TextStyle textStyle = TextStyle.FULL;
Insets headerMargin = new Insets(0, 0, 0, 20);
// add inputs and label for days starting with sunday and store inputs in map
for (int i = 0; i < 7; i++) {
DayOfWeek day = DayOfWeek.SUNDAY.plus(i);
Label label = new Label(day.getDisplayName(textStyle, locale));
GridPane.setMargin(label, headerMargin);
TextField timeField = new TextField();
TextField dField = new TextField();
inputs.put(day, new TextField[] { timeField, dField });
grid.addColumn(i, label, timeField, dField);
}
HBox buttonContainer = new HBox(10, clear, open, submit);
buttonContainer.setAlignment(Pos.TOP_RIGHT);
VBox.setMargin(buttonContainer, new Insets(0, 20, 0, 0));
VBox root = new VBox(10, grid, buttonContainer);
Scene scene = new Scene(root, 600, 300);
primaryStage.setTitle("Appoinment Calendar");
primaryStage.setScene(scene);
primaryStage.show();
}

How to convert Custom View which contains Curve Text to Bitmap?

I have added custom view in relative layout and want bitmap of that relative layout containing curve text and want to store that bitmap inside imageview.
'
RelativeLayout relativeLayout;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout= (RelativeLayout) findViewById(R.id.rel);
imageView= (ImageView) findViewById(R.id.img1);
Circle circle=new Circle(MainActivity.this);
relativeLayout.addView(circle);
}
public class Circle extends View {
Paint paint = new Paint();
Path path = new Path();
private static final String s = "Hello world example";
public Circle(Context context) {
super(context);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
paint.setAntiAlias(true);
paint.setTextSize(30);
}
public void onDraw(Canvas c) {
c.rotate(180, getWidth()/2, getHeight()/2);
path.addCircle(getWidth()/2, getHeight()/2, 90, Path.Direction.CW);
c.drawTextOnPath(s, path, 0, 10, paint);
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}`'
Try this.
Bitmap bitmap = loadBitmapFromView(this, relImagePreviewParent); mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".JPEG";
File imageFile = new File(mPath);
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fout);
fout.flush();
fout.close();
String tempPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".JPEG";
File compressPath = new File(tempPath);
Bitmap tempbitmap = GIFUtils.compressImage(imageFile.getAbsolutePath(), ImageEditingActivity.this, bitmap);
OutputStream fileOut = new FileOutputStream(compressPath);
tempbitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
fileOut.flush();
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
public static Bitmap loadBitmapFromView(Context context, View v) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
v.measure(View.MeasureSpec.makeMeasureSpec(dm.widthPixels, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(dm.heightPixels, View.MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap returnedBitmap = Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
v.draw(c);
return returnedBitmap;
}

NativeExpressAdView java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

I am working on android app which fetch data using RecyclerView and Retrofit for parsing JSON Url. I had following tutorial on this Github
My project on Android Studio has no Errors and I'm able to run the Application. But when I open the MainActivity it crashes.
Error that i am get
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
This is the following line is on setUpAndLoadNativeExpressAds
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
This is MainActivity
public class MainActivity extends AppCompatActivity{
public static final int ITEMS_PER_AD = 3;
private static final int NATIVE_EXPRESS_AD_HEIGHT = 150;
private static final String AD_UNIT_ID = ADMOB_NATIVE_MENU_ID;
private StartAppAd startAppAd = new StartAppAd(this);
private RecyclerView mRecyclerView;
private List<Object> mRecyclerViewItems = new ArrayList<>();
private KontenAdapter kontenAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
// Use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView.
mRecyclerView.setHasFixedSize(true);
// Specify a linear layout manager.
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
// mRecyclerViewItems = new ArrayList<>();
// Update the RecyclerView item's list with menu items and Native Express ads.
// addMenuItemsFromJson();
loadJSON();
// initData();
setUpAndLoadNativeExpressAds();
}
/**
* Adds Native Express ads to the items list.
*/
private void addNativeExpressAds() {
// Loop through the items array and place a new Native Express ad in every ith position in
// the items List.
for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = new NativeExpressAdView(MainActivity.this);
mRecyclerViewItems.add(i, adView);
}
}
/**
* Sets up and loads the Native Express ads.
*/
private void setUpAndLoadNativeExpressAds() {
mRecyclerView.post(new Runnable() {
#Override
public void run() {
final float scale = MainActivity.this.getResources().getDisplayMetrics().density;
// Set the ad size and ad unit ID for each Native Express ad in the items list.
for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
final CardView cardView = (CardView) findViewById(R.id.ad_card_view);
final int adWidth = cardView.getWidth() - cardView.getPaddingLeft()
- cardView.getPaddingRight();
AdSize adSize = new AdSize((int) (adWidth / scale), NATIVE_EXPRESS_AD_HEIGHT);
adView.setAdSize(adSize);
adView.setAdUnitId(AD_UNIT_ID);
}
// Load the first Native Express ad in the items list.
loadNativeExpressAd(0);
}
});
}
/**
* Loads the Native Express ads in the items list.
*/
private void loadNativeExpressAd(final int index) {
if (index >= mRecyclerViewItems.size()) {
return;
}
Object item = mRecyclerViewItems.get(index);
if (!(item instanceof NativeExpressAdView)) {
throw new ClassCastException("Expected item at index " + index + " to be a Native"
+ " Express ad.");
}
final NativeExpressAdView adView = (NativeExpressAdView) item;
// Set an AdListener on the NativeExpressAdView to wait for the previous Native Express ad
// to finish loading before loading the next ad in the items list.
adView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
// The previous Native Express ad loaded successfully, call this method again to
// load the next ad in the items list.
loadNativeExpressAd(index + ITEMS_PER_AD);
}
#Override
public void onAdFailedToLoad(int errorCode) {
// The previous Native Express ad failed to load. Call this method again to load
// the next ad in the items list.
Log.e("MainActivity", "The previous Native Express ad failed to load. Attempting to"
+ " load the next Native Express ad in the items list.");
loadNativeExpressAd(index + ITEMS_PER_AD);
}
});
// Load the Native Express ad.
adView.loadAd(new AdRequest.Builder().build());
}
private void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.myjson.com/") //https://api.myjson.com/bins/v4dzd
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
mRecyclerViewItems = new ArrayList<Object>(Arrays.asList(jsonResponse.getKonten()));
addNativeExpressAds();
RecyclerView.Adapter adapter = new KontenAdapter(mRecyclerViewItems, getApplicationContext());
mRecyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
/**
* Adds {#link KontenItem}'s from a JSON file.
*/
private void addMenuItemsFromJson() {
try {
String jsonDataString = readJsonDataFromFile();
JSONArray menuItemsJsonArray = new JSONArray(jsonDataString);
for (int i = 0; i < menuItemsJsonArray.length(); ++i) {
JSONObject menuItemObject = menuItemsJsonArray.getJSONObject(i);
String menuItemName = menuItemObject.getString("name");
String menuItemDescription = menuItemObject.getString("description");
String menuItemPrice = menuItemObject.getString("price");
String menuItemCategory = menuItemObject.getString("category");
String menuItemImageName = menuItemObject.getString("photo");
String menuItemUrl = menuItemObject.getString("url");
KontenItem kontenItem = new KontenItem(menuItemName, menuItemDescription, menuItemPrice,
menuItemCategory, menuItemImageName, menuItemUrl);
mRecyclerViewItems.add(kontenItem);
}
} catch (IOException | JSONException exception) {
Log.e(MainActivity.class.getName(), "Unable to parse JSON file.", exception);
}
}
/**
* Reads the JSON file and converts the JSON data to a {#link String}.
*
* #return A {#link String} representation of the JSON data.
* #throws IOException if unable to read the JSON file.
*/
private String readJsonDataFromFile() throws IOException {
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
try {
String jsonDataString = null;
inputStream = getResources().openRawResource(R.raw.menu_items_json);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((jsonDataString = bufferedReader.readLine()) != null) {
builder.append(jsonDataString);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return new String(builder);
}
}
This is MyAdapter
public class KontenAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
// A menu item view type.
private static final int MENU_ITEM_VIEW_TYPE = 0;
// The Native Express ad view type.
private static final int NATIVE_EXPRESS_AD_VIEW_TYPE = 1;
// An Activity's Context.
private final Context mContext;
// The list of Native Express ads and menu items.
private final List<Object> mRecyclerViewItems;
public KontenAdapter(List<Object> recyclerViewItems, Context context) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
}
/**
* The {#link MenuItemViewHolder} class.
* Provides a reference to each view in the menu item view.
*/
public class MenuItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView menuItemName;
private TextView menuItemDescription;
private TextView menuItemPrice;
private TextView menuItemCategory;
private ImageView menuItemImage;
private TextView menuItemUrl;
MenuItemViewHolder(View view) {
super(view);
menuItemImage = (ImageView) view.findViewById(R.id.menu_item_image);
menuItemName = (TextView) view.findViewById(R.id.menu_item_name);
menuItemPrice = (TextView) view.findViewById(R.id.menu_item_price);
menuItemCategory = (TextView) view.findViewById(R.id.menu_item_category);
menuItemDescription = (TextView) view.findViewById(R.id.menu_item_description);
menuItemUrl = (TextView) view.findViewById(R.id.menu_item_url);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent detailIntent = new Intent(v.getContext(), PostActivity.class);
detailIntent.putExtra("name",menuItemName.getText().toString() );
detailIntent.putExtra("url", menuItemUrl.getText().toString());
mContext.startActivity(detailIntent);
}
}
/**
* The {#link NativeExpressAdViewHolder} class.
*/
public class NativeExpressAdViewHolder extends RecyclerView.ViewHolder {
NativeExpressAdViewHolder(View view) {
super(view);
}
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
/**
* Determines the view type for the given position.
*/
#Override
public int getItemViewType(int position) {
return (position % MainActivity.ITEMS_PER_AD == 0) ? NATIVE_EXPRESS_AD_VIEW_TYPE
: MENU_ITEM_VIEW_TYPE;
}
/**
* Creates a new view for a menu item view or a Native Express ad view
* based on the viewType. This method is invoked by the layout manager.
*/
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
View menuItemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.menu_item_container, viewGroup, false);
return new MenuItemViewHolder(menuItemLayoutView);
case NATIVE_EXPRESS_AD_VIEW_TYPE:
// fall through
default:
View nativeExpressLayoutView = LayoutInflater.from(
viewGroup.getContext()).inflate(R.layout.native_express_ad_container,
viewGroup, false);
return new NativeExpressAdViewHolder(nativeExpressLayoutView);
}
}
/**
* Replaces the content in the views that make up the menu item view and the
* Native Express ad view. This method is invoked by the layout manager.
*/
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
MenuItemViewHolder menuItemHolder = (MenuItemViewHolder) holder;
KontenItem kontenItem = (KontenItem) mRecyclerViewItems.get(position);
// Get the menu item image resource ID.
String imageName = kontenItem.getImageName();
int imageResID = mContext.getResources().getIdentifier(imageName, "drawable",
mContext.getPackageName());
// Add the menu item details to the menu item view.
menuItemHolder.menuItemImage.setImageResource(imageResID);
menuItemHolder.menuItemName.setText(kontenItem.getName());
menuItemHolder.menuItemPrice.setText(kontenItem.getPrice());
menuItemHolder.menuItemCategory.setText(kontenItem.getCategory());
menuItemHolder.menuItemDescription.setText(kontenItem.getDescription());
menuItemHolder.menuItemUrl.setText(kontenItem.getInstructionUrl());
break;
case NATIVE_EXPRESS_AD_VIEW_TYPE:
// fall through
default:
NativeExpressAdViewHolder nativeExpressHolder =
(NativeExpressAdViewHolder) holder;
NativeExpressAdView adView =
(NativeExpressAdView) mRecyclerViewItems.get(position);
ViewGroup adCardView = (ViewGroup) nativeExpressHolder.itemView;
// The NativeExpressAdViewHolder recycled by the RecyclerView may be a different
// instance than the one used previously for this position. Clear the
// NativeExpressAdViewHolder of any subviews in case it has a different
// AdView associated with it, and make sure the AdView for this position doesn't
// already have a parent of a different recycled NativeExpressAdViewHolder.
if (adCardView.getChildCount() > 0) {
adCardView.removeAllViews();
}
if (adView.getParent() != null) {
((ViewGroup) adView.getParent()).removeView(adView);
}
// Add the Native Express ad to the native express ad view.
adCardView.addView(adView);
}
}
}
KontenItem.java
class KontenItem {
private final String name;
private final String description;
private final String price;
private final String category;
private final String imageName;
private final String instructionUrl;
public KontenItem(String name, String description, String price, String category,
String imageName, String instructionUrl) {
this.name = name;
this.description = description;
this.price = price;
this.category = category;
this.imageName = imageName;
this.instructionUrl = instructionUrl;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getPrice() {
return price;
}
public String getCategory() {
return category;
}
public String getImageName() {
return imageName;
}
public String getInstructionUrl() {
return instructionUrl;
}
}
Thanks in advance!
You are calling addNativeExpressAds() and
for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
in different threads. So, mRecyclerViewItems.get(i) is used before its initialization.
I would suggest to use
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
mRecyclerViewItems = new ArrayList<Object>(Arrays.asList(jsonResponse.getKonten()));
addNativeExpressAds();
RecyclerView.Adapter adapter = new KontenAdapter(mRecyclerViewItems, getApplicationContext());
mRecyclerView.setAdapter(adapter);
setUpAndLoadNativeExpressAds(); // << ADD THIS METHOD HERE AND REMOVE THE OTHER CALLING
}
Your problem is that mRecyclerViewItems is a zero based array/collection. Yet in setUpAndLoadNativeExpressAds() you will iterate even if you have no elements, and then ask for element 0.
for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
..
}
you should instead
for (int i = 0; i < mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
..
}

Implementing a Launcher Framework - disabled Apply button on dialog

I am working on a eclipse plugin and implementing a custom launcher as per the link https://eclipse.org/articles/Article-Launch-Framework/launch.html .
I have implemented a class BrowsersTab which extends AbstractLaunchConfigurationTab and implemented all the methods. The problem is that when I call the updateLaunchConfigurationDialog(); on the selection event , the 'Apply' Button remains disabled.
Code :
public class BrowsersTab extends AbstractLaunchConfigurationTab {
private Button chrome;
private Button firefox;
private Button safari;
private Button ie;
private Button opera;
private Button android;
private Button ios;
#Override
public void createControl(Composite parent) {
Composite comp = new Composite(parent, SWT.NONE);
setControl(comp);
GridLayout topLayout = new GridLayout();
comp.setLayout(topLayout);
Group fGroup = new Group(comp, SWT.NONE);
fGroup.setFont(parent.getFont());
fGroup.setLayout(new GridLayout(2, true));
fGroup.setText(DialogMessages.browserSelection);
chrome = new Button(fGroup, SWT.CHECK);
chrome.setText("Google Chrome");
chrome.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println("chrome selected");
updateLaunchConfigurationDialog();
}
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
});
Image chromeIcon= getBrowserIcon("chrome-browser-24X24.png");
if(null!=chromeIcon)
chrome.setImage(chromeIcon);
Combo comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
firefox = new Button(fGroup, SWT.CHECK);
firefox.setText("Mozilla Firefox");
Image firefoxIcon= getBrowserIcon("Firefox-icon.png");
if(null!=firefoxIcon)
firefox.setImage(firefoxIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
safari = new Button(fGroup, SWT.CHECK);
safari.setText("Apple Safari");
Image safariIcon= getBrowserIcon("Safari-icon.png");
if(null!=safariIcon)
safari.setImage(safariIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
ie = new Button(fGroup, SWT.CHECK);
ie.setText("Internet Explorer");
Image ieIcon= getBrowserIcon("Internet-Explorer-icon.png");
if(null!=ieIcon)
ie.setImage(ieIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
opera= new Button(fGroup, SWT.CHECK);
opera.setText("Opera");
Image operaIcon= getBrowserIcon("browser-opera-icon.png");
if(null!=operaIcon)
opera.setImage(operaIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
android= new Button(fGroup, SWT.CHECK);
android.setText("Android");
Image androidIcon= getBrowserIcon("android-platform-icon.png");
if(null!=androidIcon)
android.setImage(androidIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
ios= new Button(fGroup, SWT.CHECK);
ios.setText("Mobile Safari");
Image iosIcon= getBrowserIcon("Apple-grey-icon.png");
if(null!=iosIcon)
ios.setImage(iosIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
}
#Override
public String getName() {
return "Browsers";
}
public Image getBrowserIcon(String name){
Image icon=null;
try {
icon = AbstractUIPlugin.imageDescriptorFromPlugin("SuitACore","icons/"+name).createImage();
} catch (Exception e) {
// Swallow it; we'll do without images
}
return icon;
}
public Image getImage() {
Image tab=null;
try {
tab = AbstractUIPlugin.imageDescriptorFromPlugin("SuitACore","icons/browser.png").createImage();
} catch (Exception e) {
// Swallow it; we'll do without images
}
return tab;
}
public void initializeFrom(ILaunchConfiguration configuration) {
try {
List<String> browsersDefaults = new ArrayList<String>();
browsersDefaults.add("chrome");
List<String> browsers =configuration.getAttribute("browsers", browsersDefaults);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
chrome.setSelection(true);
}
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
List<String> browsers = new ArrayList<String>();
browsers.add("chrome");
configuration.setAttribute("browser",browsers );
}
public void setDefaults(ILaunchConfigurationWorkingCopy arg0) {
}
}
You must call updateLaunchConfigurationDialog() whenever anything changes that might update the Apply button - so all checkboxes and combos.
You must also save everything that changes in the ILaunchConfigurationWorkingCopy in the performApply method. The Apply button state is determined by checking that the working copy is different from the original configuration.

Adding numbers to an arraylist from the Jtextfield

I am sure its very simple but this is my first java class. the user enters a number into the input Jtextfield. the Add button is supposed to add that number to the arraylist. I am having trouble figuring out how to do that exactly. Any help you can give me would be awesome
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class ArrayExercise extends JFrame
{
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 300;
private JPanel panel1;
private JPanel panel2;
private JLabel messageLabel;
private JTextField input;
private JTextArea output;
private JButton addButton;
private JButton list;
private JButton rlist;
private JButton clear;
public ArrayExercise()
{
setTitle("Array Exercise");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panel1();
panel2();
add(panel1, BorderLayout.EAST);
add(panel2, BorderLayout.WEST);
setVisible(true);
input.requestFocus();
}
private void panel1()
{
messageLabel = new JLabel("Input");
input = new JTextField(5);
addButton = new JButton("Add");
list = new JButton("List");
rlist = new JButton("R-List");
clear = new JButton("Clear");
addButton.addActionListener(new ButtonListener());
list.addActionListener(new ButtonListener());
rlist.addActionListener(new ButtonListener());
clear.addActionListener(new ButtonListener());
panel1 = new JPanel();
panel1.setLayout(new GridLayout(6,1));
panel1.add(messageLabel);
panel1.add(input);
panel1.add(addButton);
panel1.add(list);
panel1.add(rlist);
panel1.add(clear);
}
private void panel2()
{
output = new JTextArea(12, 10);
panel2 = new JPanel();
panel2.add(output);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String in;
int number;
int index = 0;
ArrayList<String> list = new ArrayList<>();
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Add"))
{
index++;
in = addButton.getText();
list.add(addButton.getText());
if (index == 9)
{
input.setEditable(false);
addButton.setEnabled(false);
}
output.setText(in + " added.");
input.setText(null);
input.requestFocus();
}
if (actionCommand.equals("List"))
{
for(int x = 0; x <= list.size(); x++)
{
output.setText((x+1)+ ". " + list.get(x) + "\n");
}
}
}
}
public static void main(String[] args)
{
new ArrayExercise();
}
}
You have ArrayList list which is not adding any string value to that list and you are trying to run that over loop to get you values. If you are not adding anything to list then how can you extract anything out of it.
ArrayList<String> list = new ArrayList<String>();
For each button attach different actionlistener as all buttons are not supposed to act same way.
To add elements in ArrayList use this
list.add(input.getText()); // adding text entered into input textfield.
Make a list
List item
Make a TextField
Make Button Add Listener to button
Get the text from the text field or text area Add to array list
object
Here is all the work you need to do:
ArrayList<String> arrayObject= new ArrayList<String>();
JButton button = new JButton();
JtextField textBox = new JtextField ();
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//inside your action listener:
String add_item_to_array = textBox.getText().trim();
arrayObject.add(add_item_to_array);
}
});