I'm creating a boolean array pre-populated with false values. I understand that I don't have to declare false values as they are automatically assigned however I've been trying different methods to try and solve the problem.
package com.bignerdranch.android.geoquiz;
import android.app.ActionBar;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends ActionBarActivity {
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private Button mCheatButton;
private TextView mQuestionTextView;
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true),
};
private int mCurrentIndex = 0;
private boolean mIsCheater;
private boolean[] mCheatedAnswers = new boolean[] {false, false, false, false, false};
I have a breakpoint on the last line, and when the program breaks here the mCheatedAnswers is instantiated as null. I don't understand why as I have given it a boolean array - does anyone know why this could be?
The previous variables all have the correct values assigned to them when I check them in the debug mode.
If you've put the breakpoint on the last line, then when it hits, the assignment hasn't executed yet.
If you put a breakpoint in the constructor body - or just step over the line - you'll find the value is assigned appropriately. (It would be simpler just to use new boolean[5], mind you... false is the default value... Mind you, it would probably be better to have a class which included the question and whether or not the user cheated. Then you'd only need one collection.)
Related
I'm really new to Android. I'm trying to pass the data to the text view of another class. But for some reason, it does not appear in the second class / page (the textview didnt change). I was able to do it when I was not using android annotation, but I was told that using annotations is a lot easier so I'm trying to convert it to that but for some reason it isn't working? I might be missing something.
Main 1
package com.example.faculty.labactivity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
#EActivity(R.layout.world)
public class MainActivity extends AppCompatActivity {
#ViewById(R.id.userName)
EditText user;
#Click(R.id.signIn)
public void signInButton(){
Main2Activity_.intent().name(user.getText().toString()).start();
}
Main 2
package com.example.faculty.labactivity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
#EActivity(R.layout.welcome)
public class Main2Activity extends AppCompatActivity {
#Extra("name")
String n;
#ViewById(R.id.name)
TextView tv;
Intent in2 = getIntent();
#AfterViews
void home(){
tv.setText("Hello, " + n + " !");
}
}
In your receiving Activity (for example MyActivity) you must declare the name of the object you want to receive like that
#Extra("name")
String name;
To pass data, when you create your intent you must do something like this:
Main2Activity_.intent(this).name(user.getText().toString()).start();
If you need a more precise solution edit your question to show more of your code.
You can look at the official doc for a more complete example
It might have to do with the dependencies you should add for the annotations to your project_root/build.gradle and app/build.gradle files.
Make sure to check this thread: what is Android Annotations and why we use Android Annotations?
I would like to call Scala code from Java. However I can only manipulate a specific portion of the code (the code within the apply method in the example below). Additionally I can add JARs to the class path.
Example
pure Java Code:
// system imports
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.*;
import org.apache.spark.api.java.function.*;
import org.apache.spark.sql.types.*;
import org.apache.spark.sql.*;
import com.knime.bigdata.spark.core.exception.*;
import com.knime.bigdata.spark1_6.api.RowBuilder;
import com.knime.bigdata.spark1_6.jobs.scripting.java.AbstractSparkJavaSnippet;
import com.knime.bigdata.spark1_6.jobs.scripting.java.AbstractSparkJavaSnippetSource;
import com.knime.bigdata.spark1_6.jobs.scripting.java.AbstractSparkJavaSnippetSink;
// Your custom imports:
// system variables
public class SparkJavaSnippet extends AbstractSparkJavaSnippet {
private static final long serialVersionUID = 1L;
// Your custom variables:
// expression start
public JavaRDD<Row> apply(final JavaSparkContext sc, final JavaRDD<Row> rowRDD1, final JavaRDD<Row> rowRDD2) throws Exception {
//*************************************************
//Specify the fraction of data to sample and if
//the sampling should be performed with replacement
//*************************************************
final double fraction = 0.5;
final boolean withReplacement = false;
//final boolean withReplacement = true;
//Returns a sample of the incoming RDD
return rowRDD1.sample(withReplacement, fraction);
// expression end
}
}
partly Scala code (not working):
// system imports
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.*;
import org.apache.spark.api.java.function.*;
import org.apache.spark.sql.types.*;
import org.apache.spark.sql.*;
import com.knime.bigdata.spark.core.exception.*;
import com.knime.bigdata.spark1_6.api.RowBuilder;
import com.knime.bigdata.spark1_6.jobs.scripting.java.AbstractSparkJavaSnippet;
import com.knime.bigdata.spark1_6.jobs.scripting.java.AbstractSparkJavaSnippetSource;
import com.knime.bigdata.spark1_6.jobs.scripting.java.AbstractSparkJavaSnippetSink;
// Your custom imports:
// system variables
public class SparkJavaSnippet extends AbstractSparkJavaSnippet {
private static final long serialVersionUID = 1L;
// Your custom variables:
// expression start
public JavaRDD<Row> apply(final JavaSparkContext sc, final JavaRDD<Row> rowRDD1, final JavaRDD<Row> rowRDD2) throws Exception {
//Scala code begins here
val fraction = 0.5
val withReplacement = false
rowRDD1.sample(withReplacement, fraction)
//Scala code ends here
// expression end
}
}
Question
How do I write the code between //Scala code starts here and //Scala code ends here such that I can use Scala code in there - embedded in the Java code?
(I cannot change the code outside those comments! However I can add JARs to the class path!)
Context
I have implemented a NatTable (v1.1.0.201405012245) - please consider this simplified example:
package testproject;
import java.util.ArrayList;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration;
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
import org.eclipse.nebula.widgets.nattable.config.EditableRule;
import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
import org.eclipse.nebula.widgets.nattable.data.IColumnAccessor;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.data.ListDataProvider;
import org.eclipse.nebula.widgets.nattable.edit.EditConfigAttributes;
import org.eclipse.nebula.widgets.nattable.edit.config.DefaultEditBindings;
import org.eclipse.nebula.widgets.nattable.edit.config.DefaultEditConfiguration;
import org.eclipse.nebula.widgets.nattable.edit.editor.TextCellEditor;
import org.eclipse.nebula.widgets.nattable.grid.GridRegion;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.nebula.widgets.nattable.layer.LabelStack;
import org.eclipse.nebula.widgets.nattable.layer.cell.IConfigLabelAccumulator;
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
import org.eclipse.nebula.widgets.nattable.selection.config.DefaultSelectionStyleConfiguration;
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
public class ViewPart1 extends ViewPart
{
#Override
public void createPartControl(final Composite parent)
{
final ArrayList<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
final IColumnAccessor<String> columnAccessor = new IColumnAccessor<String>()
{
#Override
public void setDataValue(final String rowObject, final int columnIndex, final Object newValue)
{
if (!(newValue instanceof String) || ((String) newValue).contains("x"))
{
MessageDialog.openError(getSite().getShell(), "Error", "Invalid Input");
return;
}
list.set(list.indexOf(rowObject), (String) newValue);
}
#Override
public Object getDataValue(final String rowObject, final int columnIndex)
{
return rowObject;
}
#Override
public int getColumnCount()
{
return 1;
}
};
final IDataProvider dataProvider = new ListDataProvider<>(list, columnAccessor);
final DataLayer dataLayer = new DataLayer(dataProvider);
final SelectionLayer selectionLayer = new SelectionLayer(dataLayer);
final ViewportLayer viewportLayer = new ViewportLayer(selectionLayer);
final NatTable table = new NatTable(parent, viewportLayer, false);
GridDataFactory.fillDefaults().grab(true, true).applyTo(table);
viewportLayer.addConfiguration(new DefaultEditConfiguration());
viewportLayer.addConfiguration(new DefaultEditBindings());
viewportLayer.setRegionName(GridRegion.BODY);
viewportLayer.setConfigLabelAccumulator(new IConfigLabelAccumulator()
{
#Override
public void accumulateConfigLabels(final LabelStack configLabels, final int columnPosition, final int rowPosition)
{
configLabels.addLabel("myLabel");
}
});
table.setConfigRegistry(new ConfigRegistry());
table.addConfiguration(new DefaultNatTableStyleConfiguration());
table.addConfiguration(new DefaultSelectionStyleConfiguration());
table.addConfiguration(new AbstractRegistryConfiguration()
{
#Override
public void configureRegistry(final IConfigRegistry registry)
{
registry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new TextCellEditor(true), DisplayMode.NORMAL, "myLabel");
registry.registerConfigAttribute(EditConfigAttributes.CELL_EDITABLE_RULE, EditableRule.ALWAYS_EDITABLE, DisplayMode.NORMAL, "myLabel");
}
});
table.configure();
}
#Override
public void setFocus()
{
}
}
Of course, this is not the real code, but my issue can be demonstrated with this code as well.
The important part is that in my actual project, when the user modifies a value, I need to update a model (including a complex tree of dependencies) and if that fails (e.g. in a numerical calculation the change results in a division by zero), I need to show an error (and revert to the previous value).
To show my core problem, in the code shown here I check for a simple condition in IColumnAccessor#setDataValue (the input contains an 'x') and show the error accordingly.
Problem
My actual problem is that if you enter an x into the TextCellEditor, the error dialog pops up twice (in sequence - meaning that as soon as I click ok for the first one, the second one will show).
Analysis
My analysis shows that the reason is that setDataValue is called twice:
because the ENTER key is pressed - Stacktrace
TextCellEditor(AbstractCellEditor).commit(SelectionLayer$MoveDirectionEnum, boolean) line: 331
TextCellEditor(AbstractCellEditor).commit(SelectionLayer$MoveDirectionEnum) line: 326
TextCellEditor$1.keyPressed(KeyEvent) line: 246
because the TextCellEditor loses focus - Stacktrace
TextCellEditor(AbstractCellEditor).commit(SelectionLayer$MoveDirectionEnum, boolean, boolean) line: 341
TextCellEditor(AbstractCellEditor).commit(SelectionLayer$MoveDirectionEnum, boolean) line: 331
AbstractCellEditor$InlineFocusListener.focusLost(FocusEvent) line: 462
So, my main question is: how can I prevent (or at least detect) the second event?
The issue with your implementation is, that you are performing a conversion in the IColumnAccessor and open a dialog to inform the user about the error. But that is not the way to do this with NatTable because of various use cases.
If you need to perform conversion and/or validation you should register an appropriate IDisplayConverter and an IDataValidator. As you need a String you don't need to register a different converter, as the default converter that is registered via DefaultEditConfiguration is doing that already. So what you need is an IDataValidator that checks for the value x and throws a ValidationFailedException in that case. If you register the DialogErrorHandling as validation error handler, the error with the exception message will be shown in a dialog. And the checks for not opening the dialog twice is done internally.
This is explained in the (currently small) documentation http://www.eclipse.org/nattable/documentation.php?page=editing
BTW, I suggest to update to the latest NatTable release 1.3.0 as it also contains several bugfixes.
This question already exists:
Android Development-XML and Java Files, Insert Random String into Activity
Closed 8 years ago.
I am trying to write a code to generate a random string from a set of arrays. I need help with fixing this code and then what do I include in the xml file to ensure that the code from java will work? Please help! Thanks!
Below is my code from java:
package com.momsmealplanner;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class OutcomeActivity extends Activity
{
public String[] myString;
Resources res = getResources();
myString = res.getStringArray(R.array.restArray);
Random random = new Random(System.currentTimeMillis());
int[] textViews =
{
//add textviews to this array
};
for (int v : textViews)
{
TextView tv = (TextView)findViewById(v);
tv.setText(myString[random.nextInt(myString.length)]);
}
}
}
Where am I going wrong?
I'm so sick of android errors in eclipse.. this has been happening for too long but here it goes.
here's the code
import android.app.Activity;
import android.os.Bundle;
import android.R;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
//constants used when saving/restoring state
private static final String BILL_TOTAL = "BILL_TOTAL";
private static final String CUSTOM_PERCENT = "CUSTOM_PERCENT";
I just threw the imports in to see where the code starts
the first private static final (BILL_TOTAL) errors like this:
Multiple markers at this line
- Syntax error on token(s), misplaced
construct(s)
- Syntax error on tokens, delete these
tokens
- Syntax error on tokens, delete these
tokens
I delete the first private static final then the error jumps to the next static method declaration... ugh.. the code is 90% done and I know there are no errors.. (if anything a curly brace somewhere)..
Please help me understand these random eclipse errors.
thanks in advance
Also... in the midst of all this i lost access to my main layout
main cannot be resolved or is not a field
also one last thing
NONE of my variables "can be resolved as a variable"
Those private static final variables need to be inside of a class context:
import android.app.Activity;
import android.os.Bundle;
import android.R;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
class MyClass {
//constants used when saving/restoring state
private static final String BILL_TOTAL = "BILL_TOTAL";
private static final String CUSTOM_PERCENT = "CUSTOM_PERCENT";
...
}