Monday, December 3, 2012

Please help Anvi fifteen months old

Hi All,

This post is to support the cause of  treatment of Anvi. She is fifteen months old from Mumbai and she needs a life saving bone marrow transplant operation. Please read more about her here:

Please spread the word more and more to support her treatment. You could be a part of saving the life of this fifteen month child.

http://www.ndtv.com/article/cities/mumbai-couple-struggle-to-save-their-daughter-here-s-how-you-can-help-300360?fb

Saturday, November 24, 2012

Calling system applications in Android

In my previous posts I have used reading contacts through API calls, however there is an easy method for doing standard tasks by calling system's pre installed apps. In this post I am going to cover the details of how we can call the system apps through intents.


We are going to create a spinner control for providing the user some options and hit a submit button.

Here's main.xml which defines the UI.

 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
        android:orientation="vertical"  
        android:layout_width="fill_parent"  
        android:layout_height="fill_parent"  
     >  
   <Spinner  
       android:id="@+id/spinner1"  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       android:entries="@array/application_array"  
       android:prompt="@string/app_prompt" />  
   <Button  
       android:id="@+id/btnSubmit"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:text="Submit"  
       android:onClick="btnSubmitOnClick"/>  
 </LinearLayout>  


Spinner control requires a string array (application_array) for it's entries which is defined in strings.xml.

 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
   <string name="app_name">callingsystemapps</string>  
   <string name="app_prompt">Choose a application</string>  
   <string-array name="application_array">  
     <item>Browser</item>  
     <item>Dialler</item>  
     <item>Map</item>  
     <item>Contacts</item>  
   </string-array>  
 </resources>  


In main.xml we have also have defined onClick method btnSubmitOnClick which is defined in MyActivity.java

   public void btnSubmitOnClick (View v)  
   {  
     Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);  
     if (spinner1.getSelectedItem().toString().equals("Browser")){  
       Intent i = new  
           Intent(android.content.Intent.ACTION_VIEW,  
           Uri.parse("http://www.google.com"));  
       startActivity(i);  
     }  
     else if (spinner1.getSelectedItem().toString().equals("Dialler")){  
       Intent i = new  
           Intent(android.content.Intent.ACTION_DIAL);  
       startActivity(i);  
     }  
     else if (spinner1.getSelectedItem().toString().equals("Map")) {  
         Intent i = new  
             Intent(android.content.Intent.ACTION_VIEW,  
             Uri.parse("geo:37.827500,-122.481670"));  
         startActivity(i);  
     }  
     else if (spinner1.getSelectedItem().toString().equals("Contacts")) {  
       Intent i = new  
           Intent(android.content.Intent.ACTION_PICK);  
       i.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);  
       startActivity(i);  
     }  


Only difference between the four is the passing intent which is as below:

ACTION_VIEW
ACTION_DIAL
ACTION_PICK


Along with that we are passing parameters depending upon intent type. After that it's just calling startActivity on the intent.

Try running the example and you shall get like this.




Thanks for reading, don't forget to check links page for resources.

Wednesday, November 21, 2012

getActionBar and targetSdkVersion in Android development

Hi All,

Recently I was trying to reiterate Android docs training just to fill in anything I missed previously. There I came across this piece of code:

     // Initialize member TextView so we can manipulate it later  
     mTextView = (TextView) findViewById(R.id.edit_message);  
     // Make sure we're running on Honeycomb or higher to use ActionBar APIs  
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {  
       // For the main activity, make sure the app icon in the action bar  
       // does not behave as a button  
       ActionBar actionBar = getActionBar();  
       actionBar.setHomeButtonEnabled(false);  
     }  


I tried to put that in a simple hello world example and it worked on an 2.2 emulator, however it failed to run on 4.0 emulator. On debugging it turned out that getActionBar was returning null value. Though there was on-line help available for some other directions it just came to my mind to check AndroidManifest.xml file. There I saw only "android:minSdkVersion="8"" I remembered that there was a target SDK  as well which can be defined. So I checked a project created by eclipse and found the "android:targetSdkVersion="15"" line and added it to "uses-sdk " tag in AndroidManifest.xml and the app started working on 4.0 emulator.

This clears two things, first is that Idea IDE adds only minSDKVersion while eclipse adds targetSDKVersion as well. Which is reflected in new project also but could effect like this.

Second, if you search for getActionBar returning null you get loads of advice but maybe not this. So check if you are having this issue.

Thanks for reading. Thanks for Android guys for creating such a good documentation, which by and large so much better than Facebook developer docs. Only wish Facebook docs were also as clear as the Android docs.

Tuesday, November 20, 2012

Quick tips for improving Java apps performance

"Ever had performance problems? Yeah me too. If my manager screams
“faaaaster” one more time, i will have hearing impairment for the rest
of my life. BTW, did i sense a German pronunciation in all that noise?"

http://www.javacodegeeks.com/2011/09/quick-tips-for-improving-java-apps.html

Sunday, November 18, 2012

Nexus 4 unboxing and first impressions

Google’s newest flagship handset, the LG Nexus, 4 is finally upon us. The highly anticipated stock Android smartphone features some of the highest-end specs of any phone currently on the market, but does it manage to satisfy? Stay tuned for a complete review. However, in the meantime, be sure to catch our unboxing and first impressions below.

http://supertechblog.com/2012/11/17/nexus-4-unboxing-and-first-impressions/

Saturday, November 17, 2012

Capture the output of var_dump in a string


Introduction

You are programming in PHP and you have an array variable that you’d like to explore at different execution paths. Of course, the best way is to use a PHP debugger like xdebug or Zend Debugger, but, what happens when you’re too lazy to install a debugger? What happens when you don’t want or can’t install a debugger and you just need to check the content of that array by dumping it in your log file? Well, you might think you’re stuck, but, read on…

Thursday, November 8, 2012

How to change look & feel of NetBeans IDE and application

Standard GUI toolkit of Java is Swing. NetBeans IDE and Platform is written in Swing. It's widely used and accepted. It's cross-platform and it's doesn't look very well under (GTK+) Linux.

Read more here:

http://devblog.virtage.com/2011/09/how-to-change-look-feel-of-netbeans-ide-and-application/

Debugging php locally with Zend debugger

My tryst with Facebook app development is taking me to rather not ventured areas of computing.

Latest is debugging php code locally, kindly browse my previous posts to see how to deploy LAMP and create virtual hosts etc.


I was on the lookout of seeing which debugger will suit most on Linux Mint. I found that Zend has a debugger which could be blended with your existing server stack. So I researched and setted it up.

Here is how I did it.


Download the Zend debugger from Zend website here. Select the "Studio Web Debugger" and follow the instructions.

Zend forums has excellent step by step guide on installing the debugger. It can be found here.

Once you have completed the instructions restart your web server.

Now check your error log "/var/log/apache2/error.log", if it has error like following:


"Failed loading /etc/apache2/ZendDebugger.so:  libssl.so.0.9.8: cannot open shared object file: No such file or directory"

install libssl0.9.8 using synaptic.


After that I installed PDT for eclipse and tested the debugger connection in "Debug Cnfigurations..." in Run menu. But the connection failed after searching a bit I found that default port for Zend debugger is 10137, which I changed in eclipse.


Now I am able to debug php in eclipse.

Hope you find this useful, thanks for reading, thanks again to guys for creating such useful software's.


Wednesday, November 7, 2012

Deploying a facebook php app locally on Linux

As in my previous post I said that currently I am having a tryst with Facebook apps. Going further I thought of setting up a local environment where I could make changes locally and see them without uploading on heroku website. I find lots of issues which finally got resolved thanks to generous guys on internet. Following their path I am sharing the complete list of instructions I followed to deploy the Facebook app locally here.

First of all you need to create an app on facebook and host it on heroku website following instructions from following link.

https://devcenter.heroku.com/articles/facebook


Please bear in mind that I chose to deploy the main app locally rather than creating a dev app.

If you find any problem related to ssh keys these commands may help you as they did for me.

 # ssh -vT git@heroku.com  


Above command checks whether a secure connections with heroku site is possible or not. If you get any errors try generating a ssh key and submitting it to heroku.

 # ssh-keygen  
 # heroku keys:add ~/.ssh/id_rsa.pub  


Follow my previous post to create virtual hosts, also don't forget to set facebook app id and app secret in "/etc/apache2/conf/extra/httpd-vhosts.conf" file under VirtualHost tag as below. You can these two from Facebook app site.

 <VirtualHost *:80>  
   DocumentRoot /home/ashish/savefromiad/xxxxxxxxxxxx  
   ServerName mycoolapp-dev.localhost  
   SetEnv FACEBOOK_APP_ID xxxxxxxxxxxxxxxxxx  
   SetEnv FACEBOOK_SECRET xxxxxxxxxxxxxxxxxxxxxxxxxxxxx  
 </VirtualHost  


When I tried accessing the virtual site I got a blank page. I tried searching on internet and got this error in apache error.log at "/var/log/apache2/error.log".

 PHP Warning: require_once(sdk/src/facebook.php): failed to open stream: No such file or directory  


When checked the app directory I found that the php sdk was missing so I got that from their git repository.


and copied that under src/sdk of my app local directory.


Still I kept getting permission error so I changed the owner of the directory to www-data as below.

 # chown -R www-data .  


So the permission error vanished, please bear in mind that may have further repercussions but for now things worked for me. I got this help while setting up Joomla! locally so applied this here as well.

But the errors kept coming, this time like this one.

 Uncaught exception 'Exception' with message 'Facebook needs the CURL PHP extension.  


So checked the php manual and from user notes installed curl and php extension as below.

 # sudo apt-get install curl libcurl3 libcurl3-dev php5-curl  


Even after this it didn't worked so I restarted my laptop and lo!!! it worked.

Update:
Later I noticed that this local running is not same as on heroku.Will see how to resolve and add.
Update 2:
In the mean time you could try heroku eclipse plugin http://eclipse-plugin.herokuapp.com. It greatly eases the change, commit, and test phases. Off course you would be running your actual master code

Thanks for reading and thanks to guys for helping me out. Please don't forget to share if you find this helpful.

Tuesday, November 6, 2012

Creating virtual hosts in apache2

Recently I was trying to create a facebook app and thought of creating virtual hosts on my machine where I possibly could test it. Here is the steps I took to create two virtual hosts on my Linux Mint.


First install LAMP stack if you don't have it already

 sudo apt-get install lamp-server^ -y  

(Don't forget the caret '^')


Now define the following in "/etc/apache2/conf/extra/httpd-vhosts.conf" file


 NameVirtualHost *:80  

If the above mentioned file does not exist create it.

Also make sure that "/etc/apache2/httpd.conf" has this line

 Include conf/extra/httpd-vhosts.confconf  

NameVirtualHost needs to be all conf files only once so make sure that "/etc/apache2/ports.conf" has got it commented out.

 #NameVirtualHost *:80  

Now create the definition of virtual hosts like below.

 NameVirtualHost *:80  
 <VirtualHost *:80>  
    DocumentRoot "/var/www"  
    ServerName localhost  
  </VirtualHost>  
 <VirtualHost *:80>  
   DocumentRoot "/var/www/mysite"  
   ServerName mysite.localhost  
 </VirtualHost>  

One also need to create the entry in "/etc/hosts" like this.

 127.0.0.1    localhost  
 127.0.0.1    mysite.localhost  

Now you should be able to test your sites.

Thanks for reading and much credit goes to guys on internet for helping out specially on stackoverflow.com.


Sunday, November 4, 2012

Most useful wordpress plugins for any website

Recently I've been into foray of creating websites. Though I liked joomla for saving time I decided upon wordpress. In a couple of weeks I have come across many plugins which are very useful for any wordpress site hence am sharing them here. Please keep in mind though tht it depends on your hosting site whether you would be able to take full benefit of these plugins.

1. Akismet

Fighting spam for you and free for personal use. It needs and API key which is easy to create and deploy into your site.


2. BackUpWordPress

Regularly backups your website so you free of worry about your site corruption.


3. bbPress

Very easy to create forums which looks native to your website.


4. Better WP Security

Tightens your website security though depends on your website hosting company not all options are enforcing.


5. CloudFlare

Free CDN for your site again your website hosting site support is needed to enable it.


6. Disqus Comment System

Professional looking commenting system for your site, has community and some other nice feature as well.


7. Facebook

Needless to say anything about this.


8. Google Analytics

Helps adding Google Analytics to your site in easy way.


9. Google XML Sitemaps

Generate site maps which are easy to be submitted in Google webmaster and bing.


10. Gravatar Favicon

An avataar system to be used for any site integrating nicely into wordpress.


11. gtrans

Makes it super easy to make your site translated on the fly to cater to a larger audience.

12. Jetpack by WordPress.com

Many useful options such as site stats, mobile themes, wordpress.com integration etc. Very useful.


13. Newsletter

As the name says handy newsletter creation.


14. PayPal Donations

Easy to use donation plugin to get support for your siite.


15. Scripts Gzip

Compress your scripts to fasten your website.


16. Sociable

Adds lots of social networking site sharing to your posts.


17. Ultimate TinyMCE

Ultimate editor to create posts if not wrong used by wordpress.com as well.


18. W3 Total Cache

Lot of caching options to make your website faster. Again depends on your website.


19. Wordfence Security

Integrates antivirus and firewall in your website.


20. WordPress Gzip Compression

Enable gzip compression to make your website load faster.


21. WordPress Importer

Import your posts from other worpress site.


22. WordPress Ping Optimizer

Save your site from being tagged as ping spammer.


23. WordPress SEO

Search engine optimization tools tightly integrated into your site.


24. WP-o-Matic

Automated posting into your website.


25. WP-Optimize

Optimize your database.


26. WP-PageNavi

A better menu navigation system.


27. WP Code Highlight

Highlight your code snippets into colorful coding.


28. WP Smush.it

High images are bottleneck into site performance make it faster with this plugin.


29. WPtouch

Make your website ready for touch screen based devices like iPhone etc.


30. Yet Another Related Posts Plugin

Automatically creates related posts entries for your posts.

31. BAW Post Views Count

Adds how many times a post has been viewed.


I've given very short intros of these plugins however you can click on links and see the details.

Please do not forget to share if you liked this.

Thanks

Wednesday, October 31, 2012

Auto blogging in wordpress

Recently I was trying to set up auto posting for my website Android Beginner Developer Help. After doing some research this is how I did it.

First install wp-o-matic from your wordpress site dashboard.



After installation it will come up in settings.

Select add new campaign, you will need a feed URL to insert into it. Add name and save it.



Submit it and if feed URL is OK it will create a new campaign.

Now go to options and see the cron URL.



Rest all you need is to go to site like setcronjob.com and set a online cron job using the URL.



See my website Android Beginner Developer Help to see wp-o-matic in action.

Thursday, October 25, 2012

Accessing contacts and sending SMS in an Android app

Re-posting : An outrageously simple note taking android app made further better (part 5)


In this post we will cover sending SMS through Android App and also how to read contacts.

I apologize for the gap in coming up with this post. I can only work as much as my health permits, which sometimes not very long. :)

The very first thing an Android app needs is to register for permission to send SMS and read contacts. This can be done by putting these lines into AndroidManifest.xml.




We will add a new menu item in context menu like below.

    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        currentNote = ((TextView)v).getText().toString();
        // Create your context menu here
        menu.setHeaderTitle("Context Menu");
        menu.add(0, v.getId(), 0, "Edit n Replace");
        menu.add(0, v.getId(), 1, "Delete");
        menu.add(0, v.getId(), 2, "Send as SMS");
    }

And we will see somethinglike below.




For handling this menu item we will add a new else section.

    public boolean onContextItemSelected(MenuItem item) {
        // Call your function to preform for buttons pressed in a context menu
        // can use item.getTitle() or similar to find out button pressed
        // item.getItemID() will return the v.getID() that we passed before
        super.onContextItemSelected(item);

        if ( item.getTitle().toString().equals("Delete")){
            NotesDatabase db =new NotesDatabase(this);

            db.searchAndDelete(currentNote);
            onResume();
        }
        else if ( item.getTitle().toString().equals("Edit n Replace")) {
            Intent intent = new Intent(this, EditNoteActivity.class);
            intent.putExtra("ACTION","oldnote");
            intent.putExtra("ACTION2","replace");
            intent.putExtra(EXTRA_MESSAGE,currentNote);
            startActivity(intent);
        }
        else if (item.getTitle().toString().equals("Send as SMS")){
            Intent intent = new Intent(this, SendAsSmsActivity.class);
            intent.putExtra("SMS", currentNote);
            startActivity(intent);
        }


        return true;
    }

In the newly added code we are creating a new Activity SendAsSmsActivity and passing the note as SMS in intent.

Here is SendAsSmsActivity.xml which is defined as below.



              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical">
            android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number"
        android:hint="Enter number here..."
        android:gravity="top|left">
       
   
                android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="text"
            android:hint="Enter note here..."
            android:gravity="top|left" >

   

                      android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:orientation="horizontal"
                  android:weightSum="2">
       
                 android:id="@+id/buttonSendSMS"

                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:onClick="onClickSend"

                android:text="Send" />
                        android:id="@+id/button2"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:onClick="onClickCancel"

                android:text="Cancel" />
 

It will come up like this



Here we are using nested LinearLayout with nested wights assigned to buttons as well as second edit text, which though is not a good practise; but for our small app workes fine.

Below is SendAsSmsActivity.java

public class SendAsSmsActivity extends Activity {
    String sms = new String();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sendassmsactivity);
        Intent intent = getIntent();
        EditText text = (EditText) findViewById(R.id.editText2);
        Bundle extras = intent.getExtras();
        sms = extras.getString("SMS");
        text.setText(sms);
        EditText text1 = (EditText) findViewById(R.id.editText1);
        registerForContextMenu (text1);
    }
    public void onClickSend ( View button){
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this,0,new Intent(SENT),0);
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this,0,new Intent(DELIVERED),0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(DELIVERED));

        SmsManager smsManager = SmsManager.getDefault();

        EditText text1 = (EditText) findViewById(R.id.editText1);
        Log.v("phoneNumber", text1.getText().toString());
        Log.v("MEssage",sms);
        smsManager.sendTextMessage(text1.getText().toString(), null, sms, sentPI, deliveredPI);
        finish();
    }
    public void onClickCancel( View button){
        finish();
    }
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        //currentNote = ((TextView)v).getText().toString();
        // Create your context menu here
        // Clear current contents
        menu.clearHeader();
        menu.clear();

        menu.setHeaderTitle("Context Menu");
        menu.add(0, v.getId(), 0, "Contacts");
    }
    public boolean onContextItemSelected(MenuItem item) {
        // Call your function to preform for buttons pressed in a context menu
        // can use item.getTitle() or similar to find out button pressed
        // item.getItemID() will return the v.getID() that we passed before
        super.onContextItemSelected(item);

        if ( item.getTitle().toString().equals("Contacts")){
            Intent intent = new Intent(this,readAllActivity.class);
            startActivityForResult( intent, 0);
        }
        return true;
    }

}


Kindly go through my previous post if you are not familier with above code.

We are here in onCreate method; setting the view by setContentView, getting the intent by getIntent, getting the note by getExtras and getString and assigning to second edit text. We are also registering the first edit text for a context menu.

onClickSend is the method registered for "Send" button. Here is the actual code for sending SMS  Here we are creating PendingIntent which are a kind of callback mechanism in which we specifies the action need to be performed at a certain event later in lifecycle of application.

registerReceiver defines the method which needs to be performed in the case of event (SMS sent). It has two parameters one is BroadcastReceiver which actually holds the methods needs to be performed. When the onReceive overridden method is called it raises a Toast ( small info window) based on  the return value of getResultCode which tells whether the action was prformed well.

Second parameter is a IntentFilter object.

Here's the toast :)



After that SmsManager.getDefault returns a sms manager object, which actually send the sms and also registers the PendingIntents.

Overriding onCreateContextMenu definesthe context menu which we have registered for text1 in onCreate. "Contacts" is the only menu item here.



In onContextItemSelected when we find this selected we start a new activity readAllActivity.

Here is readAllActivity.java

public class readAllActivity extends Activity {


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        readContacts();
    }
    public void readContacts (){
        LinearLayout lLayout = (LinearLayout)findViewById(R.id.layout1);
        final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
        while (cursor.moveToNext()) {
            String contactId = cursor.getString(cursor.getColumnIndex(
                    ContactsContract.Contacts._ID));
                Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
                while (phones.moveToNext()) {
                    String name = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    TextView b2 = (TextView) inflater.inflate(R.layout.textviews,null);
                    b2.setTextColor(Color.BLACK) ;
                    b2.setText(name);
                    registerForContextMenu(b2);
                    lLayout.addView(b2);

                    String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
                    TextView b = (TextView) inflater.inflate(R.layout.textviews,null);
                    b.setTextColor(Color.BLACK) ;
                    b.setText(phoneNumber);
                    registerForContextMenu(b);
                    lLayout.addView(b);

                }
                phones.close();
        }
        cursor.close();
    }
}

getContentResolve returns all the contacts in a cursor "phones", which we scrolls through and populates edit texts.

Till now all is fine except how do we return the selected phone number.

We have used startActivityForResult instead of startActivity in onContextItemSelected of SendAsSmsActivity.java file.

In readAllActivity.java we will add this method to set returning data

     public void onClickTextView1(View v) {
        Intent resultData = new Intent();
        String s =((TextView)v).getText().toString();
        resultData.putExtra("number", s);
        setResult(Activity.RESULT_OK, resultData);
        finish();
    }
Aaaaand we shall have our number in first EditText.

Thanks to Wei-Meng Lee for his "Beginning Android Application Development" for sms code and stackoverflow.com for rest of help.

Saturday, October 20, 2012

changing splash screen in ubuntu

Unlike my previous post if you  want to change the splash screen you can do so with plymouth-manager.

Download it from here and install it with gdebi package manager.

Run it from command line as "plymouth-manager".



Click on "Themes" and install any theme.







Now choose from the available list



Reboot and watch newly installed theme.

Share it if you liked it.

Removing home directory contents from your desktop

Recently I was trying to install xfce 4.10 on my Ubuntu 12.04 OS but found my desktop filled with my home directory contents.

This is what I do to remove the contents.

Open "~/.config/users-dirs.dirs" file and chnage line with XDG_DESKTOP_DIR as "XDG_DESKTOP_DIR="$HOME/Desktop"", and log out and come back ( alternatively restart).

And you shall have only desktop icons on your desktop.


Friday, October 19, 2012

Removing splash screen from your Ubuntu

Many a times one may want to get completely rid of boot splash screen. Here's what one needs to do to get it.

Edit grub defaults file with "sudo vi /etc/default/grub" and change "splash" to "nosplash"



Update grub with "sudo update-grub"" and it shall generate boot menus with new option.


Sunday, October 14, 2012

Saturday, October 13, 2012

New website for Android developer help

Hi All

After facing a lot of issues on Android help forums, I decided to create a new one where no one is discouraged to ask question no matter how simple is that.

I pledge all people interested in learning Android programming and pros who like to help together on this site.

Please spread the word and join to create a new free and open community.

http://android-beginner-developer-help.webs.com

Sunday, October 7, 2012

Moving to wordpress

Too many issues in blogger , moving to wordpress now.

http://ashishkyadav.wordpress.com/

Inconvenience is highly regretted, but please blame it to blogger.

An outrageously simple note taking android app made better (part 2)

OK blogger is so adamant to not update my post in better format so moved to wordpress.

Sorry folks one more link to follow.

http://ashishkyadav.wordpress.com/2012/10/07/4/

Saturday, October 6, 2012

An outrageously simple note taking android app (part 1)

Hi all, in this post we will create a very basic note taking app. It will store only single note and retrieve it back. In later post we will keep extending it until it become a fully working app. So bear with it as the attempt  is to learn android programming not anything else.

Instructions here are being done with IntelliJ IDEA IDE.But they shall be convertible for any IDE,or command line.

First off course create a blank project.





This newly created project already has one activity MyActivity Consider this as window in a desktop app as this has also got screen area and can have button, text, etc.

Activities in android are usually tied with an XML file where the UI is designed, in this case main.xml. Open it to design the first Activity(window) of this app.


Change the XML to remove the TextView and have a button instead.


<Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/AddNote"
            android:onClick="addNote"/>


This button property width as "fill_parent" which will specify that it spans the whole width of Activity, height as "wrap_content" which specify that its height will only be accommodate its label. text property sets the label of the button, which is string to be defined in strings.xml under "values" as following.

<string name="AddNote">+ Add a new note</string>

onClick defines the function which will be called when the button is pressed and wiil be defined in "MyActivity.java" file.

At this point of time UI will look like this in IntelliJ IDEA.


Here you can experiment with different device and android profiles to preview how well it will look like.

The onClick function addNote will be defined as this.


public void addNote ( View theButton) {
        Intent intent = new Intent(this, EditNoteActivity.class);
        startActivity(intent);
    }

This function does only two things, first create an intent which is like a message passing to the new Activity(window) and start new Activity EditeNoteActivity which we will shortly define.


Now create a new activity EditNoteActivity by right clicking on src--com.example -> New -> Android Component


Now we need to create a resource xml file, right click on layout directory in project view and select New->Layout resource file.



This is an empty layout file we need an edit text here, and a hew buttons. So here they are, first EditText.


<EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="text"
            android:hint="Enter note here..."
            android:gravity="top|left" >

        <requestFocus />
    </EditText

id uniquely identifies the field in your java code. setting the height to 0dp and weight set the field to take up screen space to its fullest. inputType specifies the default type of input like text, number etc. hint specifies the subtle non editable text to be displayed in EditText which will disappear when the user enters text. Rest of the fields can be looked up in API reference of Google site.

Set the orientation of layout to be vertical
android:orientation="vertical"

Here we have chosen LinearLayout which is more feasible for this app. There are different types of layout which can be seen on Google reference.

Now create two buttons as below


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="2">
    <Button
            android:id="@+id/button1"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:onClick="onClickSave"

            android:text="Save" />
    <Button
            android:id="@+id/button1"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:onClick="onClickBack"

            android:text="Back" />
    </LinearLayout>

Here the orientation of layout is horizontal so that buttons are sideways aligned. weightSum is 2 so that buttons are equally spaced in all type of screens. Rest of the fields are self explanatory I guess by now.

At this point the whole xml file is like this

http://snipt.org/vWP3



Now open your EditNoteActivity.java file and add onclickSave method to look like this


    public void onClickSave(View theButton) {
        String FILENAME = "note_file";

        EditText text = (EditText) findViewById(R.id.editText1);


        FileOutputStream fos = null;
        try {
            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        assert fos != null;
        try {
            String str = new String (text.getText().toString());
            fos.write(str.getBytes());
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        finish();
    }

Here you get the handle of the button1by findViewById and passing the resourse ID. openFileOutput opens up the file on internal memory exclusively for this app as specified by MODE_PRIVATE. You take the text out of the field by getText and convert it to bytes by getBytes method before saving it to file and close it.


Now make your onCreate method to look like this


public void onCreate(Bundle savedInstanceState) {
        String FILENAME = "note_file";
        byte[] buffer = new byte[100];

        super.onCreate(savedInstanceState);
        setContentView(R.layout.editnote);
        EditText text = (EditText) findViewById(R.id.editText1);

        FileInputStream fos = null;
        try {
            fos = openFileInput(FILENAME);
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        if ( fos != null){
        try {
            fos.read(buffer, 0, 10);
            String str = new String(buffer, "UTF8");
            text.setText(str);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        }
    }

This one is self explanatory mostly as it open the file and read the node. Only one worth mentioning is setContentView which takes the editnote.xml defined and create the UI. Remember it to put first before findViewById to avoid crash as this needs to be done first.

Also add onClickBack method


    public void onClickBack(View theButton) {
        finish();
    }
This one only calls finish which returns to the main Activity MyActivity.


Now build and compile and run it on emulator to see how it goes. This is fairly shortcoming app as it saves only one note and retrieves it back, however I am sure this helps in understanding many concepts in android. Especially as if you try this and the go around the reference or books you will find yourself eased out a bit.

Hope this helps and many thanks to guys on http://stackoverflow.com for helping.






Wednesday, October 3, 2012

Android development using IntelliJ part 1

Open source is about choice, they say. So here is one more choice, use IntelliJ IDE for development of android apps.

IntelliJ is a good IDE for Java development by JetBRAINS. It comes in two flavours, free community edition and  paid ultimate edition. Both can be downloaded from here.

I am using free community edition for this tutorial. Which according to site has "Powerful environment for building Google Android apps". Though I will left that for readers to decide.

Update: To install android sdk tools please refer this post.

Installation is pretty straightforward, just unzip it in a convenient location and run idea.sh file from "bin" directory. Select File -> New Project and you shall be welcomed by this dialog box


Click next and you will get this screen


Enter project name, select type as "Android Module", and click next to get following screen.


Click next with settings remains intact.


In above screen select the emulator device, one thing which surprised me was that there was no option to select build target. I manually changed that to Android API level 8 ( Android 2.2) in AndrodManifest.xml (android:minSdkVersion="8").


Just click on run and you will have your app running in emulator.


Update 2: One difference I noticed between eclipse and IntelliJ is that running app from eclipse twice runs a new instance of emulator, while IntelliJ does the , well intelligent thing to connect to the already running emulator and initiate the app within. Probably those who are well versed with eclipse will be able to tell the peculiar behavior of eclipse.


Comparing to my previous jEdit tutorial, this was short and easy. Well that's what a IDE is supposed to be, but in my personal opinion one know about the internal working more if one uses a simple editor and command line. However if you are short of time, using IDE will save you lots of time.


In forthcoming parts I will try to give examples of creating android apps step by step. Consider this a group study rather than a conventional classroom teaching as I myself is learning android programming.

All suggestions of improvement are welcome. Thanks for reading.