How to design multipane with 3 fragment using Android-PanesLibrary? - arrays

Good Day Developers,
I already implement this fantastic library called "Android-PanesLibrary" by Kenrick Rilee. and what i want to achive is something like this.
But i end up doing like this :
my first problem if in showDetails method i delete the comment symbol, it will showing up an error. but if i make the method empty, it will run just like the second image.
my objective is how can this be done just using string array data?
Any ideas or help would be greatly appreciated.
Environment : Windows 7, Android Studio, Genymotion.
This is MainMenuFragment.java :
public class MainMenuFragment extends android.app.ListFragment {
private static int sExampleNum = 0;
protected final String TAG = "mainmenuFragment" ;
#ViewById(R.id.menu_listview)
protected ListView menuListView ;
private View parentView;
int mCurCheckPosition = 0;
public MainMenuFragment() {
super();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Resources res = getResources();
String [] mainmenulistview = res.getStringArray(R.array.listview_main_menu);
ArrayAdapter<String> connectArrayToListView = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_activated_1,mainmenulistview);
setListAdapter(connectArrayToListView);
if (savedInstanceState != null) {
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
showDetails(mCurCheckPosition);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
// if I un-comment on method bellow, it will result an error.
void showDetails(int index) {
//mCurCheckPosition = index;
//getListView().setItemChecked(index, true);
//PCDesktopFragment_ pcDesktop = (PCDesktopFragment_) getFragmentManager().findFragmentById(R.id.sub_one_fragment);
//if (pcDesktop == null || pcDesktop.getShownIndex() != index) {
// welder_pipe_reg = PCDesktopFragment_.newInstance(index);
// android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
// ft.replace(R.id.sub_one_fragment, pcDesktop);
// ft.commit();
//}
}
}
and then i already create a class called PCDesktopFragment.java that extends ListFragment (this should be showing up on second fragment using listfragment)
#EFragment(R.layout.sub_one_menu)
public class PCDesktopFragment_ extends ListFragment {
View v;
public static int i;
public static PCDesktopFragment_ newInstance(int index){
PCDesktopFragment_ f = new PCDesktopFragment_();
Bundle args = new Bundle();
args.putInt("index", index);
index = i;
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
inflater.inflate(R.layout.sub_one_menu, container, false);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (i == 0) {
String [] sub_a = {"Test1","Test2"};
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, sub_a));
}
}
//#ItemClick(R.id.sub_one_listview)
//protected void handleDomainClick(int position) {
// Fragment f = null ;
// if (position == 0) {
// f = new PCDesktopFragment_();
// }
// Activity a = getActivity();
// if (f != null && a != null && a instanceof FragmentLauncher)
// ((FragmentLauncher) a).addFragment(this, f);
//}
}

Related

Unsubscribe from SceneView draw calls when Edited Unity PropertyDrawer Array element got deleted

I'm making an editor in PropertyDrawer using SceneView.duringSceneGui. So it involves subscribing to SceneView.duringSceneGui when a property needs to draw stuff in SceneView and unsubscribing when it's gone. However I have no idea how to know if edited array element was removed from an array. It still exists in the memory and SceneView.duringSceneGui subscribed method is still there. I need to know when to stop editing and unsubscribe from it.
I guess I need to implement some context object, to store property value, edited object, PropertyDrawer and that subscription method should be there, to be able to unsubscribe exactly that editor... Although there may be only one editor running at once.
Does anybody found that out? Couldn't find anything with PropertyDrawers and array elements being deleted or removed.
TL.DR. Does Unity has an event to tell that PropertyDrawer's array element was removed or is there a simple or neat way to figure this out?
So, while making an example, I've solved my problem by getting property value every SceneView draw call and on catching an exception or if that value isn't edited stopped editor. I've added [NonSerialized] to _IsInEditMode to fix a new issue that I caught at the last moment, so that one is crucial.
Not sure if it's the best way to do that. If anybody will ever need to make a SceneView editor for some class, here's the example that works on arrays and lists also. Just separate it into 3 files and put them in respective folders, like Editor/ for MyClassDrawer.
using InspectorSerializedUtility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MyScript : MonoBehaviour
{
public MyClass field;
public List<MyClass> list = new List<MyClass>();
}
[Serializable]
public class MyClass
{
#if UNITY_EDITOR
[NonSerialized]
public bool _IsInEditMode;
#endif
public Vector3 position;
public void Reset()
{
position = Vector3.zero;
#if UNITY_EDITOR
_IsInEditMode = false;
#endif
}
}
[CustomPropertyDrawer(typeof(MyClass))]
public class MyClassDrawer : PropertyDrawer
{
public MyClass value;
public Transform targetTransform;
private Tool internalTool;
bool editorStarted {
get => value?._IsInEditMode ?? false;
set {
if (this.value != null)
this.value._IsInEditMode = value;
}
}
private SerializedProperty currentProperty;
private SerializedProperty drawerProperty;
private static MyClassDrawer currentlyEditedDrawer;
string editorButtonText(bool isInEditMode) => isInEditMode ? "Stop Editing" : "Start Editing";
Color editorButtonColor(bool isInEditMode) => isInEditMode ? Color.red + Color.white / 2f : Color.white;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
//Debug.Log("OnGUI");
drawerProperty = property;
targetTransform = ((Component)property.serializedObject.targetObject).transform;
var val = property.GetValue<MyClass>();
GUI.color = editorButtonColor(val._IsInEditMode);
var toggle = GUI.Toggle(position, val._IsInEditMode, editorButtonText(val._IsInEditMode), "Button");
if (toggle != val._IsInEditMode)
{
if (toggle && currentlyEditedDrawer != null && currentlyEditedDrawer.editorStarted)
currentlyEditedDrawer.StopEditor();
value = val;
currentlyEditedDrawer = this;
if (toggle)
StartEditor();
else
StopEditor();
}
GUI.color = Color.white;
}
public void OnDrawScene(SceneView sv) => OnDrawScene();
public void OnDrawScene()
{
//Debug.Log("OnDrawScene");
MyClass value = null;
try
{
value = currentProperty.GetValue<MyClass>();
if (!value._IsInEditMode)
{
StopEditor();
return;
}
} catch
{
StopEditor();
return;
}
var m = Handles.matrix;
Handles.matrix = targetTransform.localToWorldMatrix;
if (Tools.current == Tool.Move)
{
internalTool = Tool.Move;
Tools.current = Tool.None;
}
if (internalTool == Tool.Move)
{
var pos = Handles.PositionHandle(value.position, Quaternion.identity);
if (value.position != pos)
{
Undo.RecordObject(targetTransform, "position changed");
value.position = pos;
}
}
Handles.matrix = m;
}
public void StartEditor()
{
currentProperty = drawerProperty;
editorStarted = true;
Debug.Log("StartEditor");
Subscribe();
CallAllSceneViewRepaint();
}
private void Subscribe()
{
Unsubscribe();
SceneView.duringSceneGui += OnDrawScene;
Selection.selectionChanged += StopEditor;
EditorSceneManager.sceneClosed += StopEditor;
AssemblyReloadEvents.beforeAssemblyReload += StopEditor;
}
public void StopEditor(Scene s) => StopEditor();
public void StopEditor()
{
Tools.current = internalTool;
editorStarted = false;
Unsubscribe();
currentProperty = null;
CallAllSceneViewRepaint();
}
private void Unsubscribe()
{
SceneView.duringSceneGui -= OnDrawScene;
Selection.selectionChanged -= StopEditor;
EditorSceneManager.sceneClosed -= StopEditor;
AssemblyReloadEvents.beforeAssemblyReload -= StopEditor;
}
private void CallAllSceneViewRepaint()
{
foreach (SceneView sv in SceneView.sceneViews)
sv.Repaint();
}
}
namespace InspectorSerializedUtility
{
/// <summary>
/// https://gist.github.com/douduck08/6d3e323b538a741466de00c30aa4b61f
/// </summary>
public static class InspectorSeriallizedUtils
{
public static T GetValue<T>(this SerializedProperty property) where T : class
{
try
{
if (property.serializedObject.targetObject == null) return null;
}
catch
{
return null;
}
object obj = property.serializedObject.targetObject;
string path = property.propertyPath.Replace(".Array.data", "");
string[] fieldStructure = path.Split('.');
Regex rgx = new Regex(#"\[\d+\]");
for (int i = 0; i < fieldStructure.Length; i++)
{
if (fieldStructure[i].Contains("["))
{
int index = System.Convert.ToInt32(new string(fieldStructure[i].Where(c => char.IsDigit(c)).ToArray()));
obj = GetFieldValueWithIndex(rgx.Replace(fieldStructure[i], ""), obj, index);
}
else
{
obj = GetFieldValue(fieldStructure[i], obj);
}
}
return (T)obj;
}
public static bool SetValue<T>(this SerializedProperty property, T value) where T : class
{
object obj = property.serializedObject.targetObject;
string path = property.propertyPath.Replace(".Array.data", "");
string[] fieldStructure = path.Split('.');
Regex rgx = new Regex(#"\[\d+\]");
for (int i = 0; i < fieldStructure.Length - 1; i++)
{
if (fieldStructure[i].Contains("["))
{
int index = System.Convert.ToInt32(new string(fieldStructure[i].Where(c => char.IsDigit(c)).ToArray()));
obj = GetFieldValueWithIndex(rgx.Replace(fieldStructure[i], ""), obj, index);
}
else
{
obj = GetFieldValue(fieldStructure[i], obj);
}
}
string fieldName = fieldStructure.Last();
if (fieldName.Contains("["))
{
int index = System.Convert.ToInt32(new string(fieldName.Where(c => char.IsDigit(c)).ToArray()));
return SetFieldValueWithIndex(rgx.Replace(fieldName, ""), obj, index, value);
}
else
{
Debug.Log(value);
return SetFieldValue(fieldName, obj, value);
}
}
private static object GetFieldValue(string fieldName, object obj, BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
{
FieldInfo field = obj.GetType().GetField(fieldName, bindings);
if (field != null)
{
return field.GetValue(obj);
}
return default(object);
}
private static object GetFieldValueWithIndex(string fieldName, object obj, int index, BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
{
FieldInfo field = obj.GetType().GetField(fieldName, bindings);
if (field != null)
{
object list = field.GetValue(obj);
if (list.GetType().IsArray)
{
return ((object[])list)[index];
}
else if (list is IEnumerable)
{
return ((IList)list)[index];
}
}
return default(object);
}
public static bool SetFieldValue(string fieldName, object obj, object value, bool includeAllBases = false, BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
{
FieldInfo field = obj.GetType().GetField(fieldName, bindings);
if (field != null)
{
field.SetValue(obj, value);
return true;
}
return false;
}
public static bool SetFieldValueWithIndex(string fieldName, object obj, int index, object value, bool includeAllBases = false, BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
{
FieldInfo field = obj.GetType().GetField(fieldName, bindings);
if (field != null)
{
object list = field.GetValue(obj);
if (list.GetType().IsArray)
{
((object[])list)[index] = value;
return true;
}
else if (value is IEnumerable)
{
((IList)list)[index] = value;
return true;
}
}
return false;
}
}
}

GWT comboBox multiSelect

I try to make my comboBox multiple selection
and this my code:
this multiSelectComboBox:
import java.util.List;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.WindowEvent;
import com.extjs.gxt.ui.client.event.WindowListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.CheckBoxListView;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.form.TriggerField;
import com.extjs.gxt.ui.client.widget.layout.FillLayout;
import com.google.gwt.user.client.Element;
public class MultiSelectComboBox<D extends ModelData> extends TriggerField<String> {
private Dialog checkBoxListHolder;
private CheckBoxListView<D> listView;
private ListStore<D> store;
private String delimiter = ",";
private boolean readOnly;
public MultiSelectComboBox() {
store = new ListStore<D>();
listView = new CheckBoxListView<D>();
}
#Override
protected void onTriggerClick(ComponentEvent ce) {
super.onTriggerClick(ce);
checkBoxListHolder.setSize(getWidth(), 200);
listView.setWidth(getWidth());
checkBoxListHolder.setPosition(getAbsoluteLeft(),
getAbsoluteTop() + getHeight());
if(checkBoxListHolder.isVisible()) {
checkBoxListHolder.hide();
}
else {
checkBoxListHolder.show();
}
}
#Override
protected void onRender(Element target, int index) {
super.onRender(target, index);
checkBoxListHolder = new Dialog();
checkBoxListHolder.setClosable(false);
checkBoxListHolder.setHeaderVisible(false);
checkBoxListHolder.setFooter(false);
checkBoxListHolder.setFrame(false);
checkBoxListHolder.setResizable(false);
checkBoxListHolder.setAutoHide(false);
checkBoxListHolder.getButtonBar().setVisible(false);
checkBoxListHolder.setLayout(new FillLayout());
checkBoxListHolder.add(listView);
listView.setStore(store);
checkBoxListHolder.addWindowListener(new WindowListener(){
#Override
public void windowHide(WindowEvent we) {
setValue(parseCheckedValues(listView));
}
});
}
private String parseCheckedValues(CheckBoxListView<D> checkBoxView) {
StringBuffer buf = new StringBuffer();
if(checkBoxView != null) {
List<D> selected = checkBoxView.getChecked();
int index = 1, len = selected.size();
for(D c : selected) {
buf.append(c.get(listView.getDisplayProperty()));
if(index < len) {
buf.append(delimiter);
}
index++;
}
}
return buf.toString();
}
public CheckBoxListView<D> getListView() {
return listView;
}
public void setListView(CheckBoxListView<D> listView) {
this.listView = listView;
}
public ListStore<D> getStore() {
return store;
}
public void setStore(ListStore<D> store) {
this.store = store;
}
public String getDelimiter() {
return delimiter;
}
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
public boolean isReadOnly() {
return readOnly;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
}
then use this class in my project:
// ...
ListStore<UserDTO> employeeList = getUsers();
MultiSelectComboBox<ModelData> multiUsers = new MultiSelectComboBox<ModelData>();
multiUsers.getListView().setDisplayProperty("label");
//multiUsers.setStore(employeeList);
multiUsers.getStore().add(getModelData());
multiUsers.setFieldLabel("Employee");
//multiUsers.setEditable(true);
//multiUsers.setMaxHeight(200);
simpleForm.add(multiUsers, formData);
// ...
private List<ModelData> getModelData() {
List<ModelData> list = new ArrayList<ModelData>();
List<NctrUserDTO> employees= employeeList.getModels();
for (int i=0; i<employeeList.getCount(); i++) {
ModelData data = new BaseModel();
data.set("label", employeeList.getAt(i).getName());
list.add(data);
}
return list;
}
but the comboBox appear empty or have not any values when i pass values from employeeList but when i tried with static string values this works fine, i dont know why this problem occur, any suggestion please ??
It sounds as if your looking for something like the option multiple select boxes, if so you can look up the source code on Github for pointers - or rather than re-inventing the wheel, just use that GwtBootstrap3 component

How to upload file from fragment webview in android?

I have used tabhost of two fragments. One fragment is for list and other is for webview. From that fragment I have to upload file from gallery. Following is my fragment for webview.
public class AppleFragment extends Fragment{
private static final String TAG = "SocialActivityFragment";
//protected static final int FILECHOOSER_RESULTCODE = 0;
WebView browser;
static String cookieString;
ProgressBar Pbar;
HashMap<String, String> headerMap = new HashMap<String, String>();
private ValueCallback<Uri> mUploadMessage;
final static int FILECHOOSER_RESULTCODE=1;
#Override
public void onActivityResult(int requestCode, int resultCode,Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
#SuppressLint({ "NewApi", "SetJavaScriptEnabled" })
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/** Creating array adapter to set data in listview */
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), R.layout.social_activities_layout, apple_versions);
LayoutInflater layoutInflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.social_layout, null);
Pbar = (ProgressBar) layout.findViewById(R.id.pB1);
String strResponse = util.makeWebCall("http://google.com");
DefaultHttpClient mClient = util.getClient();
Cookie sessionInfo;
List<Cookie> cookies = mClient.getCookieStore().getCookies();
if (! cookies.isEmpty()){
CookieSyncManager.createInstance(getActivity().getApplicationContext());
CookieManager cookieManager = CookieManager.getInstance();
for(Cookie cookie : cookies){
sessionInfo = cookie;
cookieString = sessionInfo.getName() + "=" + Sessions.getPhpSessid(getActivity().getApplicationContext()) + "; domain=" + sessionInfo.getDomain();
cookieManager.setCookie("http://youornot.com/social/", cookieString);
CookieSyncManager.getInstance().sync();
//Toast.makeText(getApplicationContext(), cookieString, Toast.LENGTH_LONG).show();
}
}
AlertDialogManager alert=new AlertDialogManager();
ConnectionDetector cd=new ConnectionDetector(getActivity().getApplicationContext());
if(!cd.isConnectedToInternet())
{
alert.showAlertDialog(getActivity(), "Error..!", "You have not Connected to Internet", true);
}
browser=(WebView)layout.findViewById(R.id.webBrowser);
// WebView browser = new WebView(SocialActivity.this);
WebSettings settings = browser.getSettings();
browser.setScrollBarStyle(browser.OVER_SCROLL_IF_CONTENT_SCROLLS);
WebViewClient wvClient = new WebViewClient();
browser.setWebViewClient(wvClient);
browser.getSettings().setJavaScriptEnabled(true);
browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
browser.setWebChromeClient(new WebChromeClient() {
#SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
#SuppressWarnings("unused")
public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
//For Android 4.1
#SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult( Intent.createChooser( i, "File Chooser" ),FILECHOOSER_RESULTCODE );
}
public void onProgressChanged(WebView view, int progress)
{
if(progress < 100 && Pbar.getVisibility() == ProgressBar.GONE){
Pbar.setVisibility(ProgressBar.VISIBLE);
//txtview.setVisibility(View.VISIBLE);
}
Pbar.setProgress(progress);
if(progress == 100) {
Pbar.setVisibility(ProgressBar.GONE);
// txtview.setVisibility(View.GONE);
}
}
});
headerMap.put("Cookie", cookieString);
browser.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
//The key is this line.
v.requestFocusFromTouch();
break;
}
return false;
}
});
browser.loadUrl("http://google.com", headerMap);
return layout;//super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.web_menu, menu);
}
#SuppressLint("NewApi")
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.refresh:
browser.reload();
// browser.loadUrl("http://google.com", headerMap);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Whenever I am uploading file then webview is not responding at all.When i will close the application then also webview not responding. So how I can upload file in webview that is in the tabhost fragment.
Thanks in advance.
public class AppleFragment extends Fragment{
WebView webView;
//make HTML upload button work in Webview
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != getActivity().RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_web, container, false);
// Web View
webView = (WebView) view.findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setWebChromeClient(new WebChromeClient(){
//The undocumented magic method override
//Eclipse will swear at you if you try to put #Override here
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
getActivity().startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType ) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult(Intent.createChooser(i, "File Browser"),FILECHOOSER_RESULTCODE);
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
getActivity().startActivityForResult( Intent.createChooser( i, "File Chooser" ), FILECHOOSER_RESULTCODE );
}
});
webView.loadUrl(yourUrl);
return view;
}
}
public class FragmentWeb extends Fragment {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == this.mUploadMessage) {
return;
}
Uri result=null;
try{
if (resultCode != getActivity().RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = intent == null ? mCapturedImageURI : intent.getData();
}
}
catch(Exception e)
{
Toast.makeText(getActivity().getApplicationContext(), "activity :"+e, Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
.
.
.
.
.
}
and YOU ALSO NEED TO PUT THE BELOW CODE AT MainActivity
public class MainActivity extends Activity {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
.
.
.
.
}

Nokia: Error preverifying class java/langnoclassdeffounderror : java/lang/comparable for java me platform

Getting error preverifying class java/langnoclassdeffounderror : java/lang/comparable for java me platform.
I have migrated my J2SE code to J2ME code. I am aware that some functions J2SE functions don't work on J2ME platform. Therefore, i have already crosschecked for the Comparable class. It is included in Java ME libraries.
Now, i am unable to resolve the errors. Please help me out here.
Please refer the code below:
import java.io.Serializable;
import aiproject.CompareToBuilder;
import aiproject.EqualsBuilder;
import aiproject.HashCodeBuilder;
import aiproject.ToStringBuilder;
public class WordProbability implements Comparable, Serializable {
private static final int UNDEFINED = -1;
private String word = "";
private String category = ICategorisedCategorizer.DEFAULT_CATEGORY;
private long matchingCount = UNDEFINED;
private long nonMatchingCount = UNDEFINED;
private double probability = ICategorizer.NEUTRAL_PROBABILITY;
public WordProbability() {
setMatchingCount(0);
setNonMatchingCount(0);
}
public WordProbability(String w) {
setWord(w);
setMatchingCount(0);
setNonMatchingCount(0);
}
public WordProbability(String c, String w) {
setCategory(c);
setWord(w);
setMatchingCount(0);
setNonMatchingCount(0);
}
public WordProbability(String w, double probability) {
setWord(w);
setProbability(probability);
}
public WordProbability(String w, long matchingCount, long nonMatchingCount) {
setWord(w);
setMatchingCount(matchingCount);
setNonMatchingCount(nonMatchingCount);
}
public void setWord(String w) {
this.word = w;
}
public void setCategory(String category) {
this.category = category;
}
public void setProbability(double probability) {
this.probability = probability;
this.matchingCount = UNDEFINED;
this.nonMatchingCount = UNDEFINED;
}
public void setMatchingCount(long matchingCount) {
if (matchingCount < 0) {
throw new IllegalArgumentException("matchingCount must be greater than 0");
}
this.matchingCount = matchingCount;
calculateProbability();
}
public void setNonMatchingCount(long nonMatchingCount) {
if (nonMatchingCount < 0) {
throw new IllegalArgumentException("nonMatchingCount must be greater than 0");
}
this.nonMatchingCount = nonMatchingCount;
calculateProbability();
}
public void registerMatch() {
if (matchingCount == Long.MAX_VALUE) {
throw new UnsupportedOperationException("Long.MAX_VALUE reached, can't register more matches");
}
matchingCount++;
calculateProbability();
}
public void registerNonMatch() {
if (nonMatchingCount == Long.MAX_VALUE) {
throw new UnsupportedOperationException("Long.MAX_VALUE reached, can't register more matches");
}
nonMatchingCount++;
calculateProbability();
}
private void calculateProbability() {
String method = "calculateProbability() ";
double result = ICategorizer.NEUTRAL_PROBABILITY;
if (matchingCount == 0) {
if (nonMatchingCount == 0) {
result = ICategorizer.NEUTRAL_PROBABILITY;
} else {
result = ICategorizer.LOWER_BOUND;
}
} else {
result = BayesianCategorizer.normaliseSignificance((double) matchingCount / (double) (matchingCount + nonMatchingCount));
}
probability = result;
}
/**
* output
*/
public double getProbability() {
return probability;
}
public long getMatchingCount() {
if (matchingCount == UNDEFINED) {
throw new UnsupportedOperationException("MatchingCount has not been defined");
}
return matchingCount;
}
public long getNonMatchingCount() {
if (nonMatchingCount == UNDEFINED) {
throw new UnsupportedOperationException("nonMatchingCount has not been defined");
}
return nonMatchingCount;
}
public String getWord() {
return word;
}
public String getCategory() {
return category;
}
public boolean equals(Object o) {
if (!(o instanceof WordProbability)) {
return false;
}
WordProbability rhs = (WordProbability) o;
return new EqualsBuilder().append(getWord(), rhs.getWord()).append(getCategory(), rhs.getCategory()).isEquals();
}
public int compareTo(java.lang.Object o) {
if (!(o instanceof WordProbability)) {
throw new ClassCastException(o.getClass() + " is not a " + this.getClass());
}
WordProbability rhs = (WordProbability) o;
return new CompareToBuilder().append(this.getCategory(), rhs.getCategory()).append(this.getWord(), rhs.getWord()).toComparison();
}
public String toString() {
return new ToStringBuilder(this).append("word", word).append("category", category).append("probability", probability).append("matchingCount", matchingCount).append("nonMatchingCount", nonMatchingCount).toString();
}
public int hashCode() {
return new HashCodeBuilder(17, 37).append(word).append(category).toHashCode();
}
}
I don't see a Comparable in the javadocs of JavaME.
So I think it is not there.
Where did you found it?
Maybe some Lib or JSR has included it. Than you need to include this in the project settings.
If you just need the interface, you can define it yourself.

How to get path from TreeSelectionListener

Here is my problem. I would like to write a primitive MultiRenameTool (the rename part is not important yet).
You could browse the directories on the left side (JTree), and when you select one, you could see its content on the right side (JTable - just the files).
The problem is, that I can't figure out how to pass the the selected directory to the JTable's list.
I've used the code of Kirill Grouchnikov for the JTree and I slighty modified it.
import java.awt.BorderLayout;
import java.awt.Component;
import java.io.File;
import java.io.FileFilter;
import java.util.*;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
/**
* #author Kirill Grouchnikov
*/
public class FileTreePanel extends JPanel {
protected static FileSystemView fsv = FileSystemView.getFileSystemView();
private JTree tree;
//At first I was trying this - but it is wrong.
public static File current;
private static class FileTreeCellRenderer extends DefaultTreeCellRenderer {
private Map<String, Icon> iconCache = new HashMap<String, Icon>();
private Map<File, String> rootNameCache = new HashMap<File, String>();
#Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
FileTreeNode ftn = (FileTreeNode) value;
File file = ftn.file;
String filename = "";
if (file != null) {
if (ftn.isFileSystemRoot) {
filename = this.rootNameCache.get(file);
if (filename == null) {
filename = fsv.getSystemDisplayName(file);
this.rootNameCache.put(file, filename);
}
} else {
filename = file.getName();
}
}
JLabel result = (JLabel) super.getTreeCellRendererComponent(tree, filename, sel, expanded, leaf, row, hasFocus);
if (file != null) {
Icon icon = this.iconCache.get(filename);
if (icon == null) {
icon = fsv.getSystemIcon(file);
this.iconCache.put(filename, icon);
}
result.setIcon(icon);
}
return result;
}
}
private static class FileTreeNode implements TreeNode {
private File file;
private File[] children;
private TreeNode parent;
private boolean isFileSystemRoot;
public FileTreeNode(File file, boolean isFileSystemRoot, TreeNode parent) {
this.file = file;
this.isFileSystemRoot = isFileSystemRoot;
this.parent = parent;
this.children = this.file.listFiles(new FileFilter() {
//!Modification here - display only the directories
#Override
public boolean accept(File file) {
return file.isDirectory();
}
});
if (this.children == null) {
this.children = new File[0];
}
//obliviously wrong "solution" :(
current = file;
}
public FileTreeNode(File[] children) {
this.file = null;
this.parent = null;
this.children = children;
}
#Override
public Enumeration<?> children() {
final int elementCount = this.children.length;
return new Enumeration<File>() {
int count = 0;
#Override
public boolean hasMoreElements() {
return this.count < elementCount;
}
#Override
public File nextElement() {
if (this.count < elementCount) {
return FileTreeNode.this.children[this.count++];
}
throw new NoSuchElementException("Nincs több elem.");
}
};
}
#Override
public boolean getAllowsChildren() {
return true;
}
#Override
public TreeNode getChildAt(int childIndex) {
return new FileTreeNode(this.children[childIndex],
this.parent == null, this);
}
#Override
public int getChildCount() {
return this.children.length;
}
#Override
public int getIndex(TreeNode node) {
FileTreeNode ftn = (FileTreeNode) node;
for (int i = 0; i < this.children.length; i++) {
if (ftn.file.equals(this.children[i])) {
return i;
}
}
return -1;
}
#Override
public TreeNode getParent() {
return this.parent;
}
#Override
public boolean isLeaf() {
return (this.getChildCount() == 0);
}
}
public FileTreePanel() {
super();
this.setLayout(new BorderLayout());
File[] roots = File.listRoots();
FileTreeNode rootTreeNode = new FileTreeNode(roots);
this.tree = new JTree(rootTreeNode);
this.tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
this.tree.setCellRenderer(new FileTreeCellRenderer());
this.tree.setRootVisible(true);
this.tree.addTreeSelectionListener(new JTreeSelectionListener());
JScrollPane jsp = new JScrollPane(this.tree);
this.add(jsp, BorderLayout.CENTER);
}
private class JTreeSelectionListener implements TreeSelectionListener {
#Override
public void valueChanged(TreeSelectionEvent jtsl) {
TreePath o = jtsl.getPath();
System.out.println(o);
System.out.println(current);
SelectionList.listBuilder(current);
}
}
}
The most important part is at the end, at the TreeSelectionEvent. Here somehow I should be able to convert/make/cast a File from the actually selected Directory.
import java.awt.BorderLayout;
import java.awt.Color;
import java.io.File;
import java.io.FileFilter;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class SelectionList extends JPanel {
private static FilesData data;
private static JTable table;
public SelectionList() {
super();
data = new FilesData();
table = new JTable(data);
table.setFillsViewportHeight(true);
table.setShowGrid(true);
table.setGridColor(Color.BLACK);
JScrollPane jsp = new JScrollPane(table);
this.add(jsp, BorderLayout.CENTER);
}
public static void listBuilder(final File f) {
data.files.clear();
File[] fs = f.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.isFile();
}
});
if (fs != null) {
for (File m : fs) {
Files ujFile = new Files(m, m.isHidden(), Menu.checkAll.getState());
if (!m.isHidden() || Menu.hiddenFilesVisibility.getState()) {
data.files.add(ujFile);
}
}
}
table.repaint();
}
}
It is interesting because of the listBuilder function. I think it is enough information, but if you need my other classes too, I will upload it. I appreciate any help! Thank you all in avance. Anyone? :(
The following snippet shows how you may get the file from the path inside valueChanged:
public void valueChanged(TreeSelectionEvent jtsl) {
TreePath path = jtsl.getPath();
FileTreeNode filenode = (FileTreeNode) path.getLastPathComponent();
File file = filenode.file;
...
}

Resources