Showing posts with label Concepts. Show all posts
Showing posts with label Concepts. Show all posts

Tuesday, December 18, 2012

Convert Seconds into HH:MM:SS in java?

Below are the methods to convert seconds into minute seconds format...


int day = (int)TimeUnit.SECONDS.toDays(seconds);      
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
 System.out.println("Random Element "+minute+":"+second);

OR 

public static void calculateTime(long seconds) {
   int day = (int) TimeUnit.SECONDS.toDays(seconds);
   long hours = TimeUnit.SECONDS.toHours(seconds) -
                TimeUnit.DAYS.toHours(day);
   long minute = TimeUnit.SECONDS.toMinutes(seconds) -
                 TimeUnit.DAYS.toMinutes(day) -
                 TimeUnit.HOURS.toMinutes(hours);
   long second = TimeUnit.SECONDS.toSeconds(seconds) -
                 TimeUnit.DAYS.toSeconds(day) -
                 TimeUnit.HOURS.toSeconds(hours) -
                 TimeUnit.MINUTES.toSeconds(minute);
   System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}

Monday, December 10, 2012

Android serialization of Objects ?


We can also see below links...
http://www.dreamincode.net/forums/topic/248522-serialization-in-android/

I'm going to go through the process of serializing and deserializing an object.

What this means is that we're going to convert an object into an array of bytes, which can easily be moved around or stored (for later use). And for deserialization we just take those bytes and convert them back into an Object.

The first one we have below is the serialization method, which just takes in a generic Object.


  public static byte[] serializeObject(Object o) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
      ObjectOutput out = new ObjectOutputStream(bos);
      out.writeObject(o);
      out.close();

      // Get the bytes of the serialized object
      byte[] buf = bos.toByteArray();

      return buf;
    } catch(IOException ioe) {
      Log.e("serializeObject", "error", ioe);

      return null;
    }
  }

The second one is the deserialization method, which takes in an array of bytes;


  public static Object deserializeObject(byte[] b) {
    try {
      ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
      Object object = in.readObject();
      in.close();

      return object;
    } catch(ClassNotFoundException cnfe) {
      Log.e("deserializeObject", "class not found error", cnfe);

      return null;
    } catch(IOException ioe) {
      Log.e("deserializeObject", "io error", ioe);

      return null;
    }
  }

If you're wondering how to use these, well here is an example.


  public class Bla implements Serializable {
    public String blaDate;
    public String blaText;
  }
 
  Bla bla = new Bla();
 
  // assuming that both those serialize and deserialize methods are under the SerializerClass
  byte[] blaBytes = SerializerClass.serializeObject(bla);
 
  Bla deserializedBla = (Bla) SerializerClass.deserializeObject(blaBytes);

You've probably noticed that I implemented Serializable - you need this in order to serialize an object. Some of the built in objects already have this implemented - for example the ArrayList object.

When deserializing you need to cast it back to what the object was, since it's returning it as a generic Object - hence the (Bla).
Anyways, hope this helped someone, and if you noticed any mistakes, please let me know.

Wednesday, October 17, 2012

How to view the android.jar source code in eclipse?



This plugin helps you to add source to android libraries in Eclipse.

In ADT >=8.0.0 you can add Android sources to Android container for all your project with installing the Android source feature using...

http://adt-addons.googlecode.com/svn/trunk/source/com.android.ide.eclipse.source.update/

After downloading the com.android.ide.eclipse.source_16.0.0.201112171909.jar file in plugin folder, unzip it.We will get the below sources for the following API levels:

14 - Android 4.0.1
10 - Android 2.3.4
9 - Android 2.3
8 - Android 2.2
7 - Android 2.1
6 - Android 2.0.1
4 - Android 1.6
3 - Android 1.5

The plugin is about 240 MB size.

Each folder will contain the sources.zip file within it.Copy zip file from "10" folder and paste it into below path of corresponding version...

android-sdk-linux/platform/android-10/"paste here"

i.e sources.zip and android.jar both file will be in same folder.

Now restart you eclipse and browse to android.jar file,now you can view the source code....


Wednesday, August 8, 2012

How to save custom class object in android Cache?


Create the class MyClass for writing to save object and also for retrieval object........

public class MyClass implements Serializable
{
    private static final long serialVersionUID = 1L;
    public String title;
    public String startTime;
    public String endTime;
    public String day;
    public boolean classEnabled;

     public MyClass(String title, String startTime, boolean enable){
            this.title = title;
            this.startTime = startTime;
            this.classEnabled = enable;
        }


     public MyClass()
     {
     }

     public boolean saveObject(MyClass obj) {

        final File suspend_f=new File(SerializationTest.cacheDir, "test");

            FileOutputStream   fos  = null;
            ObjectOutputStream oos  = null;
            boolean            keep = true;

            try {
                fos = new FileOutputStream(suspend_f);
                oos = new ObjectOutputStream(fos);
                oos.writeObject(obj);
            }
            catch (Exception e) {
                keep = false;


            }
            finally {
                try {
                    if (oos != null)   oos.close();
                    if (fos != null)   fos.close();
                    if (keep == false) suspend_f.delete();
                }
                catch (Exception e) { /* do nothing */ }
            }
            return keep;


        }

     public MyClass getObject(Context c)
     {
         final File suspend_f=new File(SerializationTest.cacheDir, "test");

         MyClass simpleClass= null;
         FileInputStream fis = null;
         ObjectInputStream is = null;
        // boolean            keep = true;

         try {

             fis = new FileInputStream(suspend_f);
             is = new ObjectInputStream(fis);
             simpleClass = (MyClass) is.readObject();
         }catch(Exception e)
         {
            String val= e.getMessage();

         }finally {
                try {
                    if (fis != null)   fis.close();
                    if (is != null)   is.close();

                }
                catch (Exception e) { }
            }

         return simpleClass;
     }
}

And from any of the Activity you can call the above class to save object......

if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"MyCustomObject");
        else
            cacheDir= getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();




       MyClass m= new MyClass( "umer", "asif", true);

          boolean  result =m.saveObject(m);

      if(result)
        Toast.makeText(this, "Saved object", Toast.LENGTH_LONG).show();
      else
          Toast.makeText(this, "Error saving object", Toast.LENGTH_LONG).show();

        MyClass m= new MyClass();
        MyClass c = m.getObject(this);
        if(c!= null)
            Toast.makeText(this, "Retrieved object", Toast.LENGTH_LONG).show();
        else
            Toast.makeText(this, "Error retrieving object", Toast.LENGTH_LONG).show();

}

Dont forget to use write_external_storage permissions in manifest file.And dont use context in it otherwise nonserializable exception will be raised.

Thursday, July 19, 2012

Why override tostring method in java ?




The toString() method in the Object class is used to display some information regarding any object.
If any code needs some information of an object of a class, then it can get it by using this method

The toString() method of an object gets invoked automatically, when an object reference is passed in the System.out.println() method.


package com.example.generics;

public class ToStringMethodTest {
private String companyName;
private String companyAddress;
public ToStringMethodTest(String companyName, String companyAddress) {
this.companyName = companyName;
this.companyAddress = companyAddress;
}
public static void main(String[] args) {
ToStringMethodTest test = new ToStringMethodTest("ABC private Ltd","10, yy Street, CC Town");
System.out.println(test.toString());
}

public String toString() {
return ("Company Name: " + companyName + "n" +
"Company Address: " + companyAddress);
}
  }

OUTPUT:

Company Name: ABC private LtdnCompany Address: 10, yy Street, CC Town

But if you comment the toString() method...you will get output below

com.example.generics.ToStringMethodTest@9304b1


What we have just now seen is just a sample of how a meaningful override of the toString() method would prove to be of great use in displaying an object’s information when we try printing an object using the System.out.println statement during debugging processs.

Monday, July 9, 2012

What is the Difference between Service, Async Task & Thread?



Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.

A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.

An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are two methods that run on UI thread, which is good to update UI components.

I am using Services, AsyncTasks frequently. Thread less, or not at all, as I can do almost everything with AsyncTask.

Friday, July 6, 2012

How to get decimal HTML entity from String in Java?



Below is the method for returning the decimal entity.........

public static String getHTMLEntity(String value) {
StringBuffer testBuffer = new StringBuffer();
char[] test = value.toCharArray();
if (test != null) {
int size1 = test.length;


for (int j = 0; j < size1; j++) {
testBuffer.append("&#");
testBuffer.append(Character.codePointAt(test, j));
testBuffer.append(";");
}
}
return testBuffer.toString();
}


OUTPUT for "सड्फलक्ल क्लजकलसदफ  क्ळज्सलड्फ"


&#2360;&#2337;&#2381;&#2347;&#2354;&#2325;&#2381;&#2354;&#32;&#2325;&#2381;&#2354;&#2332;&#2325;&#2354;&#2360;&#2342;&#2347;&#32;&#32;&#2325;&#2381;&#2355;&#2332;&#2381;&#2360;&#2354;&#2337;&#2381;&#2347;

How to print text from string of HTML decimal entity in Java?


Below is the Code..........


String encodeString="&#2360;&#2337;&#2381;&#2347;&#2354;&#2325;&#2381;&#2354;&#32;&#2325;&#2381;&#2354;&#2332;&#2325;&#2354;&#2360;&#2342;&#2347;&#32;&#32;&#2325;&#2381;&#2355;&#2332;&#2381;&#2360;&#2354;&#2337;&#2381;&#2347;";



 StringBuffer sb = new StringBuffer();
   Matcher m = Pattern.compile("\\&#(\\d+);").matcher(s);
   while (m.find()) {
       int uc = Integer.parseInt(m.group(1));
       m.appendReplacement(sb, "");
       sb.appendCodePoint(uc);
   }
   m.appendTail(sb);



System.out.print(sb.toString());


OUTPUT :
सड्फलक्ल क्लजकलसदफ  क्ळज्सलड्फ

How to get unicode characters from String ?


Below is the Example.....

StringBuffer a = new StringBuffer();
try {
String line = "Shailesh Shukla";
for (int index = 0; index < line.length(); index++) {
String hexCode = Integer.toHexString(line.codePointAt(index))
.toUpperCase();
String hexCodeWithAllLeadingZeros = "0000" + hexCode;
String hexCodeWithLeadingZeros = hexCodeWithAllLeadingZeros
.substring(hexCodeWithAllLeadingZeros.length() - 4);
a.append("\\u" + hexCodeWithLeadingZeros + " ");
}
} catch (Exception e) {
}
System.out.println(a.toString());

OUTPUT For String "Shailesh Shukla"

\u0053 \u0068 \u0061 \u0069 \u006C \u0065 \u0073 \u0068 \u0020 \u0053 \u0068 \u0075 \u006B \u006C \u0061 

Tuesday, May 29, 2012

What is Template Design Patter in Java?


An abstract class defines various methods and has one non-overridden method which calls the various methods.
Wikipedia Says:
A
 template method defines the program skeleton of an aligorithm.The aligorithm itself is made abstract,and the subclasses override the abstract methods to provide concrete behavior.First a class is created that provides the basic steps of an aligorithm design.These steps are implemented using abstract methods.Later on subclasses change the abstract methods to implement real actions.Thus the general aligorithm is saved in one place but the concrete steps may be changed by the subclasses.
Non-Abstract Methods are completly controlled by the Template Method.In contrast the
 template method need not be changed and is not an abstract operation and thus may guarentee required steps before and after the abstract operations.Thus the template method is invoked and as a consequence the non-abstract methods and abstract methods are called in the correct sequence.
Intent: Define the skeleton of an aligorithm in an operation,deferring some steps to subclasses.Template methods lets subclasses redefine certain steps of an aligorithm without changing the aligorithm structure .[DesignPatterns, p. 325]
Motivation:
Sometimes we want to specify the order of operations that a method uses,but allow subclasses to provide their own implementation of some of these operations.When ever we see two methods in subclasses,it makes sense to bring the methods together into a superclass method.
Applicability:
Use the Template method pattern:
·         To implement the invariant parts of an aligorithm once and leave it up to subclasses to implement the behavior that can vary.
·         To localize common behavior among subclasses and place it in a common class(in this case a superclass) to avoid code duplication.This is a classic example of “code refactoring”.
·         To control how subclasses extend superclass operations.You can define a template method that calls “hook” operations at specific points,there by permitting extensions only at that point.
THE TEMPLATE METHOD IS A FUNDAMENTAL TECHNIQUE FOR CODE REUSE
Problem:
Two different component have significant similarities,but demonstrate no reuse of common interface or implementation.If a change common to both components becomes necessary,duplicate effort must be expended.
Discussion:
The component designer decides which steps of an aligorithm are invariant(or standard) and which are variant(or customizable).The invariant steps are implemented in an abstract base class,while the variant steps are either given a default implementation or no implementation at all.The “variant” steps represent “hooks”,or “placeholders” that can or must be supplied by the component’s client in a concrete derived class.
The component designer mandates the required steps of an aligorithm,and the ordering of the steps,but allow the component client to extend or replace some number of steps.
Template methods
 are prominently used in frameworks.Each framework implements the invariant pieces of domain’s architecture,and defines “placeholders” for all necessary or interesting client customization options.The inverted control structure has been affectionately labelled “the hollywood principle” – Don’t call us we will call you.

Usage:
The template method is used to:
·         Let subclasses implement behavior that can vary.
·         Avoid duplication in the code.We look for general code in the aligorithm and implement variants in the subclasses.
·         Control at what point(s) subclassing is allowed.
Implementation Issues:
·         Operations which must be overridden by subclasses should be made abstract.
·         If the template method itself should not be overidden by subclasses it should be made final.
·         To allow a subclass to insert code at a specific spot in the operation of the aligorithm,insert “hook” operations into the template method.These hook operations may do nothing by default.
·         Try to minimize the number of operations that a subclass must override.
·         In a template method parent class calls the operations of a subclass and not the other way round.
Example:
The template method defines a skeleton of an aligorithm in an operation and defers some steps to subclasses.Home Builders use the template method when developing a new subdivision.A typical subdivision consits of a limited number of floor plans with diff variations available for each.Within a floor plan, the foundation, framing, plumbing, and wiring will be identical for each house. Variation is introduced in the later stages of construction to produce a wider variety of models. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]
Template method pattern could be refactored using an interface that explicitly signals the methods requested to subclasses and also the state needed by them from the abstract class.
Rules of Thumb:
Strategy is like Template Method except in its granularity.[Coplien, C++ Report, Mar 96, p88]
Template method uses inheritance to vary part of an aligorithm.Strategy uses delegation to vary the entire aligorithm. [GOF, p330]
Also Alex has a good explanation of why he hates Template Pattern.Even i do agree to some extent.
Below example gives an implementation of Template Design Pattern.
package patterns;

abstract class TitleInfo {
 private String titleName;

 // The Template Method.
 // Calls the concrete class methods,is not overridden

 public final String processTitleInfo() {
  StringBuffer titleInfo=new StringBuffer();
  titleInfo.append(this.getTitleBlurb());
  titleInfo.append(this.getDvdEncodingRegionInfo());
  return titleInfo.toString();
 }

 public final void setTitleName(String titleNameIn) {
  this.titleName=titleNameIn;
 }

 public final String getTitleName() {
  return this.titleName;
 }

 public abstract String getTitleBlurb();

 public String getDvdEncodingRegionInfo() {
  return " ";
 }

}

class DvdTitleInfo extends TitleInfo {
 String star;
 char encodingRegion;

 public DvdTitleInfo(String titleName,String star,char encodingRegion) {
  this.setTitleName(titleName);
  this.setStar(star);
  this.setEncodingRegion(encodingRegion);
 }

 public char getEncodingRegion() {
  return encodingRegion;
 }

 public void setEncodingRegion(char encodingRegion) {
  this.encodingRegion = encodingRegion;
 }

 public String getStar() {
  return star;
 }

 public void setStar(String star) {
  this.star = star;
 }

 public String getTitleBlurb() {
  return ("DVD: " + this.getTitleName() + ", starring " + this.getStar());
 }

 public String getDvdEncodingRegionInfo() {
        return (", encoding region: " + this.getEncodingRegion());
    }
}

class BookTitleInfo extends TitleInfo {
 private String author;

 public BookTitleInfo(String titleName,String author) {
  this.setAuthor(author);
  this.setTitleName(titleName);
 }

 public String getAuthor() {
  return author;
 }

 public void setAuthor(String author) {
  this.author = author;
 }

 public String getTitleBlurb() {
  return ("Book: " + this.getTitleName() + ", Author: " + this.getAuthor());
 }
}

public class TemplatePatternDemo {

 public static void main(String[] args) {
  TitleInfo bladeRunner=new DvdTitleInfo("Blade Runner","Harrison Ford",'1');
  TitleInfo electricSheep=new BookTitleInfo("Do Androids Dream of Electric Sheep?","Philip");

  System.out.println(" ");
  System.out.println("Testing bladeRunner" + bladeRunner.processTitleInfo());
  System.out.println("Testing electricSheep" + electricSheep.processTitleInfo());
 }
}

CallBack example in java?


Create a class Callback.java

package com.etretatlogiciels.callback.example;

public interface Callback
{
 void methodToCall();
}

Create another class CallbackImpl.java

package com.etretatlogiciels.callback.example;

public class CallbackImpl implements Callback
{
 @Override
 public void methodToCall()
 {
  System.out.println( "I've been called back!" );
 }
}
Create another class Caller.java

package com.etretatlogiciels.callback.example;

/**
 * This is my idea of how a formal call-back mechanism works. There are examples in the
 * real world, very common in Android code, for instance: look for View.OnClickListener().
 */
public class Caller
{
 public Callback callback = null;

/* register a method to be called back at some future, arbitrary point */
 public void register( Callback callback )
 {
  this.callback = callback;
 }

/* how Caller invokes the call-back method at the appropriate juncture  */
 public void execute()
 {
  this.callback.methodToCall();
 }

/* directly execute a method (I don't see this is a "call-back" at all) */
 public void execute( Callback callback )
 {
  callback.methodToCall();
 }

 public static void main( String args[] )
 {
  Caller  caller   = new Caller();
  Callback callback = new CallbackImpl();

  /* Demonstrate simple calling back.
   */
  caller.register( callback );
  caller.execute();

/*Demonstrate direct calling back (here, immediate execution) by creating an "on
*the fly" call-back. In a real world example, caller.execute( Callback callback )* would be a mechanism that properly establishes a situation in which, later, the* "direct" call would issue. This is very common in Android code as noted above.
*/
  caller.execute( new Callback()
   {
    public void methodToCall()
    {
   System.println( "This is our \"on the fly\" method..." );
    }
   }
  );
 }
}

Below is the output
I've been called back!
This is our "on the fly" method...

CallBack Example in Java ?


interface Callable
{
    public void callBackMethod();
}
class Worker
{
    // Worker gets a handle to the boss object via the Callable interface.
    // There's no way this worker class can call any other method other than
    // the one in Callable.
    public void doSomeWork(Callable myBoss)
    {
        myBoss.callBackMethod();
        // ERROR!
        //myBoss.directMethod();
    }
}
class Boss implements Callable
{
    public Boss()
    {
        // Boss creates a worker object, and tells it to do some work.
        Worker w1 = new Worker();
        // Notice, we're passing a reference of the boss to the worker.
        w1.doSomeWork(this);
    }
    public void callBackMethod()
    {
        System.out.println("What do you want?");
    }
    public void directMethod()
    {
        System.out.println("I'm out for coffee.");
    }
}
public class CallBack
{
    // Main driver.
    public static void main(String[] args)
    {
        Boss b = new Boss();
        b.directMethod();
    }
}

CallBack Using Inner Class in Java ?



Create interface seperately Incrementable .java


interface Incrementable {
  void increment();
}


Also create Callbacks.java
// Very simple to just implement the interface:

class Callee1 implements Incrementable {
  private int i = 0;

  public void increment() {
    i++;
    System.out.println(i);
  }
}

class MyIncrement {
  void increment() {
    System.out.println("Other operation");
  }

  static void f(MyIncrement mi) {
    mi.increment();
  }
}

// If your class must implement increment() in
// some other way, you must use an inner class:

class Callee2 extends MyIncrement {
  private int i = 0;

  private void incr() {
    i++;
    System.out.println(i);
  }

  private class Closure implements Incrementable {
    public void increment() {
      incr();
    }
  }

  Incrementable getCallbackReference() {
    return new Closure();
  }
}

class Caller {
  private Incrementable callbackReference;

  Caller(Incrementable cbh) {
    callbackReference = cbh;
  }

  void go() {
    callbackReference.increment();
  }
}

public class Callbacks {

  public static void main(String[] args) {
    Callee1 c1 = new Callee1();
    Callee2 c2 = new Callee2();
    MyIncrement.f(c2);
    Caller caller1 = new Caller(c1);
    Caller caller2 = new Caller(c2.getCallbackReference());
    caller1.go();
    caller1.go();
    caller2.go();
    caller2.go();
  }
}

Output :


Other operation
1
2
1
2

String Versus StringBuffer ?


An understanding of the difference between Java Strings and StringBuffers can lead to great performance increases. Although it may seem not to be the case given Java's String concatenation syntax (like a=a+"hi"), Strings are in actuality read-only (ie, immutable) after they are created so that they cannot change. As a result of this, when you concatenate Strings via the + operator, in the background a temporary StringBuffer gets created and the toString method is called on the StringBuffer to create the new String, and this operation is fairly time-consuming.
However, much less overhead is required to concatenate a String onto a StringBuffer object via the StringBuffer append method. You can basically think of each append as adding another String piece into a linked list that makes up the StringBuffer. So you basically have a StringBuffer consisting of a String chunk which then points to another String chunk which points to another String chunk, etc...
The benefits of StringBuffer become clear when you have a situation involving many concatenations. To illustrate this, let's try concatenating 10,000 "a" Strings together via the String + operator and via a StringBuffer append method and monitor the time required to perform these operations. The StringVersusStringBuffer class below illustrates this.
package test;

public class StringVersusStringBuffer {
         public static void main(String[] args) {
                 try {
                          final int NUM_REPEATS = 10000;
                          String string = "";
                          long start = System.currentTimeMillis();
                          for (int i = 0; i < NUM_REPEATS; i++) {
                                   string = string + "a";
                          }
                          long end = System.currentTimeMillis();
                          System.out.println("String loop time (ms): " + (end - start));

                          StringBuffer sb = new StringBuffer();
                          start = System.currentTimeMillis();
                          for (int i = 0; i < NUM_REPEATS; i++) {
                                   sb.append("a");
                          }
                          end = System.currentTimeMillis();
                          System.out.println("StringBuffer loop time (ms): " + (end - start));
                 } catch (Exception e) {
                          e.printStackTrace();
                 }
         }
}

OutPut :
String loop time (ms) : 156
StringBuffer loop time (ms) : 0

Monday, March 5, 2012

How do I load properties from XML file in android?


Reading XML properties can be easily done using the Properties.loadFromXML() method. Just like reading the properties from a file that contains a key=value pairs, the XML file will also contains a key and value wrapped in the following XML format.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
  <comment>Application Configuration</comment>
  <entry key="data.folder">D:\App\Data</entry>
  <entry key="jdbc.url">jdbc:mysql://localhost/mydb</entry>
</properties>

import java.io.FileInputStream;
import java.util.Properties;

public class LoadXmlProperties {
    public static void main(String[] args) {
        LoadXmlProperties lxp = new LoadXmlProperties();
        try {
            Properties properties = lxp.readProperties();
            /*
             * Display all properties information
             */
            properties.list(System.out);

            /*
             * Read the value of data.folder and jdbc.url configuration
             */
            String dataFolder = properties.getProperty("data.folder");
            System.out.println("dataFolder = " + dataFolder);
            String jdbcUrl = properties.getProperty("jdbc.url");
            System.out.println("jdbcUrl = " + jdbcUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Properties readProperties() throws Exception {
        Properties properties = new Properties();
        FileInputStream fis = new FileInputStream("configuration.xml");
        properties.loadFromXML(fis);

        return properties;
    }
}





Tuesday, February 21, 2012

How to Disabe a button on an appwidget?


As far as I know it can not be done, since the appwiget UI manipulation is limited by the methods of the RemoteViews class.
But if you insist to do that there is a way to make it look like the button were disabled!
RemoteViews can't manipulate a buttons enabled/disabled state, but it can modify its visibility. So the trick is to have two buttons, the real one, and an other which is designed to look like the real one in disabled state, and change witch one is visible.
Lets see a simple example:
We want to have two buttons on the widget, a stop and a start button in order to stop and start some kind of functionality. Once we have started it, we can not start it agin, until we stopped it and vica versa, so we want to disable the button which can not be used right now.
The XML definition of the buttons can be like this:
<Button android:id="@+id/startbutton" android:text="Start" android:visibility="visible"></Button>
<Button android:id="@+id/startbutton_disabled" android:text="Start" android:clickable="false" 
android:textColor="#999999" android:visibility="gone"></Button>
 
<Button android:id="@+id/stopbutton" android:text="Stop"  android:visibility="gone"></Button>
<Button android:id="@+id/stopbutton_disabled" android:text="Stop" 
android:clickable="false" android:textColor="#999999" android:visibility="visible"></Button>


The code that runs when clicked on the start button will contain someting like this:
RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.widget);
remoteView.setViewVisibility(R.id.startbutton, View.GONE);
remoteView.setViewVisibility(R.id.startbutton_disabled, View.VISIBLE);
remoteView.setViewVisibility(R.id.stopbutton, View.VISIBLE);
remoteView.setViewVisibility(R.id.stopbutton_disabled, View.GONE);
AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, remoteView);


And the same for the stop button:
RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.widget);
remoteView.setViewVisibility(R.id.startbutton, View.VISIBLE);
remoteView.setViewVisibility(R.id.startbutton_disabled, View.GONE);
remoteView.setViewVisibility(R.id.stopbutton, View.GONE);
remoteView.setViewVisibility(R.id.stopbutton_disabled, View.VISIBLE);
AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, remoteView);