Search Results

Search found 24043 results on 962 pages for 'private methods'.

Page 86/962 | < Previous Page | 82 83 84 85 86 87 88 89 90 91 92 93  | Next Page >

  • Can I use boost::make_shared with a private constructor?

    - by Billy ONeal
    Consider the following: class DirectoryIterator; namespace detail { class FileDataProxy; class DirectoryIteratorImpl { friend class DirectoryIterator; friend class FileDataProxy; WIN32_FIND_DATAW currentData; HANDLE hFind; std::wstring root; DirectoryIteratorImpl(); explicit DirectoryIteratorImpl(const std::wstring& pathSpec); void increment(); public: ~DirectoryIteratorImpl() {}; }; class FileDataProxy //Serves as a proxy to the WIN32_FIND_DATA struture inside the iterator. { friend class DirectoryIterator; boost::shared_ptr<DirectoryIteratorImpl> iteratorSource; FileDataProxy(boost::shared_ptr<DirectoryIteratorImpl> parent) : iteratorSource(parent) {}; public: std::wstring GetFolderPath() const { return iteratorSource->root; } }; } class DirectoryIterator : public boost::iterator_facade<DirectoryIterator, detail::FileDataProxy, std::input_iterator_tag> { friend class boost::iterator_core_access; boost::shared_ptr<detail::DirectoryIteratorImpl> impl; void increment() { impl->increment(); }; detail::FileDataProxy dereference() const { return detail::FileDataProxy(impl); }; public: DirectoryIterator() { impl = boost::make_shared<detail::DirectoryIteratorImpl>(); }; }; It seems like DirectoryIterator should be able to call boost::make_shared<DirectoryIteratorImpl>, because it is a friend of DirectoryIteratorImpl. However, this code fails to compile because the constructor for DirectoryIteratorImpl is private. Since this class is an internal implementation detail that clients of DirectoryIterator should never touch, it would be nice if I could keep the constructor private. Is this my fundamental misunderstanding around make_shared or do I need to mark some sort of boost piece as friend in order for the call to compile?

    Read the article

  • How can I use functools.partial on multiple methods on an object, and freeze parameters out of order

    - by Joseph Garvin
    I find functools.partial to be extremely useful, but I would like to be able to freeze arguments out of order (the argument you want to freeze is not always the first one) and I'd like to be able to apply it to several methods on a class at once, to make a proxy object that has the same methods as the underlying object except with some of its methods parameter being frozen (think of it as generalizing partial to apply to classes). I've managed to scrap together a version of functools.partial called 'bind' that lets me specify parameters out of order by passing them by keyword argument. That part works: >>> def foo(x, y): ... print x, y ... >>> bar = bind(foo, y=3) >>> bar(2) 2 3 But my proxy class does not work, and I'm not sure why: >>> class Foo(object): ... def bar(self, x, y): ... print x, y ... >>> a = Foo() >>> b = PureProxy(a, bar=bind(Foo.bar, y=3)) >>> b.bar(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: bar() takes exactly 3 arguments (2 given) I'm probably doing this all sorts of wrong because I'm just going by what I've pieced together from random documentation, blogs, and running dir() on all the pieces. Suggestions both on how to make this work and better ways to implement it would be appreciated ;) One detail I'm unsure about is how this should all interact with descriptors. Code follows. from types import MethodType class PureProxy(object): def __init__(self, underlying, **substitutions): self.underlying = underlying for name in substitutions: subst_attr = substitutions[name] if hasattr(subst_attr, "underlying"): setattr(self, name, MethodType(subst_attr, self, PureProxy)) def __getattribute__(self, name): return getattr(object.__getattribute__(self, "underlying"), name) def bind(f, *args, **kwargs): """ Lets you freeze arguments of a function be certain values. Unlike functools.partial, you can freeze arguments by name, which has the bonus of letting you freeze them out of order. args will be treated just like partial, but kwargs will properly take into account if you are specifying a regular argument by name. """ argspec = inspect.getargspec(f) argdict = copy(kwargs) if hasattr(f, "im_func"): f = f.im_func args_idx = 0 for arg in argspec.args: if args_idx >= len(args): break argdict[arg] = args[args_idx] args_idx += 1 num_plugged = args_idx def new_func(*inner_args, **inner_kwargs): args_idx = 0 for arg in argspec.args[num_plugged:]: if arg in argdict: continue if args_idx >= len(inner_args): # We can't raise an error here because some remaining arguments # may have been passed in by keyword. break argdict[arg] = inner_args[args_idx] args_idx += 1 f(**dict(argdict, **inner_kwargs)) new_func.underlying = f return new_func

    Read the article

  • Why aren't Admob click callback delegate methods getting called?

    - by executor21
    I'm integrating the latest version of the admob sdk (version 20100412) into my app. The ads get displayed, but I need the app to make some changes when an ad is clicked and admob displays a full-screen browser. However, none of the callback methods (willPresentFullScreenModal, didPresentFullScreenModal, willDismissFullScreenModal, and didDismissFullScreenModal) are called, even though other delegate methods are. Why aren't these callbacks being made? They were in the previous versions of the SDK, and the sample app doesn't use them, so it's no help. EDIT: removed the double negative from the question title

    Read the article

  • Access 2007 DAO VBA Error 3381 causes objects in calling methods to "break".

    - by MT
    ---AFTER FURTHER INVESTIGATION--- "tblABC" in the below example must be a linked table (to another Access database). If "tblABC" is in the same database as the code then the problem does not occur. Hi, We have recently upgraded to Office 2007. We have a method in which we have an open recordset (DAO). We then call another sub (UpdatingSub below) that executes SQL. This method has its own error handler. If error 3381 is encountered then the recordset in the calling method becomes "unset" and we get error 3420 'Object invalid or no longer set'. Other errors in UpdatingSub do not cause the same problem. This code works fine in Access 2003. Private Sub Whatonearth() Dim rs As dao.Recordset set rs = CurrentDb.OpenRecordset("tblLinkedABC") Debug.Print rs.RecordCount UpdatingSub "ALTER TABLE tblTest DROP Column ColumnNotThere" 'Error 3240 occurs on the below line even though err 3381 is trapped in the calling procedure 'This appears to be because error 3381 is encountered when calling UpdatingSub above Debug.Print rs.RecordCount End Sub Private Sub WhatonearthThatWorks() Dim rs As dao.Recordset set rs = CurrentDb.OpenRecordset("tblLinkedABC") Debug.Print rs.RecordCount 'Change the update to generate a different error UpdatingSub "NONSENSE SQL STATEMENT" 'Error is trapped in UpdatingSub. Next line works fine. Debug.Print rs.RecordCount End Sub Private Sub UpdatingSub(strSQL As String) On Error GoTo ErrHandler: CurrentDb.Execute strSQL ErrHandler: 'LogError' End Sub Any thoughts? We are running Office Access 2007 (12.0.6211.1000) SP1 MSO (12.0.6425.1000). Perhaps see if SP2 can be distributed? Sorry about formatting - not sure how to fix that.

    Read the article

  • Why don't Domain class static methods work from inside a grails "service"?

    - by ?????
    I want a grails service to be able to access Domain static methods, for queries, etc. For example, in a controller, I can call IncomingCall.count() to get the number of records in table "IncomingCall" but if I try to do this from inside a service, I get the error: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'incomingStatusService': Invocation of init method failed; nested exception is groovy.lang.MissingMethodException: No signature of method: static ms.wdw.tropocontrol.IncomingCall.count() is applicable for argument types: () values: [] How do these methods get injected? There's no magic def statement in a controller that appears to do this. Or is the problem that Hibernate isn't available from my Service class?

    Read the article

  • [hibernate - jpa] @OneToOne annotoation problem (i think...)

    - by blow
    Hi all, im new in hibernate and JPA and i have some problems with annotations. My target is to create this table in db (PERSON_TABLE with personal-details) ID ADDRESS NAME SURNAME MUNICIPALITY_ID First of all, i have a MUNICIPALITY table in db containing all municipality of my country. I mapped this table in this ENTITY: @Entity public class Municipality implements Serializable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String country; private String province; private String name; @Column(name="cod_catasto") private String codCatastale; private String cap; public Municipality() { } ... Then i make an EMBEDDABLE class Address containing fields that realize a simple address... @Embeddable public class Address implements Serializable { @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="id_municipality") private Municipality municipality; @Column(length=45) private String address; public Address() { } ... Finally i embedded this class into Person ENTITY @Entity public class Person implements Serializable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String name; private String surname; @Embedded private Address address; public Person() { } ... All works good when i have to save a new Person record, in fact hibernate creates a PERSON_TABLE as i want, but if i try to retrieve a Person record i have an exception. HQL is simply "from Person" The excpetion is (Entities is the package containing all classes above-mentioned): org.hibernate.AnnotationException: @OneToOne or @ManyToOne on Entities.Person.address.municipality references an unknown entity: Entities.Municipality Is the @OneToOne annotation the problem? Thanks.

    Read the article

  • Differentiate generic methods by type parameters only using reflection?

    - by Brian Vallelunga
    I'm trying to use reflection to get a specific MethodInfo of a class, but am unsure how to differentiate between the two following methods: public class Test { public IBar<T1> Foo<T1>(); public IBar<T1, T2> Foo<T1, T2>(); } How can I get a reference to the different Foo methods, assuming I know the number of type parameters? Just calling typeof(Test).GetMethod("Foo") will throw an exception that the method name is ambiguous and there aren't a differing number of parameters to check.

    Read the article

  • Easiest way to convert json data into objects with methods attached?

    - by John Mee
    What's the quickest and easiest way to convert my json, containing the data of the objects, into actual objects with methods attached? By way of example, I get data for a fruitbowl with an array of fruit objects which in turn contain an array of seeds thus: {"fruitbowl": [{ "name": "apple", "color": "red", "seeds": [] },{ "name": "orange", "color": "orange", "seeds": [ {"size":"small","density":"hard"}, {"size":"small","density":"soft"} ]} } That's all nice and good but down on the client we do stuff with this fruit, like eat it and plant trees... var fruitbowl = [] function Fruit(name, color, seeds){ this.name = name this.color = color this.seeds = seeds this.eat = function(){ // munch munch } } function Seed(size, density){ this.size = size this.density = density this.plant = function(){ // grow grow } } My ajax's success routine currently is currently looping over the thing and constructing each object in turn and it doesn't handle the seeds yet, because before I go looping over seed constructors I'm thinking Is there not a better way? success: function(data){ fruitbowl.length = 0 $.each(data.fruitbowl, function(i, f){ fruitbowl.push(new Fruit(f.name, f.color, f.seeds)) }) I haven't explored looping over the objects as they are and attaching all the methods. Would that work?

    Read the article

  • Adding methods to an Objective C class interface is optional?

    - by Steve the Plant
    Coming from a C++ background, one thing that confuses me about Objective C is the fact that you can add a method to a class without actually specifying it in the class interface. So I had a barrage of questions: Why would someone choose to not add the method in the class interface? Is it simply because of visibility? Methods without a declaration in the interface are private? Is declaring methods in a class interface just optional? Is it different for overriding a base class' method?

    Read the article

  • What methods are there to configure puppet to serve resources for multiple environments?

    - by cclark
    I seem to come across two ways for using puppet in multiple environments: 1) Install a puppetmaster in each environment and only update the recipes from source control for that environment when ready to deploy the recipes in that environment. 2) Use one puppetmaster and use a variable in the puppet.conf of each client to specify the environment and then in the puppetmaster specify a different modulepath for each environment and each of those paths is updated to the branch of the recipe repository intended for that environment (e.g. dev, staging, production). Only running one puppetmaster seems like it is one less piece of infrastructure to keep running but there is some additional complexity in the configuration. Are there additional pros or cons to one of these methods or something which I'm missing entirely?

    Read the article

  • How do I dynamically update an instance array to hold a list of dynamic methods on instantiation?

    - by Will
    I am trying to dynamically define methods based on xml mappings. This works really well. However I want to create an instance variable that is a array of the dynamically defined methods. My code looks something like this def xml_attr_reader(*args) xml_list = "" args.each do |arg| string_val = "def #{arg}; " + " xml_mapping.#{arg}; " + "end; " self.class_eval string_val xml_hash = xml_list + "'#{arg}'," end self.class_eval "@xml_attributes = [] if @xml_attributes.nil?;" + "@xml_attributes = @xml_attributes + [#{xml_list}];" + "puts 'xml_attrs = ' + @xml_attributes.to_s;" + "def xml_attributes;" + " puts 'xml_attrs = ' + @xml_attributes.to_s;" + " @xml_attributes;" + "end" end So everything works except when I call xml_attributes on an instance it return null (and prints out 'xml_attrs = '). While the puts before the definition actually prints out the correct array. (when I instantiate the instance)

    Read the article

  • Performance Impact of Generating 100's of Dynamic Methods in Ruby?

    - by viatropos
    What are the performance issues associated with generating 100's of dynamic methods in Ruby? I've been interested in using the Ruby Preferences Gem and noticed that it generates a bunch of helper methods for each preference you set. For instance: class User < ActiveRecord::Base preference :hot_salsa end ...generates something like: user.prefers_hot_salsa? # => false user.prefers_hot_salsa # => false If there are 100's of preferences like this, how does this impact the application? I assume it's not really a big deal but I'm just wondering, theoretically.

    Read the article

  • Javascript (using jQuery) in a large Project... organization, passing data, private method, etc.

    - by gaoshan88
    I'm working on a large project that is organized like so: Multiple javascript files are included as needed and most code is wrapped in anonymous functions... // wutang.js //Included Files Go Here // Public stuff var MethodMan; // Private stuff (function() { var someVar1; MethodMan = function(){...}; var APrivateMethod = function(){...}; $(function(){ //jquery page load stuff here $('#meh').click(APrivateMethod); }); })(); I'm wondering about a few things here. Assuming that there are a number of these files included on a page, what has access to what and what is the best way to pass data between the files? For example, I assume that MethodMan() can be accessed by anything on any included page. It is public, yes? var someVar1 is only accessible to the methods inside that particular anonymous function and nowhere else, yes? Also true of var APrivateMethod(), yes? What if I want APrivateMethod() to make something available to some other method in a different anonymous wrapped method in a different included page. What's the best way to pass data between these private, anonymous functions on different included pages? Do I simply have to make whatever I want to use between them public? How about if I want to minimize global variables? What about the following: var PootyTang = function(){ someVar1 = $('#someid').text(); //some stuff }; and in another included file used by that same page I have: var TangyPoot = function(){ someVar1 = $('#someid').text(); //some completely different stuff }; What's the best way to share the value of someVar1 across these anonymous (they are wrapped as the first example) functions?

    Read the article

  • Hibernate JPA Caching Problem, Please help!

    - by Sameer Malhotra
    Ok, Here is my problem. I have a table named Master_Info_tbl. Its a lookup table: Here is the code for the table: @Entity @Table(name="MASTER_INFO_T") public class CodeValue implements java.io.Serializable { private static final long serialVersionUID = -3732397626260983394L; private Integer objectid; private String codetype; private String code; private String shortdesc; private String longdesc; private Integer dptid; private Integer sequen; private Timestamp begindate; private Timestamp enddate; private String username; private Timestamp rowlastchange; //getter Setter methods I have a service layer which calls the method       service.findbycodeType("Code1");   same way this table is queried for the other code types as well e.g. code2, code3 and so on till code10 which gets the result set from the same table and is shown into the drop down of the jsp pages since these drop downs are in 90% of the pages I am thinking to cache them globally. Any idea how to achieve this? FYI: I am using JPA and Hibernate with Struts2 and Spring. The database being used is DB2 UDB8.2 Please help!

    Read the article

  • How to rename an private file of my application?

    - by Ungureanu Liviu
    Hi! I want to rename an context private file created with openFileOutput() but I don't know how... I tried that: File file = getFileStreamPath(optionsMenuView.getPlaylistName()); // this file already exists try { FileOutputStream outStream = openFileOutput(newPlaylistName, Context.MODE_WORLD_READABLE); // i create a new file with the new name outStream.close(); } catch (FileNotFoundException e) { Log.e(TAG, "file not found!"); e.printStackTrace(); } catch (IOException e) { Log.e(TAG, "IO exception"); e.printStackTrace(); } Log.e(TAG, "rename status: " + file.renameTo(getFileStreamPath(newPlaylistName))); //it return true This code throw FileNotFoundException but the documentation said "Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist." so the new file should be created on disk. The problem: When I try to read from the new renamed file I got FileNotFoundException! Thank you!

    Read the article

  • Is it possible, in ASP .net, to reference private assembly in a non-virtual subdirectory?

    - by Bago
    Is it possible to reference a private assembly in asp .net from a sub-folder that is not setup as a virtual directory? In other words, my page is setup in ~/subdir, I don't have access to ~/, and I am not an IIS admin. Can I reference a private assembly? How would I do this? I've tried <%@ Assembly Src="/subdir/bin/Assembly.dll % and <%@ Assembly Src="/subdir/bin/Assembly.dll % , but I get the messages "There is no build provider to match the extension .dll" or "Failed to map to path" respectively. Here is my folder structure: / | -subdir | | - Bin | | | *Assembly.dll | | *Default.aspx I've heard that in web.config might do the trick, but when I've tried it, it doesn't seem to work. Furthermore, I've read that only works in the application .config file. (i.e., the one in ~/). Anyhow, I already tried adding the following to web.config: <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="/subdir/bin" /> <dependentAssembly> <codeBase href="/subdir/bin/Assembly.dll"/> </dependentAssembly> </assemblyBinding> For more background on my problem, I am simply using a shared host, all I have is access to is that subdirectory, and I am trying to use fckeditor.

    Read the article

  • Is it possible, in ASP.net, to reference private assembly in a non-virtual subdirectory?

    - by Bago
    Is it possible to reference a private assembly in asp .net from a sub-folder that is not setup as a virtual directory? In other words, my page is setup in ~/subdir, I don't have access to ~/, and I am not an IIS admin. Can I reference a private assembly? How would I do this? I've tried <%@ Assembly Src="/subdir/bin/Assembly.dll % and <%@ Assembly Src="/subdir/bin/Assembly.dll % , but I get the messages "There is no build provider to match the extension .dll" or "Failed to map to path" respectively. Here is my folder structure: / | -subdir | | - Bin | | | *Assembly.dll | | *Default.aspx I've heard that in web.config might do the trick, but when I've tried it, it doesn't seem to work. Furthermore, I've read that only works in the application .config file. (i.e., the one in ~/). Anyhow, I already tried adding the following to web.config: <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="/subdir/bin" /> <dependentAssembly> <codeBase href="/subdir/bin/Assembly.dll"/> </dependentAssembly> </assemblyBinding> For more background on my problem, I am simply using a shared host, all I have is access to is that subdirectory, and I am trying to use fckeditor.

    Read the article

  • Is it a good or bad practice to call instance methods from a java constructor?

    - by Steve
    There are several different ways I can initialize complex objects (with injected dependencies and required set-up of injected members), are all seem reasonable, but have various advantages and disadvantages. I'll give a concrete example: final class MyClass { private final Dependency dependency; @Inject public MyClass(Dependency dependency) { this.dependency = dependency; dependency.addHandler(new Handler() { @Override void handle(int foo) { MyClass.this.doSomething(foo); } }); doSomething(0); } private void doSomething(int foo) { dependency.doSomethingElse(foo+1); } } As you can see, the constructor does 3 things, including calling an instance method. I've been told that calling instance methods from a constructor is unsafe because it circumvents the compiler's checks for uninitialized members. I.e. I could have called doSomething(0) before setting this.dependency, which would have compiled but not worked. What is the best way to refactor this? Make doSomething static and pass in the dependency explicitly? In my actual case I have three instance methods and three member fields that all depend on one another, so this seems like a lot of extra boilerplate to make all three of these static. Move the addHandler and doSomething into an @Inject public void init() method. While use with Guice will be transparent, it requires any manual construction to be sure to call init() or else the object won't be fully-functional if someone forgets. Also, this exposes more of the API, both of which seem like bad ideas. Wrap a nested class to keep the dependency to make sure it behaves properly without exposing additional API:class DependencyManager { private final Dependency dependency; public DependecyManager(Dependency dependency) { ... } public doSomething(int foo) { ... } } @Inject public MyClass(Dependency dependency) { DependencyManager manager = new DependencyManager(dependency); manager.doSomething(0); } This pulls instance methods out of all constructors, but generates an extra layer of classes, and when I already had inner and anonymous classes (e.g. that handler) it can become confusing - when I tried this I was told to move the DependencyManager to a separate file, which is also distasteful because it's now multiple files to do a single thing. So what is the preferred way to deal with this sort of situation?

    Read the article

  • When can we mock an object and its methods?

    - by Shailendra
    I am novice to the Moq and unit testing. I have to write unit tests to a lot of classes which has the objects of other classes. can i mock the methods of the class objects. Here is the exact scenerio- I have a class two classes A and B and A has a private object of B and in a method of A i am internally calling the method of B and then doing some calculation and returning the result. Can i mock the method of B in this scenerio? Please try to give me full detail about the conditions where i can mock the methods and functions of the class. Thanx

    Read the article

  • Is there an automatic way to remove debugging methods for a release build?

    - by Lewis
    Note: This is an extension of an earlier question I asked here: Do additional function/method definitions increase a program's memory footprint? When I write a class, I usually end up writing several testing/debugging methods, used to make sure the class works as it should, or for printing data to help with debugging, or for unit testing, etc. Is there an easy/automatic way to make a release without these methods, or do I need to manually delete the extra code any time I want to compile a release version? I ask this question both from a C++ and a Java perspective. I'm using Code::Blocks and Eclipse as IDEs, if that plays into the answer somehow.

    Read the article

  • Installation error: INSTALL_FAILED_OLDER_SDK in eclipse

    - by user3014909
    I have an unexpe`ted problem with my Android project. I have a real android device with ice_cream sandwich installed. My app was working fine during the development but after I added a class to the project, I got an error: Installation error: INSTALL_FAILED_OLDER_SDK The problem is that everything is good in the manifest file. The minSdkversion is 8. Here is my manifest file: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="zabolotnii.pavel.timer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18 " /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="zabolotnii.pavel.timer.TimerActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> I don't know, if there is any need to attach the new class ,but I didn't any changes to other code that should led to this error: package zabolotnii.pavel.timer; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Environment; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.*; import android.widget.*; import java.io.File; import java.io.FilenameFilter; import java.util.*; public class OpenFileDialog extends AlertDialog.Builder { private String currentPath = Environment.getExternalStorageDirectory().getPath(); private List<File> files = new ArrayList<File>(); private TextView title; private ListView listView; private FilenameFilter filenameFilter; private int selectedIndex = -1; private OpenDialogListener listener; private Drawable folderIcon; private Drawable fileIcon; private String accessDeniedMessage; public interface OpenDialogListener { public void OnSelectedFile(String fileName); } private class FileAdapter extends ArrayAdapter<File> { public FileAdapter(Context context, List<File> files) { super(context, android.R.layout.simple_list_item_1, files); } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getView(position, convertView, parent); File file = getItem(position); if (view != null) { view.setText(file.getName()); if (file.isDirectory()) { setDrawable(view, folderIcon); } else { setDrawable(view, fileIcon); if (selectedIndex == position) view.setBackgroundColor(getContext().getResources().getColor(android.R.color.holo_blue_dark)); else view.setBackgroundColor(getContext().getResources().getColor(android.R.color.transparent)); } } return view; } private void setDrawable(TextView view, Drawable drawable) { if (view != null) { if (drawable != null) { drawable.setBounds(0, 0, 60, 60); view.setCompoundDrawables(drawable, null, null, null); } else { view.setCompoundDrawables(null, null, null, null); } } } } public OpenFileDialog(Context context) { super(context); title = createTitle(context); changeTitle(); LinearLayout linearLayout = createMainLayout(context); linearLayout.addView(createBackItem(context)); listView = createListView(context); linearLayout.addView(listView); setCustomTitle(title) .setView(linearLayout) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (selectedIndex > -1 && listener != null) { listener.OnSelectedFile(listView.getItemAtPosition(selectedIndex).toString()); } } }) .setNegativeButton(android.R.string.cancel, null); } @Override public AlertDialog show() { files.addAll(getFiles(currentPath)); listView.setAdapter(new FileAdapter(getContext(), files)); return super.show(); } public OpenFileDialog setFilter(final String filter) { filenameFilter = new FilenameFilter() { @Override public boolean accept(File file, String fileName) { File tempFile = new File(String.format("%s/%s", file.getPath(), fileName)); if (tempFile.isFile()) return tempFile.getName().matches(filter); return true; } }; return this; } public OpenFileDialog setOpenDialogListener(OpenDialogListener listener) { this.listener = listener; return this; } public OpenFileDialog setFolderIcon(Drawable drawable) { this.folderIcon = drawable; return this; } public OpenFileDialog setFileIcon(Drawable drawable) { this.fileIcon = drawable; return this; } public OpenFileDialog setAccessDeniedMessage(String message) { this.accessDeniedMessage = message; return this; } private static Display getDefaultDisplay(Context context) { return ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); } private static Point getScreenSize(Context context) { Point screeSize = new Point(); getDefaultDisplay(context).getSize(screeSize); return screeSize; } private static int getLinearLayoutMinHeight(Context context) { return getScreenSize(context).y; } private LinearLayout createMainLayout(Context context) { LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setMinimumHeight(getLinearLayoutMinHeight(context)); return linearLayout; } private int getItemHeight(Context context) { TypedValue value = new TypedValue(); DisplayMetrics metrics = new DisplayMetrics(); context.getTheme().resolveAttribute(android.R.attr.listPreferredItemHeightSmall, value, true); getDefaultDisplay(context).getMetrics(metrics); return (int) TypedValue.complexToDimension(value.data, metrics); } private TextView createTextView(Context context, int style) { TextView textView = new TextView(context); textView.setTextAppearance(context, style); int itemHeight = getItemHeight(context); textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight)); textView.setMinHeight(itemHeight); textView.setGravity(Gravity.CENTER_VERTICAL); textView.setPadding(15, 0, 0, 0); return textView; } private TextView createTitle(Context context) { TextView textView = createTextView(context, android.R.style.TextAppearance_DeviceDefault_DialogWindowTitle); return textView; } private TextView createBackItem(Context context) { TextView textView = createTextView(context, android.R.style.TextAppearance_DeviceDefault_Small); Drawable drawable = getContext().getResources().getDrawable(android.R.drawable.ic_menu_directions); drawable.setBounds(0, 0, 60, 60); textView.setCompoundDrawables(drawable, null, null, null); textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { File file = new File(currentPath); File parentDirectory = file.getParentFile(); if (parentDirectory != null) { currentPath = parentDirectory.getPath(); RebuildFiles(((FileAdapter) listView.getAdapter())); } } }); return textView; } public int getTextWidth(String text, Paint paint) { Rect bounds = new Rect(); paint.getTextBounds(text, 0, text.length(), bounds); return bounds.left + bounds.width() + 80; } private void changeTitle() { String titleText = currentPath; int screenWidth = getScreenSize(getContext()).x; int maxWidth = (int) (screenWidth * 0.99); if (getTextWidth(titleText, title.getPaint()) > maxWidth) { while (getTextWidth("..." + titleText, title.getPaint()) > maxWidth) { int start = titleText.indexOf("/", 2); if (start > 0) titleText = titleText.substring(start); else titleText = titleText.substring(2); } title.setText("..." + titleText); } else { title.setText(titleText); } } private List<File> getFiles(String directoryPath) { File directory = new File(directoryPath); List<File> fileList = Arrays.asList(directory.listFiles(filenameFilter)); Collections.sort(fileList, new Comparator<File>() { @Override public int compare(File file, File file2) { if (file.isDirectory() && file2.isFile()) return -1; else if (file.isFile() && file2.isDirectory()) return 1; else return file.getPath().compareTo(file2.getPath()); } }); return fileList; } private void RebuildFiles(ArrayAdapter<File> adapter) { try { List<File> fileList = getFiles(currentPath); files.clear(); selectedIndex = -1; files.addAll(fileList); adapter.notifyDataSetChanged(); changeTitle(); } catch (NullPointerException e) { String message = getContext().getResources().getString(android.R.string.unknownName); if (!accessDeniedMessage.equals("")) message = accessDeniedMessage; Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show(); } } private ListView createListView(Context context) { ListView listView = new ListView(context); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) { final ArrayAdapter<File> adapter = (FileAdapter) adapterView.getAdapter(); File file = adapter.getItem(index); if (file.isDirectory()) { currentPath = file.getPath(); RebuildFiles(adapter); } else { if (index != selectedIndex) selectedIndex = index; else selectedIndex = -1; adapter.notifyDataSetChanged(); } } }); return listView; } }

    Read the article

< Previous Page | 82 83 84 85 86 87 88 89 90 91 92 93  | Next Page >