Adding numbers to an arraylist from the Jtextfield - arraylist

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);
}
});

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();
}

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) {
..
}

The test not run in other activity robotium

I'm using robotium to test an application. In my test class have 2 tests:
public class MainActivityTestAll extends ActivityInstrumentationTestCase2<MainActivity> {
private Solo solo;
private static TestItem item;
private boolean isTimeOut;
private ArrayList<Button> arrButton;
private static final String USER_NAME = "varick";
private static final String PASSWORD = "123456";
private static final String BTN_DISMISS = "Dismiss";
private static final String BTN_OK = "OK";
private static final String BTN_TRYAGAIN = "Try Again";
private static final String BTN_CANCEL = "Cancel";
private static final String BTN_GETSTARTED = "Get Started";
private static final String BTN_EXIT = "Exit";
private static EditText edtName, edtPass;
private View inflaterView;
private Button btnLight, btnSwitch, btnOutlet;
public MainActivityTestAll(String name) {
super(MainActivity.class);
setName(name);
}
public void setUp() throws Exception {
solo = new Solo(getInstrumentation(), getActivity());
edtName = (EditText) solo.getView(R.id.edittext_userName);
edtPass = (EditText) solo.getView(R.id.edittext_passWord);
LayoutInflater i = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
inflaterView = i.inflate(R.layout.consumer_welcome, null);
isTimeOut = true;
item = new TestItem();
}
#MediumTest
public void test1_DoorLock_Click() throws Exception {
Login();
View view = (View) solo.getView(R.id.fragment_holder);
solo.waitForView(view);
solo.clickOnView(view);
solo.waitForActivity(ConsumerSystemMapDetailPhone.class.getName());
btnLight = (Button) solo.getView(R.id.btnLight);
btnSwitch = (Button) solo.getView(R.id.btnSwitch);
btnOutlet = (Button) solo.getView(R.id.btnOutlet);
assertNotNull(btnLight);
assertNotNull(btnSwitch);
assertNotNull(btnOutlet);
solo.clickOnView(btnLight);
solo.clickOnView(btnSwitch);
solo.clickOnView(btnOutlet);
solo.sleep(2000);
arrButton = solo.getCurrentViews(Button.class,
solo.getView(R.id.consumerzoom_main_container));
assertTrue("DoorLock button had not active", clickonDoorlock(arrButton.get(0)));
}
#MediumTest
public void test2_Switch_Click() throws Exception{
/*
btnLight = (Button) solo.getView(R.id.btnLight);
btnOutlet = (Button) solo.getView(R.id.btnOutlet);
assertNotNull(btnLight);
assertNotNull(btnOutlet);
solo.clickOnView(btnLight);
solo.clickOnView(btnOutlet);
*/
btnSwitch = (Button) solo.getView(R.id.btnSwitch);
assertNotNull(btnSwitch);
solo.clickOnView(btnSwitch);
solo.sleep(2000);
clickonSpinner(1, 3);
solo.sleep(1000);
arrButton = solo.getCurrentViews(Button.class, solo.getView(R.id.consumerzoom_main_container));
clickonSwitch(arrButton.get(0), true, item.getbtnLevel2());
clickonSpinner(0, 1);
clickonSpinner(1, 4);
solo.sleep(1000);
arrButton = solo.getCurrentViews(Button.class, solo.getView(R.id.consumerzoom_main_container));
clickonSwitchInfortop(arrButton.get(0), false, item.getbtnParentLevel8(), item.getbtnLevel3());
exitApp();
}
My problem is after test1 finish the test2 do nothing. It still running but do nothing. When I put the code from test2 into test1 it run ok.
I'm not sure what's wrong here but I guess the reason is because the test2 doesn't start from MainActivity.
I think it's because you are missing tearDown method:
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
}

Null pointer Exception using a PrintWriter

I have that inner class shown under. This is for a client/server and I had nullpointer exception at the "println" from an PrintWriter. I have tried all I know to solve it but, unsuccessfully. Anyone can give me a tip or an idea for what I have to do. Thanks guys!
Here's the FULL CLASS code:
public class ChatClient extends JFrame{
private JTextField textToSend;
private Socket socket;
private PrintWriter writer
private String name;
private JTextArea receivedText;
private Scanner reader;
public ChatCliente(String name){
super("Chat: "+ name);
this.name = name;
Font font = new Font("Serif", Font.PLAIN, 20);
textToSend = new JTextField();
textToSend.setFont(font);
JButton btn = new JButton("Send");
btn.setFont(font);
btn.addActionListener(new Listener());
Container content = new JPanel();
content.setLayout(new BorderLayout());
content.add(BorderLayout.CENTER, textToSend);
content.add(BorderLayout.EAST, btn);
receivedText = new JTextArea();
receivedText.setFont(font);
JScrollPane scroll = new JScrollPane(receivedText);
getContentPane().add(BorderLayout.CENTER, scroll);
getContentPane().add(BorderLayout.SOUTH, content);
configureNetwork();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
setVisible(true);
}
private void configureNetwork(){
try{
socket = new Socket("127.0.0.1",5000);
writer = new PrintWriter(socket.getOutputStream());
reader = new Scanner(socket.getInputStream());
new Thread(new ServerThread()).start();
}catch (Exception e){}
}
private class Listener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
try{
String s = name;
String t = textToSend.getText();
System.out.println(name+" : "+ textToSend.getText());
writer.println(s+" : "+t);
writer.flush();
textToSend.setText("");
textToSend.requestFocus();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
private class ServerThread implements Runnable{
#Override
public void run() {
String text;
try{
while((text = reader.nextLine()) != null){
receivedText.append(text+"\n");
}
}catch(Exception e){}
}
}
}
'name' is not declared.
Maybe you meant:
String s = "name";
Just some stupid thing that happened to me: do not insert "/" in the name of your file, or it will of course look for an extra folder that probably isn't there.
int number = 1, total = 126;
String path = "some/path/found " + number + "/" + total;
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(path, true)));

Java initialization question

JPanel p2 = new JPanel(new GridLayout(6,1));
ButtonGroup tubtype = new ButtonGroup();
JRadioButton roundrButton = new JRadioButton("Round", true);
tubtype.add(roundrButton);
JRadioButton ovalrButton = new JRadioButton("Oval", false);
tubtype.add(ovalrButton);
calcButton = new JButton("Calculate Volume");
exitButton = new JButton("Exit");
hlength = new JTextField(5);
hwidth = new JTextField(5);
hdepth = new JTextField(5);
hvolume = new JTextField(5);
lengthLabel = new JLabel("Enter the tub's length (ft):");
widthLabel = new JLabel("Enter the tub's width (ft):");
depthLabel = new JLabel("Enter the tub's depth (ft):");
volumeLabel = new JLabel("The tub's volume (ft^3):");
p2.add(roundrButton);
p2.add(ovalrButton);
p2.add(lengthLabel);
p2.add(hlength);
p2.add(widthLabel);
p2.add(hwidth);
p2.add(depthLabel);
p2.add(hdepth);
p2.add(volumeLabel);
p2.add(hvolume);
p2.add(calcButton);
p2.add(exitButton);
tab.addTab( "Hot Tubs", null, p2, " Panel #1" );
calcButtonHandler2 ihandler =new calcButtonHandler2();
calcButton.addActionListener(ihandler);
exitButtonHandler ghandler =new exitButtonHandler();
exitButton.addActionListener(ghandler);
FocusHandler hhandler =new FocusHandler();
hlength.addFocusListener(hhandler);
hwidth.addFocusListener(hhandler);
hdepth.addFocusListener(hhandler);
hvolume.addFocusListener(hhandler);
// add JTabbedPane to container
getContentPane().add( tab );
setSize( 550, 500 );
setVisible( true );
}
public class calcButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
DecimalFormat num =new DecimalFormat(",###.##");
double sLength, sWidth, sdepth, Total;
sLength = Double.valueOf(plength.getText());
sWidth =Double.valueOf(pwidth.getText());
sdepth =Double.valueOf(pdepth.getText());
if(e.getSource() == pcalcButton) {
Total = sLength * sWidth * sdepth;
pvolume.setText(num.format(Total));
try{
String value=pvolume.getText();
File file = new File("output.txt");
FileWriter fstream = new FileWriter(file,true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Length= "+sLength+", Width= "+sWidth+", Depth= "+sdepth+" so the volume of Swimming Pool is "+value);
out.newLine();
out.close();
}
catch(Exception ex){}
}
}
}
public class calcButtonHandler2 implements ActionListener {
public void actionPerformed(ActionEvent g) {
DecimalFormat num =new DecimalFormat(",###.##");
double cLength, cWidth, cdepth, Total;
cLength = Double.valueOf(hlength.getText());
cWidth = Double.valueOf(hwidth.getText());
cdepth = Double.valueOf(hdepth.getText());
try
{
AbstractButton roundrButton;
if(roundrButton.isSelected())
{
Total = Math.PI * Math.pow(cLength / 2.0, 2) * cdepth;
}
else
{
Total = Math.PI * Math.pow(cLength * cWidth, 2) * cdepth;
}
hvolume.setText(""+num.format(Total));
}
catch(Exception ex){}
}
}
}
class exitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent g){
System.exit(0);
}
}
class FocusHandler implements FocusListener {
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
}
public static void main( String args[] )
{
Final tabs = new Final();
tabs.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
I am getting an error that says my roundrButton may not have been initialized. Please help.
The problem is these lines here:
try
{
AbstractButton roundrButton;
if(roundrButton.isSelected())
{
You're declaring a variable called roundrButton, and then attempting to call .isSelected() on it. You never assign anything to roundButton, though, so it is going to be null.
It seems like you might want to be referring to the roundrButton that you declared earlier. Have you considered making it a field of your class?
The error happens here:
try {
AbstractButton roundrButton;
if (roundrButton.isSelected()) {
You declared a variable called roundrButton but did not assign any object to it.
Then you called a method on, well, who knows? There is no object on which to call the method, because the variable roundrButton never received a value.
I guess your problem is in method actionPerformed of class calcButtonHandler2 :
try {
AbstractButton roundrButton;
if(roundrButton.isSelected())
roundrButton is indeed not initialized and it will lead to a NullPointerException at runtime.