Java dynamic JTree - java

I want to find the method that adds nodes to a JTree dynamically, looking through the documentation and the examples, this can only be done at the constructor of the JTree.
If possible please show me the code snippets to do this.
Thanks in advance.

You need to have a custom implementation of a TreeModel and TreeNode, see bellow. Just extend LazyTreeModel and implement loadChildren().
There a few dependencies that you must replace with your implementations : LOG - your logger
and WorkerManager.getInstance().schedule(new LoadNodesWorker()) you can replace it with a Thread() - Worker is the equivalent of Runnable.
public abstract class LazyTreeModel extends DefaultTreeModel implements TreeWillExpandListener {
public LazyTreeModel(TreeNode root, JTree tree) {
super(root);
setAsksAllowsChildren(true);
tree.addTreeWillExpandListener(this);
tree.setModel(this);
}
public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
LazyTreeNode node = (LazyTreeNode) event.getPath().getLastPathComponent();
if (node.isLoaded()) {
return;
}
setLoading(node, false);
WorkerManager.getInstance().schedule(new LoadNodesWorker(node));
}
public void reloadNode(String id) {
LazyTreeNode node = findNode(id);
if (node != null) {
node.setLoaded(false);
setLoading(node, true);
WorkerManager.getInstance().schedule(new LoadNodesWorker(node));
}
}
public void reloadParentNode(String id) {
LazyTreeNode node = findParent(id);
if (node != null) {
node.setLoaded(false);
setLoading(node, true);
WorkerManager.getInstance().schedule(new LoadNodesWorker(node));
}
}
public LazyTreeNode findParent(String id) {
LazyTreeNode node = findNode(id);
if (node != null && node.getParent() != null) {
return (LazyTreeNode) node.getParent();
}
return null;
}
public void loadFirstLevel() {
setLoading((LazyTreeNode) getRoot(), false);
WorkerManager.getInstance().schedule(new LoadNodesWorker((LazyTreeNode) getRoot()));
}
public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
}
protected void setChildren(LazyTreeNode parentNode, LazyTreeNode... nodes) {
if (nodes == null) {
return;
}
int childCount = parentNode.getChildCount();
if (childCount > 0) {
for (int i = 0; i < childCount; i++) {
removeNodeFromParent((MutableTreeNode) parentNode.getChildAt(0));
}
}
for (int i = 0; i < nodes.length; i++) {
insertNodeInto(nodes[i], parentNode, i);
}
}
private void setLoading2(final LazyTreeNode parentNode, final boolean reload) {
if (reload) {
setChildren(parentNode, createReloadingNode());
} else {
setChildren(parentNode, createLoadingNode());
}
}
private void setLoading(final LazyTreeNode parentNode, final boolean reload) {
if (SwingUtilities.isEventDispatchThread()) {
setLoading2(parentNode, reload);
} else {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
setLoading2(parentNode, reload);
}
});
} catch (Exception e) {
LOG.error("Cannot create loading node", e);
}
}
}
private LazyTreeNode findNode(String id) {
return findNode(id, (LazyTreeNode) getRoot());
}
private LazyTreeNode findNode(String id, LazyTreeNode parent) {
int count = parent.getChildCount();
for (int i = 0; i < count; i++) {
LazyTreeNode node = (LazyTreeNode) parent.getChildAt(i);
if (id.equals(node.getId())) {
return node;
}
if (node.isLoaded()) {
node = findNode(id, node);
if (node != null) {
return node;
}
}
}
return null;
}
public abstract LazyTreeNode[] loadChildren(LazyTreeNode parentNode);
protected LazyTreeNode createLoadingNode() {
return new LazyTreeNode(null, "Loading...", false);
}
protected LazyTreeNode createReloadingNode() {
return new LazyTreeNode(null, "Refreshing...", false);
}
class LoadNodesWorker implements Worker {
private LazyTreeNode parentNode;
LoadNodesWorker(LazyTreeNode parent) {
this.parentNode = parent;
}
public String getName() {
return "Lazy loading of node " + parentNode.getId();
}
public void execute() throws Exception {
final LazyTreeNode[] treeNodes = loadChildren(parentNode);
if (treeNodes == null) {
return;
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
parentNode.setLoaded(true);
setChildren(parentNode, treeNodes);
}
});
}
}
}
public class LazyTreeNode extends DefaultMutableTreeNode {
private boolean loaded;
private String id;
public LazyTreeNode(String id) {
this(id, null);
}
public LazyTreeNode(String id, Object userObject) {
this(id, userObject, true);
}
public LazyTreeNode(String id, Object userObject, boolean allowsChildren) {
super(userObject, allowsChildren);
this.id = id;
}
public String getId() {
return id;
}
protected boolean isLoaded() {
return loaded;
}
protected void setLoaded(boolean loaded) {
this.loaded = loaded;
}
#Override
public boolean isLeaf() {
return !getAllowsChildren();
}
}

Try this
Edit with more explanation: you want your tree model to be based on MutableTreeNode. The link above is an example from the Sun tutorial.

The Sun example tutorial mentioned by I82Much, includes a demo project, DynamicTreeDemo, that is made up of the two source files DynamicTreeDemo.java and DynamicTree.java. You should be able to get to them from these links.

Related

Xamarin Visual Studio Constructing instances of generic types from Java is not supported

I would appreciate some help with this current problem. I think I understand the cause of the issue, however I have no idea how to fix it. I have two custom views, one implements a ViewGroup and the other just a View.
CameraSourcePreview and GraphicOverlay
However they are both generic to T where T : GraphicOverlay<\T>.Graphic
In BarcodeFragmentActivity. Line 64.
SetContentView(Resource.Layout.Barcode_Capture)
Throws the following error.
System.NotSupportedException: Constructing instances of generic types from Java is not supported, as the type parameters cannot be determined. occurred
Im not sure how to create a full stack trace, as I am using my phone as the test device. Program wont run on an emulator.
Code on Github: https://github.com/StormMaster12/StockApp.
Thought it would be easier to see it on there, than copy all of my code in.
Edit Code Throwing Error.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Content.PM;
using Android.Gms.Vision.Barcodes;
using Android.Gms.Common.Apis;
using Android.Gms.Common;
using Android.Gms.Vision;
using Android.Hardware;
using Android.Support.V4.View;
using Android.Support.V4.App;
using Android.Support.V7.App;
using Android.Support.Design.Widget;
using StockApp.UI;
using Android.Util;
namespace StockApp.BarcodeReader
{
[Activity(Label = "Barcode Fragment Activity")]
class BarcodeFragmentActivity : AppCompatActivity
{
private static string tag = "Barcode-Reader";
private static int RC_HANDLE_GMS = 9001;
private static int RC_HANDLE_CAMERA_PERM = 2;
public static string AutoFocus = "AutoFocus";
public static string UseFlash = "UseFlash";
public static string BarcodeObject = "Barcode";
private CameraSourcePreview<BarcodeGraphic> mPreview;
private Android.Gms.Vision.CameraSource mCameraSource;
private GraphicOverlay<BarcodeGraphic> mGraphicOverlay;
private ScaleGestureDetector scaleGestureDetector;
private GestureDetector getsureDetector;
private View layout;
private static BarcodeFragmentActivity thisInstance;
public override View OnCreateView(View parent, string name, Context context, IAttributeSet attrs)
{
return base.OnCreateView(parent, name, context, attrs);
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
thisInstance = this;
SetContentView(Resource.Layout.Barcode_Capture);
//LayoutInflater inflater = LayoutInflater.From(this);
//ViewGroup viewGroup = (ViewGroup)FindViewById(Resource.Id.preview);
//View child = inflater.Inflate(Resource.Layout.layout1, viewGroup, true);
mPreview = (CameraSourcePreview<BarcodeGraphic>)FindViewById(Resource.Id.preview);
mGraphicOverlay = (GraphicOverlay<BarcodeGraphic>)FindViewById(Resource.Id.graphicOverlay);
bool autoFocus = Intent.GetBooleanExtra(AutoFocus, false);
bool useFlash = Intent.GetBooleanExtra(UseFlash, false);
int rc = (int) ActivityCompat.CheckSelfPermission(this, Manifest.Permission.Camera);
if (rc == (int) Permission.Granted)
{
createCameraSource(autoFocus, useFlash);
}
else
{
requestCameraPermission();
}
getsureDetector = new GestureDetector(this, new CaptureGestureListener());
}
private void requestCameraPermission()
{
string[] permissions = new string[] { Manifest.Permission.CallPhone };
if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.Camera))
{
Snackbar.Make(layout, "Require Camera Permions To Read Barcodes", Snackbar.LengthIndefinite)
.SetAction("Ok", new Action<View> (delegate(View obj)
{
ActivityCompat.RequestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);
}
)).Show();
}
else
{
ActivityCompat.RequestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);
}
//Activity thisActivity = this;
//View.IOnClickListener listener = new View.IOnClickListener;
}
public override bool OnTouchEvent(MotionEvent e)
{
bool b = scaleGestureDetector.OnTouchEvent(e);
bool c = getsureDetector.OnTouchEvent(e);
return b || c || base.OnTouchEvent(e);
}
private void createCameraSource(bool autoFocus, bool useFlash)
{
Context context = ApplicationContext;
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).Build();
BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay);
barcodeDetector.SetProcessor(
new MultiProcessor.Builder(barcodeFactory).Build());
if (!barcodeDetector.IsOperational)
{
IntentFilter lowstorageFilter = new IntentFilter(Intent.ActionDeviceStorageLow);
bool hasLowStorage = RegisterReceiver(null, lowstorageFilter) != null;
if (hasLowStorage)
{
Toast.MakeText(this, "Low Storage Error", ToastLength.Long);
}
}
Android.Gms.Vision.CameraSource.Builder builder = new Android.Gms.Vision.CameraSource.Builder(base.ApplicationContext, barcodeDetector)
.SetFacing(Android.Gms.Vision.CameraFacing.Back)
.SetRequestedPreviewSize(1600, 1024)
.SetRequestedFps(15.0f)
.SetAutoFocusEnabled(true);
mCameraSource = builder.Build();
}
private void startCameraSource()
{
int code = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(ApplicationContext);
if(code != ConnectionResult.Success)
{
Dialog dig = GoogleApiAvailability.Instance.GetErrorDialog(this, code, RC_HANDLE_GMS);
dig.Show();
}
if (mCameraSource != null)
{
try
{
mPreview.start(mCameraSource, mGraphicOverlay);
}
catch (InvalidOperationException)
{
mCameraSource.Release();
mCameraSource = null;
}
}
}
private bool OnTap(float rawX, float rawY)
{
int[] location = new int[2];
mGraphicOverlay.GetLocationOnScreen(location);
float x = (rawX - location[0]);
float y = (rawY - location[1]);
Barcode best = null;
float bestDistance = float.MaxValue;
foreach (BarcodeGraphic graphic in mGraphicOverlay.getGraphics())
{
Barcode barcode = graphic.GetBarcode();
if(barcode.BoundingBox.Contains((int)x,(int)y))
{
best = barcode;
break;
}
float dx = x - barcode.BoundingBox.CenterX();
float dy = y - barcode.BoundingBox.CenterY();
float distance = (dx * dx) + (dy * dy);
if ( distance > bestDistance)
{
best = barcode;
bestDistance = distance;
}
if (best != null)
{
Intent data = new Intent();
data.PutExtra(BarcodeObject, best);
SetResult(CommonStatusCodes.Success, data);
Finish();
return true;
}
}
return false;
}
protected override void OnResume()
{
base.OnResume();
startCameraSource();
}
protected override void OnPause()
{
base.OnPause();
if (mPreview != null)
{
mPreview.stop();
}
}
protected override void OnDestroy()
{
base.OnDestroy();
if(mPreview != null)
{
mPreview.release();
}
}
private class CaptureGestureListener : GestureDetector.SimpleOnGestureListener
{
public override bool OnSingleTapConfirmed(MotionEvent e)
{
return thisInstance.OnTap(e.RawX, e.RawY) || base.OnSingleTapConfirmed(e);
}
}
private class ScaleListener : ScaleGestureDetector.IOnScaleGestureListener
{
public IntPtr Handle => throw new NotImplementedException();
public void Dispose()
{
throw new NotImplementedException();
}
public bool OnScale(ScaleGestureDetector detector)
{
return false;
}
public bool OnScaleBegin(ScaleGestureDetector detector)
{
return true;
}
public void OnScaleEnd(ScaleGestureDetector detector)
{
}
}
}
}
Code that is being called.
CameraSourcePreview
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Gms.Vision;
using Android.Util;
using Android.Support.Annotation;
using Android.Gms.Common.Images;
using Android.Content.Res;
using Android.Graphics;
namespace StockApp.UI
{
[Register("stockapp.stockapp.ui.CameraSourcePreview")]
class CameraSourcePreview<T> : ViewGroup where T : GraphicOverlay<T>.Graphic
{
private static string TAG = "CameraSourcePreview";
private Context mContext;
private SurfaceView mSurfaceView;
public bool mStartRequested;
private bool mSurfaceAvaialbe;
private Android.Gms.Vision.CameraSource mCameraSource;
private GraphicOverlay<T> mOverlay;
private static CameraSourcePreview<T> Instance { get; set; }
public CameraSourcePreview(Context context, IAttributeSet attrs) : base(context,attrs)
{
mContext = context;
mStartRequested = false;
mSurfaceAvaialbe = false;
SurfaceCallback instance = new SurfaceCallback();
mSurfaceView = new SurfaceView(context);
mSurfaceView.Holder.AddCallback(instance);
AddView(mSurfaceView);
}
public void start(Android.Gms.Vision.CameraSource cameraSource)
{
if (cameraSource == null)
{
stop();
}
mCameraSource = cameraSource;
if(mCameraSource != null)
{
mStartRequested = true;
startIfReady();
}
}
public void start(Android.Gms.Vision.CameraSource cameraSource, GraphicOverlay<T> graphicOverlay)
{
mOverlay = graphicOverlay;
start(cameraSource);
}
public void stop()
{
if(mCameraSource != null)
{
mCameraSource.Stop();
}
}
public void release()
{
if(mCameraSource != null)
{
mCameraSource.Release();
mCameraSource = null;
}
}
private bool isPortaitMode()
{
int orientation = (int)mContext.Resources.Configuration.Orientation;
if (orientation == (int)Android.Content.Res.Orientation.Landscape)
{
return false;
}
else if (orientation == (int)Android.Content.Res.Orientation.Portrait)
{
return true;
}
return false;
}
private void startIfReady()
{
if (mStartRequested && mSurfaceAvaialbe)
{
mCameraSource.Start(mSurfaceView.Holder);
if (mOverlay != null)
{
Android.Gms.Common.Images.Size size = mCameraSource.PreviewSize;
int min = Math.Min(size.Width, size.Height);
int max = Math.Max(size.Width, size.Width);
if(isPortaitMode())
{
mOverlay.setCameraInfo(min, max, (int)mCameraSource.CameraFacing);
}
else
{
mOverlay.setCameraInfo(max, min, (int)mCameraSource.CameraFacing);
}
mOverlay.Clear();
}
mStartRequested = false;
}
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
int intWidth = 320;
int intHeight = 240;
if(mCameraSource != null)
{
Android.Gms.Common.Images.Size size = mCameraSource.PreviewSize;
if(size != null)
{
intWidth = size.Width;
intHeight = size.Height;
}
}
if(isPortaitMode())
{
int tmp = intWidth;
intHeight = intWidth;
intWidth = tmp;
}
int layoutWidth = l - r;
int layoutHeight = t - b;
int childWidth = layoutWidth;
int childHeight = (int)(((float)layoutWidth / (float) intHeight)*intWidth);
if (childHeight > layoutWidth)
{
childHeight = layoutHeight;
childWidth = (int)(((float)layoutHeight / (float)intHeight) * intWidth);
}
for (int i =0 ; i < ChildCount; i++ )
{
GetChildAt(i).Layout(0, 0, childWidth, childHeight);
}
try
{
startIfReady();
}
catch (Exception e)
{
Log.Debug("Something went wrong", e.ToString());
}
}
private class SurfaceCallback : ISurfaceHolderCallback
{
public IntPtr Handle => throw new NotImplementedException();
public void Dispose()
{
}
public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
{
}
public void SurfaceCreated(ISurfaceHolder holder)
{
Instance.mSurfaceAvaialbe = true;
try
{
Instance.startIfReady();
}
catch (Exception e)
{
Log.Debug("Something went wrong",e.ToString());
}
}
public void SurfaceDestroyed(ISurfaceHolder holder)
{
Instance.mSurfaceAvaialbe = false;
}
}
}
}
GraphicOverlay
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Gms.Vision;
using Android.Util;
using Android.Graphics;
using Java.Util;
namespace StockApp.UI
{
[Register("stockapp.stockapp.ui.GraphicOverlay")]
class GraphicOverlay<T> : View where T: GraphicOverlay<T>.Graphic
{
public T tT ;
private Object mLock = new object();
private int mPreviewWidth { get; set; }
private float mWidthScaleFactor { get; set; } = 1.0f;
private int mPreviewHeight;
private float mHeightScaleFactor { get; set; } = 1.0f;
private int mFacing { get; set; } = (int)CameraFacing.Back;
private HashSet<T> mGraphics = new HashSet<T>();
public GraphicOverlay(Context context, IAttributeSet attrs)
: base(context, attrs)
{
}
public void Clear()
{
lock(mLock)
{
mGraphics.Clear();
}
}
public void Add(T graphic)
{
lock(mLock)
{
mGraphics.Add(graphic);
}
PostInvalidate();
}
public void Remove(T graphic)
{
lock(mLock)
{
mGraphics.Remove(graphic);
}
PostInvalidate();
}
public List<T> getGraphics()
{
lock(mLock)
{
return mGraphics.ToList();
}
}
public void setCameraInfo(int previewWidth, int previewHeight, int facing)
{
lock(mLock)
{
mPreviewHeight = previewHeight;
mPreviewWidth = previewWidth;
mFacing = facing;
}
PostInvalidate();
}
protected void onDraw(Canvas canvas)
{
base.OnDraw(canvas);
lock(mLock)
{
if(mPreviewWidth !=0 && mPreviewHeight !=0)
{
mWidthScaleFactor = (float)canvas.Width / (float)mPreviewWidth;
mHeightScaleFactor = (float)canvas.Height / (float)mPreviewHeight;
}
foreach (Graphic graphic in mGraphics)
{
graphic.Draw(canvas);
}
}
}
public abstract class Graphic
{
private GraphicOverlay<T> mOverlay;
public Graphic(GraphicOverlay<T> overlay)
{
mOverlay = overlay;
}
public abstract void Draw(Canvas canvas);
public float scaleX(float horizontal) { return horizontal * mOverlay.mWidthScaleFactor; }
public float scaleY(float vertical) { return vertical * mOverlay.mHeightScaleFactor; }
public float translateX(float x)
{
float scale = scaleX(x);
if(mOverlay.mFacing == (int)CameraFacing.Front)
{
return mOverlay.Width - scale;
}
else
{
return scale;
}
}
public float translateY(float y) { return scaleY(y); }
public void postInvalidate() { mOverlay.PostInvalidate(); }
}
}
}

TreeView doesn't displays items

I'm trying to set an initial input to a treeview but I must forget something because It does not displays anything.
public class TreeEditor extends OperationDetailsAspectEditor {
private TreeViewer fConditionField;
private BooleanOperator root;
#Override
public void createControl(Composite parent, FormToolkit toolkit) {
createConditionControls(parent, toolkit);
}
private void createConditionControls(final Composite parent, FormToolkit toolkit) {
fConditionField = new TreeViewer(parent);
fConditionField.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 5));
fConditionField.setLabelProvider(new ConditionsLabelProvider());
fConditionField.setContentProvider(new ConditionsContentProvider());
fConditionField.setUseHashlookup(true);
fConditionField.setInput(getInitialTreeConditions());
fConditionField.expandAll();
}
private BooleanOperator getInitialTreeConditions(){
root = new BooleanOperator(Operator.AND);
return root;
}
}
public class ConditionsLabelProvider implements ILabelProvider {
#Override
public void addListener(ILabelProviderListener paramILabelProviderListener) {}
#Override
public void dispose() { }
#Override
public boolean isLabelProperty(Object paramObject, String paramString) {return false;}
#Override
public void removeListener(
ILabelProviderListener paramILabelProviderListener) {}
#Override
public Image getImage(Object paramObject) {return null;}
#Override
public String getText(Object element) {
if(element instanceof Model){
return ((Model) element).getDisplayName();
} else {
throw unknownElement(element);
}
}
protected RuntimeException unknownElement(Object element) {
return new RuntimeException("Unknown type of element in tree of type " + element.getClass().getName());
}
}
public class ConditionsContentProvider implements ITreeContentProvider {
private static Object[] EMPTY_ARRAY = new Object[0];
protected TreeViewer viewer;
#Override
public void dispose() {
}
#Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
this.viewer = (TreeViewer) viewer;
}
#Override
public Object[] getElements(Object inputElement) {
return getChildren(inputElement);
}
#Override
public Object[] getChildren(Object parentElement) {
if(parentElement instanceof BooleanOperator){
BooleanOperator operator = ((BooleanOperator) parentElement);
return concat(operator.getOperators().toArray(),
operator.getExpresions().toArray());
}
return EMPTY_ARRAY;
}
#Override
public Object getParent(Object element) {
if(element instanceof Model) {
return ((Model)element).getParent();
}
return null;
}
#Override
public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
protected Object[] concat(Object[] a, Object[] b) {
int aLen = a.length;
int bLen = b.length;
Object[] c = new Object[aLen + bLen];
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
protected Object[] concat(Object[]... arrays) {
Object[] array = arrays[0] != null? arrays[0] : null;
for(int i = 1; i < arrays.length; i++) {
array = concat(arrays[i-1], arrays[i]);
}
return array;
}
}
Models
public abstract class Model {
protected BooleanOperator parent;
protected String displayName;
public String getDisplayName(){ return displayName; }
public void setDisplayName(String displayName){
this.displayName = displayName;
}
public BooleanOperator getParent() { return parent; }
public void setParent(BooleanOperator parent) { this.parent = parent; }
public Model(String displayName) { this.displayName = displayName; }
public Model(){}
}
public class BooleanOperator extends Model {
private Operator operator;
private List<BooleanOperator> operators;
private List<Expression> expressions;
public Operator getOperator() {
return operator;
}
public List<BooleanOperator> getOperators() {
return operators;
}
public List<Expresion> getExpresions() {
return expresions;
}
public BooleanOperator() {
operators = new ArrayList<BooleanOperator>();
expresions = new ArrayList<Expresion>();
}
public BooleanOperator(Operator operator) {
this();
this.operator = operator;
this.displayName = operator.toString();
}
}
The idea is that Tree contains something such as:
AND
|- Attribute_1 == value_1
|- Attribute_2 == value_2
|- OR
|- Attribute_3 == value_3
The nodes are Boolean operators and the leaves are expressions.

How to pass object of View via intent?

I tried by implementing my POJO class with Parceable. but it shows error while writing value to object of View.
POJO Class:
import android.os.Parcel;
import android.os.Parcelable;
import android.view.View;
import android.widget.EditText;
public class FieldData implements Parcelable {
private Integer id;
private String value;
private Integer job_transaction_id;
private Integer field_attribute_master_id;
private Boolean required;
private View view;
private String viewType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Integer getJob_transaction_id() {
return job_transaction_id;
}
public void setJob_transaction_id(Integer job_transaction_id) {
this.job_transaction_id = job_transaction_id;
}
public Integer getField_attribute_master_id() {
return field_attribute_master_id;
}
public void setField_attribute_master_id(Integer field_attribute_master_id) {
this.field_attribute_master_id = field_attribute_master_id;
}
public Boolean getRequired() {
return required;
}
public void setRequired(Boolean required) {
this.required = required;
}
public View getView() {
return view;
}
public void setView(View view) {
this.view = view;
}
public String getViewType() {
return viewType;
}
public void setViewType(String viewType) {
this.viewType = viewType;
}
protected FieldData(Parcel in) {
id = in.readByte() == 0x00 ? null : in.readInt();
value = in.readString();
job_transaction_id = in.readByte() == 0x00 ? null : in.readInt();
field_attribute_master_id = in.readByte() == 0x00 ? null : in.readInt();
byte requiredVal = in.readByte();
required = requiredVal == 0x02 ? null : requiredVal != 0x00;
view = (View) in.readValue(View.class.getClassLoader());
viewType = in.readString();
}
public FieldData() {
// TODO Auto-generated constructor stub
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (id == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeInt(id);
}
dest.writeString(value);
if (job_transaction_id == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeInt(job_transaction_id);
}
if (field_attribute_master_id == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeInt(field_attribute_master_id);
}
if (required == null) {
dest.writeByte((byte) (0x02));
} else {
dest.writeByte((byte) (required ? 0x01 : 0x00));
}
**dest.writeValue(view);**//Error at this line
dest.writeString(viewType);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<FieldData> CREATOR = new Parcelable.Creator<FieldData>() {
#Override
public FieldData createFromParcel(Parcel in) {
return new FieldData(in);
}
#Override
public FieldData[] newArray(int size) {
return new FieldData[size];
}
};
}
error shown at dest.writeValue(view);
Error : java.lang.RuntimeException: Parcel: unable to marshal value android.widget.EditText#41ac34a8
View is not parcelable.
ideally you can create similar view in the second activity. Required attibutes can be passed from 1st activity to second via intent
make it serializable by implementing Serializable Interface in your pojo class.
then you can put Serializable in Bundle.
public final class SavingsAccount implements Serializable {
{
}

binary tree implementation with infinite loops

I have fixed the issue with the infinite loops but it seems like now when I try to use the function find, it always returns a value null. Any ideas of what's happening? Also for some reason I'm getting a NullPointerException in my delete function. Please can you help me here guys?
package ui;
import java.time.LocalDate;
import bp.BinaryTree;
public class Main {
public static void main(String[] args) {
BinaryTree myTree = new BinaryTree();
myTree.insert(LocalDate.of(2014,12,01));
myTree.insert(LocalDate.of(2014,12,02));
myTree.insert(LocalDate.of(2014,12,03));
myTree.insert(LocalDate.of(2013,12,04));
myTree.insert(LocalDate.of(2012,12,04));
myTree.insert(LocalDate.of(2011,12,04));
myTree.insert(LocalDate.of(2010,12,04));
myTree.insert(LocalDate.of(2014,12,04));
myTree.insert(LocalDate.of(2014,12,05));
myTree.insert(LocalDate.of(2014,12,06));
myTree.insert(LocalDate.of(2014,12,07));
System.out.println(myTree);
System.out.println(myTree.getSize());
System.out.println(myTree.showMaximumValue());
System.out.println(myTree.showMinimumValue());
System.out.println(myTree.find(LocalDate.of(2014,12,07)));
}
public class BinaryTree implements IBinaryTree {
public Node root = null;
private int sizeOfTree = 0;
#Override
public LocalDate showMinimumValue() {
Node current;
Node last=null;
current = root;
while (current != null) {
last = current;
current = current.getLeftChild();
}
return last.getDate();
}
#Override
public LocalDate showMaximumValue() {
Node current;
Node last=null;
current = root;
while (current != null) {
last = current;
current = current.getRightChild();
}
return last.getDate();
}
#Override
public boolean isEmpty() {
if (root == null) {
return true;
} else
return false;
}
public int getDepth(Node n) {
int currentDepth = 0;
int depth = 0;
if (n != null) {
currentDepth++;
if (currentDepth > depth) {
depth = currentDepth;
}
getDepth(n.getLeftChild());
getDepth(n.getRightChild());
currentDepth--;
}
return depth;
}
#Override
public int getSize() {
return sizeOfTree;
}
#Override
public void clear() {
root = null;
}
#Override
public void insert(LocalDate valueToInsert) {
if (isEmpty()) {
root = new Node(valueToInsert);
sizeOfTree++;
} else {
Node n = root;
Node oldParent = null;
boolean lastDirectWasLeft = false;
sizeOfTree++;
while (n != null) {
oldParent = n;
if (valueToInsert.isBefore(n.getDate())) {
n = n.getLeftChild();
lastDirectWasLeft = true;
} else {
n = n.getRightChild();
lastDirectWasLeft = false;
}
}
if (lastDirectWasLeft) {
oldParent.setLeftChild(new Node(valueToInsert));
} else {
oldParent.setRightChild(new Node(valueToInsert));
}
}
}
#Override
public void delete(LocalDate valueToDelete) {
Node current = root;
Node parent = root;
boolean isLeftChild = true;
while (current.getDate() != valueToDelete) {
parent = current;
if (valueToDelete.isBefore(current.getDate())) {
isLeftChild = true;
current = current.getLeftChild();
} else {
isLeftChild= false;
current = current.getRightChild();
}
if (current == null) {
break;
}
}
//When there is no children, cut the string
if(current.getLeftChild().equals(null)
&& current.getRightChild().equals(null)) {
if (current == root) {
root = null;
} else if (isLeftChild) {
parent.setLeftChild(null);
} else {
parent.setRightChild(null);
}
}
//When there is no right child, replace with left child
else if (current.getRightChild().equals(null)) {
if (current == root) {
root = current.getLeftChild();
} else if (isLeftChild) {
parent.setLeftChild(current.getLeftChild());
} else
parent.setRightChild(current.getLeftChild());
}
//When there is no left child, replace with right child
else if (current.getLeftChild() == null) {
if (current == root) {
root = current.getRightChild();
} else if (isLeftChild) {
parent.setLeftChild(current.getRightChild());
} else
parent.setRightChild(current.getRightChild());
}
//has grandchildren, pass them to the grandpas
else {
//find the grandchildren
Node successor = getSuccessor(current);
if (current == root) {
root = successor;
} else if (isLeftChild) {
parent.setLeftChild(successor);
} else {
parent.setRightChild(successor);
}
//bring grandkids and granppas together
successor.setLeftChild(current.getLeftChild());
}
}
private Node getSuccessor (Node otroNode) {
Node successorParent = otroNode;
Node successor = otroNode;
Node current = otroNode.getRightChild();
while (current != null) {
successorParent = successor;
successor = current;
current = current.getLeftChild();
}
if (successor != otroNode.getRightChild()) {
successorParent.setLeftChild(successor.getRightChild());
successor.setRightChild(otroNode.getRightChild());
}
return successor;
}
#Override
public Node find(LocalDate valueToFind) {
Node current = root;
while (current.getDate() != valueToFind) {
if (valueToFind.isBefore(current.getDate())) {
current = current.getLeftChild();
} else {
current = current.getRightChild();
}
if (current == null) {
return null;
}
}
return current;
}
if (isEmpty()) {
return null;
}
if (root.getDate().isAfter(valueToFind)) {
find(root.getLeftChild().getDate());
} else if (root.getDate().isBefore(valueToFind)) {
find(root.getRightChild().getDate());
} else if (root.getDate().equals(valueToFind) ) {
return root;
}
return null;
**/
private String toString(Node todoElArbol) {
if (todoElArbol == null){
return "";
} else {
return (toString(todoElArbol.getLeftChild()) + ","
+ todoElArbol.getDate() + ","
+ toString(todoElArbol.getRightChild()))
.replaceAll(",+", ",").replaceAll("^,", "").replaceAll(",$", "");
}
}
#Override
public String toString() {
return toString(root);
}
}
The Node class:
import java.time.LocalDate;
public class Node implements IBinaryTreeNode {
private LocalDate date;
private Node leftChild;
private Node rightChild;
public Node (LocalDate valueToInsert) {
date = valueToInsert;
}
#Override
public LocalDate getDate() {
return date;
}
#Override
public void setDate(LocalDate pDate) {
date = pDate;
}
#Override
public Node getLeftChild() {
return leftChild;
}
#Override
public void setLeftChild(Node pLeftChild) {
leftChild = pLeftChild;
}
#Override
public Node getRightChild() {
return rightChild;
}
#Override
public void setRightChild(Node pRightChild) {
rightChild = pRightChild;
}
}
Your binary search is.... broken.
#Override
public Node find(LocalDate valueToFind) {
if (isEmpty()) {
return null;
}
if (root.getDate().isAfter(valueToFind)) {
find(root.getLeftChild().getDate());
} else if (root.getDate().isBefore(valueToFind)) {
find(root.getRightChild().getDate());
} else if (root.getDate() == valueToFind) {
return root;
}
return null;
}
That method is supposed to recursively find a value in the tree (a depth-first search).
Methods like that are normally implemented in two parts, the public part, and the implementation for the recursion:
#Override
public Node find(LocalDate valueToFind) {
if (isEmpty()) {
return null;
}
return findRecursive(root, valueToFind);
}
then the private/recursive method:
private Node findRecursive(Node node, LocalDate valueToFind) {
if (node == null) {
return null;
}
if (node.getDate().isAfter(valueToFind)) {
return findRecursive(node.getLeftChild(), valueToFind);
}
if (node.getDate().isBefore(valueToFind)) {
return findRecursive(root.getRightChild(), valueToFind);
}
if (node.getDate().equals(valueToFind)) {
return node;
}
return null;
}
Note, no references to root in the recursive call, and also changed the == comparison to .equals(...).
I suggest the class Node should implement the Comparable interface, then you can get rid of the help method isBefore and isAfter, which will make your code much more readable.

ClassCast exception Java generic types

first time asking around here. I'm doing an AVLTree generic and there is a method in the Node that gives me an Iterator that returns me a Object array. The thing is that when I try to get that array with the objects of one of my none generic classes it sends me this.
Exception in thread "main" java.lang.ClassCastException: [LestructuraDeDatos.NodoAVL; cannt be cast to [Lmundo.Categoria;
Here is the node class
public class NodoAVL <T extends Comparable <T>>
{
//--------------------------------------------------------------------------------------------
//Atributos
//--------------------------------------------------------------------------------------------
private NodoAVL<T> izquierdo;
private NodoAVL<T> derecho;
private T elemento;
private String criterio;
//--------------------------------------------------------------------------------------------
//Constructor
//--------------------------------------------------------------------------------------------
public NodoAVL(T elem, String crit)
{
elemento = elem;
izquierdo = null;
derecho = null;
criterio = crit;
}
//--------------------------------------------------------------------------------------------
//Metodos
//--------------------------------------------------------------------------------------------
public NodoAVL<T> getIzquierdo() {
return izquierdo;
}
public void setIzquierdo(NodoAVL<T> izquierdo) {
this.izquierdo = izquierdo;
}
public NodoAVL<T> getDerecho() {
return derecho;
}
public void setDerecho(NodoAVL<T> derecho) {
this.derecho = derecho;
}
public String getCriterio() {
return criterio;
}
public void setCriterio(String criterio) {
this.criterio = criterio;
}
public boolean soyHoja()
{
if(izquierdo == null && derecho == null)
{
return true;
}
return false;
}
public T getElemento() {
return elemento;
}
public void setElemento(T elemento) {
this.elemento = elemento;
}
public void agregarElemento(T elemento, String Crit)
{
//Buscarlo antes de agregar, no puede haber iguales en el arbol
if(buscarElemento(Crit)==null)
if(soyHoja())
{
if(elemento.compareTo(this.elemento)>0)
{
NodoAVL<T> nuevo = new NodoAVL<T>(elemento, Crit);
setDerecho(nuevo);
}else if(elemento.compareTo(this.elemento)<0)
{
NodoAVL<T> nuevo = new NodoAVL<T>(elemento, Crit);
setIzquierdo(nuevo);
}
}else
{
NodoAVL<T> nuevo = new NodoAVL<T>(elemento,Crit);
if(this.elemento.compareTo(elemento)>0 && izquierdo == null)
{
izquierdo = nuevo;
}
else if(this.elemento.compareTo(elemento)>0)
{
izquierdo.agregarElemento(elemento,Crit);
}
else if(this.elemento.compareTo(elemento)<0 && derecho == null)
{
derecho = nuevo;
}
else if( this.elemento.compareTo(elemento)<0)
{
derecho.agregarElemento(elemento, Crit);
}
}
balanciarSubArbol();
}
public NodoAVL<T> rotarIzq(NodoAVL<T> rotar)
{
NodoAVL<T> temp = rotar.derecho;
rotar.setDerecho(temp.izquierdo);
temp.setIzquierdo(rotar);
return temp;
}
public NodoAVL<T> rotarDer(NodoAVL<T> rotar)
{
NodoAVL<T> temp = rotar.izquierdo;
rotar.setIzquierdo(temp.derecho);
temp.setDerecho(rotar);
return temp;
}
public int darBalance()
{
if(soyHoja())
{
return 0;
}
else
{
int izq = (izquierdo == null)?0:izquierdo.darAltura();
int der = (derecho == null)? 0 :derecho.darAltura();
return (izq - der);
}
}
public NodoAVL<T> dobleRotacionDerIzq(NodoAVL<T> nodo)
{
nodo.setDerecho(rotarDer(nodo.getDerecho()));
return rotarIzq(nodo);
}
public NodoAVL<T> dobleRotacionIzqDer(NodoAVL<T> nodo)
{
nodo.setIzquierdo(rotarIzq(nodo.getIzquierdo()));
return rotarDer(nodo);
}
public void balanciarSubArbol()
{
int valor = darBalance();
if(-2==valor || valor==2)
{
if(valor<0 && derecho.darBalance()<0)
{
if(derecho.darBalance()<-2)
{
derecho.balanciarSubArbol();
}else
{
rotarIzq(this);
}
}else if(valor<0 && derecho.darBalance()>0)
{
if(derecho.darBalance()>2)
{
derecho.balanciarSubArbol();
}else
{
dobleRotacionDerIzq(this);
}
}else if(valor>0 && izquierdo.darBalance()>0)
{
if(izquierdo.darBalance()>2)
{
izquierdo.balanciarSubArbol();
}else
{
rotarDer(this);
}
}else if(valor>0 && izquierdo.darBalance()<0)
{
if(izquierdo.darBalance()<-2)
{
izquierdo.balanciarSubArbol();
}else
{
dobleRotacionIzqDer(this);
}
}
}
}
public NodoAVL<T> eliminarElemento(T elemento)
{
if(soyHoja() && this.elemento==elemento)
{
return null;
}else if(soyHoja() && this.elemento!=elemento)
{
return this;
}
else
{
if(this.elemento.compareTo(elemento)==0)
{
if(izquierdo != null && derecho != null)
{
NodoAVL<T> temp = derecho;
izquierdo.setDerecho(temp.getIzquierdo());
temp.setIzquierdo(izquierdo);
return temp;
}
else if(izquierdo != null)
{
return izquierdo;
}
else
{
return derecho;
}
}
else if(this.elemento.compareTo(elemento)>0)
{
izquierdo = izquierdo.eliminarElemento(elemento);
return this;
}
else if(this.elemento.compareTo(elemento)<0)
{
derecho = derecho.eliminarElemento(elemento);
return this;
}
balanciarSubArbol();
return this;
}
}
public T buscarElemento(String criterio)
{
if(this.criterio.equalsIgnoreCase(criterio))
{
return this.elemento;
}
else
{
T izq = (izquierdo != null)?izquierdo.buscarElemento(criterio):null;
T der = (derecho != null) ? derecho.buscarElemento(criterio):null;
if(izq != null)
{
return izq;
}else if(der != null)
{
return der;
}
}
return null;
}
public IteradorAVL<T> darElementos()
{
IteradorAVL<T> ite = new IteradorAVL<T> (this);
return ite;
}
public int darPeso()
{
if(soyHoja())
{
return 1;
}else
{
int izq = (izquierdo == null)? 0: izquierdo.darPeso();
int der = (derecho == null) ? 0:derecho.darPeso();
return (izq+der+1);
}
}
public int darAltura()
{
if(soyHoja())
{
return 1;
}
else
{
int izq = ( izquierdo == null ) ? 0 : izquierdo.darAltura( );
int der = ( derecho == null ) ? 0 : derecho.darAltura( );
return(izq>der || izq == der)?izq+1:der+1;
}
}
}
and the iterator class
public class IteradorAVL<T extends Comparable <T>> implements Iterator<T>{
//--------------------------------------------------------------------------------------------
//Atributos
//--------------------------------------------------------------------------------------------
private NodoAVL<T> arbolitoAVL;
private Object [] elementos;
private int posActual;
private int total;
private Stack<NodoAVL> nodePath = new Stack<NodoAVL>();
//--------------------------------------------------------------------------------------------
//Constructor
//--------------------------------------------------------------------------------------------
public IteradorAVL ( NodoAVL <T> nodo)
{
arbolitoAVL = nodo;
posActual = 0;
total = nodo.darPeso();
elementos = new NodoAVL[total];
}
//--------------------------------------------------------------------------------------------
//Metodos
//--------------------------------------------------------------------------------------------
#Override
public boolean hasNext()
{
return(total>posActual)?true:false;
}
#Override
public T next() {
T siguienteT =null;
NodoAVL<T> respuesta = arbolitoAVL;
//Guardo el nodo actual en la lista
//Avancce
while (arbolitoAVL != null) {
nodePath.push(arbolitoAVL);
elementos[posActual] = arbolitoAVL;
arbolitoAVL = arbolitoAVL.getIzquierdo();
posActual++;
}
if (!nodePath.isEmpty()) {
arbolitoAVL = nodePath.pop();
posActual++;
elementos[posActual] = arbolitoAVL;
siguienteT = arbolitoAVL.getElemento();
arbolitoAVL = arbolitoAVL.getDerecho();
}
return siguienteT;
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
public Object[] darArreglo()
{
return elementos;
}
The reason ClassCastException occurs is only one that your trying to typecast an object of one class to an object of another class which are not compatible.
Example :
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.

Categories

Resources