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.

Monday, October 1, 2012

Android development using jEdit part 2

In this part of tutorial we will see how to create Android virtual devices, create a project and deploy it.

First of all create an AVD of targetted Android platform.



Select Plugins->A-B->Android->Create AVD and fill in details. One needs to enter AVD Name (Specify identifiable name by which you can guess platform later), Target (platform),  SD Card Size and Skin. If no dialog box comes up check your $PATH variable, that happened with me and I kept wondering until I realize that Android sdk tools directory was missing from path.

If you see this error "Error: This platform has more than one ABI. Please specify one using --abi." in console window (requires console plugin) manually specify ABI as bellow.
android create avd -n avd-jelly-bean -t 11 -c 32M -s WVGA800 --abi x86
Android 4.1 is a basic Android platform.
Do you wish to create a custom hardware profile [no]
Process android exited with code 0
Created AVD 'avd-jelly-bean' based on Android 4.1, Intel Atom (x86) processor,
with the following hardware config:
hw.lcd.density=240
vm.heapSize=48
hw.ramSize=512
 PS. Bye no means this is an Android tutorial, nor I am a pro. To know about ABI etc follow any Android programming tutorial.


Launch the AVD by selecting "Launch AVD"



Depending upon how powerful machine you've got, sooner or later you'll see AVD running.

Now create a android project

Create a project viewer project. This one is for jEdit to track and different from Android project.



Build and deploy this project, and you shall see it in you emulator listed among other apps like this


Update:
If you see an error like "waiting for device" even if the AVD  is running try instructions from here.

This ends the tutorial here, I would like to reiterate that I am not a pro and if you want to learn Android programming in detail here is a link.

Thanks for reading, many thanks goes to Dale Anson for this plugin. See you some time later :).