Saturday, July 28, 2012

Filling a ListView from a Cursor

check this out first :

now this works in the same way, it just picks up the data from a cursor as :

 String[] fromColumns={ContactsContract.Data.DISPLAY_NAME_PRIMARY};
        int[] toViews={R.id.name_entry};
     
        Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, null, null, null);
        //cursor.moveToFirst();
     
     
        SimpleCursorAdapter adapter=new SimpleCursorAdapter(this, R.layout.activity_cursoradapter, cursor, fromColumns, toViews,0);
        ListView listview=getListView();
       listview.setAdapter(adapter);
     
      // this.setListAdapter(adapter);

do not forget to add the permission in the manifest :

    <uses-permission android:name="android.permission.READ_CONTACTS" />


Additionaly, you may also implement click event for each item click :

 final OnItemClickListener mMessageClickedHandler = new OnItemClickListener(){
      @Override
      public void onItemClick(AdapterView parent, View v, int position, long id) {
      // TODO Auto-generated method stub
                  Toast.makeText(getApplicationContext(), position +" clicked", Toast.LENGTH_SHORT).show();
      }
           
             };
             listview.setOnItemClickListener(mMessageClickedHandler);
         
       }

Creating a ListView populated with array.




First of all, create a Button which starts a new activity(a list view) and write following code on the click event of the button.

  Intent intent=new Intent(this, adapter_activity.class);
    startActivity(intent);

   
in the class adapter_activity write down :


package com.example.listviewadapter;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.View;
public class adapter_activity extends ListActivity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_adapter);
       
       String[] myStringArray={"Helllo","Wow","Its fun","blah","blah","blah"};
       
       setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myStringArray));
    }
   
   
}

and in layout.xml 

 <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:drawSelectorOnTop="false"
        android:choiceMode="multipleChoice" >
    </ListView>
   
     <TextView
        android:id="@+id/selection"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff0000cc"
        android:textStyle="bold"/>


do not forget to add the activity in the manifest

Saturday, July 21, 2012

Starting activity for a result(Pick contact name and display it in your activity)

On button click ::

Intent intent=new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
    startActivityForResult(intent,PICK_CONTACT_REQUEST);

and create a method which runs on returning the contact name::
 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // If the request went well (OK) and the request was PICK_CONTACT_REQUEST
        if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {
            // Perform a query to the contact's content provider for the contact's name
            Cursor cursor = getContentResolver().query(data.getData(),
            new String[] {Contacts.DISPLAY_NAME}, null, null, null);
            if (cursor.moveToFirst()) { // True if the cursor is not empty
                int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME_PRIMARY);
                String name = cursor.getString(columnIndex);
               
                // Do something with the selected contact's name...
                EditText edittext=(EditText)findViewById(R.id.editText1);
                edittext.setText(name);
            }
           
        } 

Do not forget to add the permission in the manifest::
 <uses-permission android:name="android.permission.READ_CONTACTS"/> 

Creating Activity

Activities are application components that provides a screen to which a user may respond. Its similar to a form in windows programming.

Create a new layout xml file in the layout directory and design the ui as required. Then, add a class with Activity as super class.

In the main activity on the button click method (or anywhere you want), all you need to do is create an Intent and startActivity() as shown ::


public void fun(View view){
    Intent intent=new Intent(this,newactivity.class);
    startActivity(intent);
    }

and in the activity class




public class newactivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.newactivity);
}
}

Now you need to include the activity in the manifest file as ::


<activity
            android:name=".newactivity">
             </activity>



that's it. :)

Thursday, July 19, 2012

Toggle between ringing and silent ringing mode



Source Code :


 AudioManager vAudioManager;
    public void Toggle(View view){
    Button vButton=(Button)findViewById(R.id.button1);
    ImageView vImageView=(ImageView)findViewById(R.id.imageView1);
        vAudioManager=(AudioManager)getSystemService(AUDIO_SERVICE);
    if(vAudioManager.getRingerMode()==vAudioManager.RINGER_MODE_NORMAL){
        vButton.setText("Silent Mode");
    vImageView.setImageDrawable(getResources().getDrawable(R.drawable.phone_silent));
        vAudioManager.setRingerMode(vAudioManager.RINGER_MODE_SILENT);
    }
    else{
    vButton.setText("Ringing Mode");
    vImageView.setImageDrawable(getResources().getDrawable(R.drawable.phone_on));
        vAudioManager.setRingerMode(vAudioManager.RINGER_MODE_NORMAL);
    }
    }

Wednesday, July 18, 2012

TicTacToe

TicTacToe::
UI->>
For the game logic, declare following variables::

 Button button=null;
    String vPlayer="Player1"; //for storing the current player. Switches with every btnClick
    int vRow1=0, vRow2=0, vRow3=0, vCol1=0, vCol2=0, vCol3=0, vDiag1=0, vDiag2=0;
    /*above variables changes for each button click.
     * if button 1 is pressed, vRow1,vCol1,vDiag1 are incremented for player1 else decremented for player 2
     * For player 1 to win, the value of any of the above variable should be +3 and for player 2, it should be -3
     */
    int vClicks=0; //game ends when its value reaches 9

for each button, increment rows, columns and diagonals accordingly..

public void btn11_Click(View view){
    vClicks++;
    button=(Button)view;
    view.setEnabled(false);
        if(vPlayer=="Player1"){
    vRow1++;
    vCol1++;
    vDiag1++;
        vPlayer="Player2";
    button.setText("X");
    }
    else{
    vRow1--;
    vCol1--;
    vDiag1--;
        vPlayer="Player1";
    button.setText("0");
    }
    win_or_lose();     }


and the win_or_lose method:



 public void win_or_lose(){
    EditText editText=new EditText(this);
    int flag=0;
    if(vRow1==3 || vRow2==3 || vRow3==3 || vCol1==3 || vCol2==3 || vCol3==3 || vDiag1==3 || vDiag2==3){
    editText.setText("Player 1 wins");       setContentView(editText);
    flag++;
    }
    else if(vRow1==-3 || vRow2==-3 || vRow3==-3 || vCol1==-3 || vCol2==-3 || vCol3==-3 || vDiag1==-3 || vDiag2==-3){
    editText.setText("Player 2 wins");
    setContentView(editText);
    flag++;
    }
        if(vClicks==9 && flag==0){
    editText.setText("Game Draw");
    setContentView(editText);
    }
    }


a lot of code optimization can definitely be done. Looking forward for your comments on how you would like to optimize the code.

Finding Device Information

For finding information about device like the version, manufacturer, dimension etc. etc.

Android Developer Refrence
Stack Overflow Question

Calculator

Draw the interface as


Add respective onClick events to each button.
And in Main Activity..
    Declare following variables:

    int vFirstNum=0,vSecondNum=0,vResult=0;
    int vTemp=0;
    String vOperation="";
    and then for each digit button click:


 public void btn0_Click(View view){
    EditText editText=(EditText)findViewById(R.id.editText1);
    vTemp=Integer.parseInt(editText.getText().toString());
        if(vTemp==0)
    editText.setText("0");
    else if(vTemp<=999999)
    editText.setText(editText.getText()+"0");
    }

For operation button click:

 public void btnPlus_Click(View view){
    vOperation="Add";
        EditText editText=(EditText)findViewById(R.id.editText1);
    vFirstNum=Integer.parseInt(editText.getText().toString());
        editText.setText("0");
    } 

For Clear Button:

public void btnC_Click(View view){
    EditText editText=(EditText)findViewById(R.id.editText1);
    editText.setText("0");
    }
 

and for the "=" button:

 public void btnResult_Click(View view){
    EditText editText=(EditText)findViewById(R.id.editText1);
    vSecondNum=Integer.parseInt(editText.getText().toString());
        if(vOperation=="Add")
    vResult=vFirstNum+vSecondNum;
        else if(vOperation=="Multiply")
    vResult=vFirstNum*vSecondNum;
        else if(vOperation=="Divide")
    vResult=vFirstNum/vSecondNum;
        else if(vOperation=="Minus")
    vResult=vFirstNum-vSecondNum;
        String vMessage=""+vResult;
    editText.setText(vMessage);
    vFirstNum=0;
    vSecondNum=0;
    vResult=0;
    vOperation="";
    }
 

yeah, that's it and ur handy calculator is ready.

Finding Sum Of Two Numbers

Drag and Drop the Views(Widgets, EditText, Text, Button) as shown :


add
    android:onClick="Calculate_Sum"
tag in the xml view of the interface.



Now, in the MainActivity, create a method Calculate_Sum as:


 public void Calculate_Sum(View view){
    //Taking First Num
    EditText editText=(EditText)findViewById(R.id.editText1);
    String vFirstNum=editText.getText().toString();
    int vNum1=Integer.parseInt(vFirstNum);
    editText=(EditText)findViewById(R.id.editText2);
    String vSecondNum=editText.getText().toString();
    int vNum2=Integer.parseInt(vSecondNum);
 
    int vRes=vNum1+vNum2;
    String message="Sum is"+vRes;
    TextView textView=new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);
 
    setContentView(textView);
    }