The test not run in other activity robotium - 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();
}

Related

netty different channelpool and exception process

I am new to netty and I have a problem using my netty program.
in initConnection method I want to make a different channelpool for each group.
when user group A come in my sendToMessage I want to create channelPool A
like this way user group B come in my sendToMessage I want to create channelPool B and next time if user group A come in again, i will return channelPool A
Is it right to try doing this? Is it possible?
FixedChannelPool error handling
tell me how can I FixedChannelPool error handling? Could I use acquireTimeoutMillis over time.how?
Here is my code
#Service
public class NettyPoolService {
public static final AttributeKey<CompletableFuture<String>> FUTURE = AttributeKey.valueOf("future");
private static final StringDecoder stringDecoder = new StringDecoder(CharsetUtil.UTF_8);
private static final StringEncoder stringEncoder = new StringEncoder(CharsetUtil.UTF_8);
private static ChannelPool channelPool;
private static EventLoopGroup eventLoopGroup;
#Value("${host}")
private String host;
#Value("${port}")
private String port;
#Value("${connection.count}")
private String numberOfConnections;
#Value("${thread.count}")
private String numberOfThreads;
private synchronized void initConnection (String host, int port, int numberOfThreads, int numberOfConnections,String userGroup) {
if ( (channelPool != null) && (eventLoopGroup != null) ) {
return;
}
System.out.println("#############################################");
System.out.println("initConnection start");
eventLoopGroup = new NioEventLoopGroup(numberOfThreads);
Bootstrap bootstrap = new Bootstrap();
bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
//bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
//bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
//bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).remoteAddress(host, port);
int acquireTimeoutMillis = 10000;
int maxPendingAcquires = Integer.MAX_VALUE;
channelPool = new FixedChannelPool(bootstrap,
new AbstractChannelPoolHandler() {
public void channelCreated(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// decoders
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("stringDecoder", stringDecoder);
// encoders
pipeline.addLast("stringEncoder", stringEncoder);
// business logic handler
pipeline.addLast("clientHandler", new ClientPoolHandler(channelPool));
}
},
ChannelHealthChecker.ACTIVE,//eventloop
AcquireTimeoutAction.NEW, //timeout
acquireTimeoutMillis, //
numberOfConnections, //
maxPendingAcquires); //
System.out.println("initConnection End");
System.out.println("#############################################");
}//initConnection
public void sendToMessage(String message,String GroupId) {
System.out.println("=============GroupId=============:"+GroupId);
if (channelPool == null) {
initConnection(host, Integer.parseInt(port.trim()), Integer.parseInt(numberOfThreads.trim()), Integer.parseInt(numberOfConnections.trim()) );
}
final CompletableFuture<String> future = new CompletableFuture<String>();
Future<Channel> channelFuture = channelPool.acquire();
System.out.println("=============channelFuture.get()=============:"+channelFuture.toString());
channelFuture.addListener(new FutureListener<Channel>() {
public void operationComplete(Future<Channel> f) {
if (f.isSuccess()) {
Channel channel = f.getNow();
channel.attr(NettyPoolClientService.FUTURE).set(future);
channel.writeAndFlush(message, channel.voidPromise());
}
}
});
channelFuture.syncUninterruptibly();
}//sendToBnp
}

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

How to use MetaTrader4.Manager.Wrapper to listening the event of TradeAdded/TradeClosed/TradeDeleted

I wand to listening the event of TradeAdded/TradeClosed/TradeDeleted ,that's my code:
public partial class Demo : Form
{
public static ConnectionParameters conParam = new ConnectionParameters();
public static ClrWrapper mt;
private void Hedera_Load(object sender, EventArgs e)
{
Login();
}
public void Login()
{
conParam = new ConnectionParameters
{
Login = serverConfig.ManageAccount,
Password = serverConfig.ManagePassword,
Server = serverConfig.ManageServer
};
mt = new ClrWrapper(conParam);
List<UserRecord> users = mt.UsersRequest().ToList();
mt.TradeClosed +=new TradeRecordUpdated(this.MyTradeClosed);
mt.TradeDeleted += new TradeRecordUpdated(this.MyTradeDeleted);
mt.TradeAdded += new TradeRecordUpdated(this.MyTradeAdded);
}
public void MyTradeAdded(ClrWrapper mt, TradeRecord tradeRecord)
{
MessageBox.Show("MyTradeAdded");
}
public void MyTradeClosed(ClrWrapper mt, TradeRecord tradeRecord)
{
MessageBox.Show("MyTradeClosed");
}
public void MyTradeDeleted(ClrWrapper mt, TradeRecord tradeRecord)
{
MessageBox.Show("MyTradeDeleted");
}
}
When i trade on the MetaTrader4 client ,I want to get the notify in my C# program.
“UsersRequest” is ok now,but the event does not run.
Where is wrong in my code ?
Can you write an example for me?
Those events are fired only in extended pumping mode. so you have to switch:
public void Login()
{
conParam = new ConnectionParameters
{
Login = serverConfig.ManageAccount,
Password = serverConfig.ManagePassword,
Server = serverConfig.ManageServer
};
mt = new ClrWrapper(conParam);
List<UserRecord> users = mt.UsersRequest().ToList();
mt.TradeClosed +=new TradeRecordUpdated(this.MyTradeClosed);
mt.TradeDeleted += new TradeRecordUpdated(this.MyTradeDeleted);
mt.TradeAdded += new TradeRecordUpdated(this.MyTradeAdded);
metatrader.PumpingSwitchEx();
}
However, after switching into pumping mode, you won't be able to use non pumping methods

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

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