Sunday, December 23, 2012

Android Layout xml

android:textSize="45dp" (or) "45sp"
    -- Density pixels ( To be consistent across all devices sizes. )


android:orientation="vertical"


android:layout_gravity="center"
-- > Centers the TextView.

to center the text.
--> android:gravity="center"

        android:id="@+id/tvDisplay"
--> setup ID (Id will be created in the R.java file.
display = (TextView) findViewById(R.id.tvDisplay);

when you want to include an image, save the files as *,png
and make sure the filename has lowercase letters & underscores

--> move files into project from explorer and clean and build the workspace in eclipse to see the files.

images to -> drawable-hdpi
audio files to -> raw folder

raw folder in "res" folder.

--> Calling another activity.

Intent startActivity = new Intent("android.intent.action.START_SCREEN");
startActivity(startActivity);

--> android.intent.category.LAUNCHER --> Called when application starts

        <activity android:name="com.ganta.learningandroid.Splash" android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>




    @Override
    protected void onPause() {
        super.onPause();
        finish(); // This is activity is killed. (Removed from history in navigation)
    }


SoundPool -->
short audio, gunshots,
bird sounds etc

MediaPlayer -->
all other purposes, 

MediaPlayer splashSound = MediaPlayer.create(Splash.this, R.raw.autobots_roll_out);
splashSound.start(); // start playing
splashSound.stop(); // stop playing
splashSound.release(); // song is released.


// dynamically changing the className for Intent.
Class ourClass = Class.forName("com.ganta.learningandroid." + className );
            Intent ourIntent = new Intent(Menu.this,ourClass);
            startActivity(ourIntent);


android:paddingBottom="10dp" // padding is a good idea.

android:weightSum="100"

android:layout_weight="20"
android:layout_weight="80"



<activity android:name="com.ganta.learningandroid.Menu" android:label="@string/app_name" >
  <intent-filter>
      <action android:name="android.intent.action.MENU" />
      <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>
</activity>



This is not required above.
<intent-filter>
    <action android:name="android.intent.action.MENU" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>


passTog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
            }
        });


if(passTog.isChecked()) {
     input.setInputType(InputType.TYPE_CLASS_TEXT | 
                            InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
else {
                    input.setInputType(InputType.TYPE_CLASS_TEXT);
}

public class TextPlay extends Activity implements View.OnClickListener
implement the interface, and use switch and cases if there are multiple buttons.



<ScrollView android:layout_weight="30" android:layout_width="fill_parent"
android:layout_height="fill_parent">
// content goes here.....
</ScrollView>



Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, emailaddress);
        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "I hate you");
        emailIntent.setType("plain/text");
        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
        startActivity(emailIntent);



i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(i, cameraData);
            break;


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if( resultCode == RESULT_OK ) { // For safety
            Bundle extras = data.getExtras();
            bmp = (Bitmap) extras.get("data");
            iv.setImageBitmap(bmp);
        }
    }



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

getApplicationContext().setWallpaper(bmp);


InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
getResources() --> gets the resources in "res" folder (?)

        bmp = BitmapFactory.decodeStream(is); // decode stream to bitmap.




<activity android:name="com.ganta.learningandroid.Camera" android:label="@string/app_name"
            android:screenOrientation="portrait">
        </activity>




String[] tempArray = { "" };

        setContentView(R.layout.***);
        ListView listView = (ListView) findViewById(R.id.***);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, tempArray);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int position, long id) {
                 // code goes here.
           });


Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("new_variable_name");
}



        Intent person = new Intent();
        Bundle backpack = new Bundle();
        backpack.putString("answer", sendData);
        person.putExtras(backpack);
        setResult(RESULT_OK, person);
        finish(); // Finish is required.

--> Send data to the caller



if(resultCode == RESULT_OK) {
            Bundle basket = data.getExtras();
            String answer = basket.getString("answer");
            gotAnswer.setText(answer);
        }
        gotAnswer.setText("Reulst not ok");


--> reading data from called Activity



Working with Menus

@Override
    public boolean onCreateOptionsMenu(android.view.Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater blowUp = getMenuInflater();
        blowUp.inflate(R.menu.cool_menu, menu);
        return true;
    }



@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //super.onOptionsItemSelected(item);
        switch(item.getItemId()) {
        case R.id.aboutUs:
            Intent i = new Intent("android.intent.action.ABOUT");
            startActivity(i);
            break;
        case R.id.preferences:
         
            break;
        }
     
        return false; // why false?
    }



Themes are like popup with transparent background.



<activity android:name="com.ganta.learningandroid.AboutUs" android:label="@string/app_name"
            android:theme="@android:style/Theme.Dialog">
            <intent-filter>
                <action android:name="android.intent.action.ABOUT" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>


-------------------
raw/xml/prefs.xml
-------------------

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <EditTextPreference
        android:key="name"
        android:summary="Enter your Name"
        android:title="EditText" />

    <CheckBoxPreference
        android:defaultValue="true"
        android:key="checkbox"
        android:summary="Check this box"
        android:title="CheckBox" />

    <ListPreference
        android:entries="@array/list"
        android:entryValues="@array/lValues"
        android:key="list"
        android:summary="This is a list to choose from"
        android:title="list" >
    </ListPreference>

</PreferenceScreen>


----------------
values/array.xml
------------

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="list" >
        <item>Option1</item>
        <item>Option2</item>
        <item>Option3</item>
        <item>Option4</item>
    </string-array>

    <string-array name="lValues" >
        <item>1</item>
        <item>2</item>
        <item>3</item>
        <item>4</item>
    </string-array>
 
</resources>

IMP: its not android:name in above string-array


Get the preferences:
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());


When you want to create a new layout for landscape view put the code in the "res/layout-land" folder, with the exact same layout file name, and exactly same reference names.

75x75 is an ok size for images.

drawable-hdpi/custom.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/button_selected" android:state_pressed="true"></item>
    <item android:drawable="@drawable/button_highlighted" android:state_focused="true"></item>
    <item android:drawable="@drawable/button"></item>

</selector>




FULLSCREEN_NO_TITLE -- onCreate() method


requestWindowFeature(Window.FEATURE_NO_TITLE); // No title
        //set it to full screen.
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);




Working with Graphics:

gBall = BitmapFactory.decodeResource(getResources(), R.drawable.green_ball);
--> get reference to the image.



package com.ganta.learningandroid;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;

public class MyBringBack extends View {

    Bitmap gBall;
    float changingY;
    
    public MyBringBack(Context context) {
        super(context);
        gBall = BitmapFactory.decodeResource(getResources(), R.drawable.green_ball);
        changingY = 0;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(gBall, (canvas.getWidth()/2), changingY, null);
        if(changingY < canvas.getHeight()) {
            changingY++;
        }
        else {
            changingY = 0;
        }
        Rect middleRect = new Rect();
        middleRect.set(0, 400, canvas.getWidth(), 550);
        Paint ourBlue = new Paint();
        ourBlue.setColor(Color.BLUE);
        canvas.drawRect(middleRect, ourBlue);
        invalidate();
    }
}




package com.ganta.learningandroid;

import android.app.Activity;
import android.os.Bundle;

public class GFX extends Activity {

    MyBringBack ourView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ourView = new MyBringBack(this);
        setContentView(ourView);
    }
    
}



SurfaceView:

View takes up too much processing, hence we resort to SurfaceView


package com.ganta.learningandroid;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;

public class GFXSurface extends Activity implements OnTouchListener {

    MyBringBackSurface ourSurfaceView;
    float x, y, sX, sY, fX, fY;
    float dX, dY, animateX, animateY, scaledX, scaledY;
    Bitmap test, plus;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ourSurfaceView = new MyBringBackSurface(this);
        ourSurfaceView.setOnTouchListener(this);
        x = 0;
        y = 0;
        sX = 0;
        sY = 0;
        fX = 0;
        fY = 0;
        dX = dY = animateX = animateY = scaledX = scaledY = 0;
        test = BitmapFactory.decodeResource(getResources(),
                R.drawable.green_ball);
        plus = BitmapFactory.decodeResource(getResources(),
                R.drawable.button);
        setContentView(ourSurfaceView);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ourSurfaceView.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        ourSurfaceView.resume();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        x = event.getX();
        y = event.getY();
        
        try {
            Thread.sleep(50); // FPS = 20
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            sX = event.getX();
            sY = event.getY();
            dX = dY = animateX = animateY = scaledX = scaledY = fX = fY = 0;
            break;
        case MotionEvent.ACTION_UP:
            fX = event.getX();
            fY = event.getY();
            dX = fX-sX;
            dY = fY-sY;
            scaledX = dX/30;
            scaledY = dY/30;
            x = 0; // avoid prining first label.
            y = 0;
            break;
        }

        return true; // follow the curser when dragging
    }

    public class MyBringBackSurface extends SurfaceView implements Runnable {

        SurfaceHolder ourHolder;
        Thread ourThread;
        boolean isRunning = false;

        public MyBringBackSurface(Context context) {
            super(context);
            ourHolder = getHolder();
        }

        public void pause() {
            isRunning = false;
            while (true) {
                try {
                    ourThread.join();
                } catch (InterruptedException e) {
                    // TODO Add LOG statement here.
                    e.printStackTrace();
                }
                break;
            }
            ourThread = null;
        }

        // called form GFXSurface
        public void resume() {
            isRunning = true;
            ourThread = new Thread(this);
            ourThread.start();
        }

        @Override
        public void run() {
            while (isRunning) {
                if (!ourHolder.getSurface().isValid()) {
                    continue;
                }

                Canvas canvas = ourHolder.lockCanvas();
                canvas.drawRGB(2, 2, 150);
                if (x != 0 && y != 0) {
                    canvas.drawBitmap(test, x - (test.getWidth() / 2), y- (test.getHeight() / 2), null);
                }
                if (sX != 0 && sY != 0) {
                    canvas.drawBitmap(plus, sX - (plus.getWidth() / 2), sY- (plus.getHeight() / 2), null);
                }
                if (fX != 0 && fY != 0) {
                    canvas.drawBitmap(test, fX - (test.getWidth() / 2)-animateX, fY- (test.getHeight()/2)-animateY, null);
                    canvas.drawBitmap(plus, fX - (plus.getWidth() / 2), fY- (plus.getHeight() / 2), null);
                }
                animateX = animateX + scaledX;
                animateY = animateY + scaledY;
                ourHolder.unlockCanvasAndPost(canvas);
            }
        }

    }

}





SoundPool --> loaded into memory.. for short sounds
MediaPlayer --> stream it.. takes a while.. for longer sounds


@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        View v = new View(this);
        v.setOnClickListener(this);
        v.setOnLongClickListener(this);
        setContentView(v);
        sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
        explosion = sp.load(this, R.raw.explosion, 1);
        mp = MediaPlayer.create(this, R.raw.autobots_roll_out);
    }


    @Override
    public void onClick(View v) {
        if(explosion != 0) {
            sp.play(explosion, 1, 1, 0, 0, 1);
        }
    }






    <SlidingDrawer
        android:id="@+id/slidingD"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:content="@+id/content"
        android:handle="@+id/handle" >

        <Button
            android:id="@+id/handle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Handle" />

        <LinearLayout
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <CheckBox
                android:id="@+id/checkBox1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="CheckBox" />
        </LinearLayout>
    </SlidingDrawer>



FrameLayout --> Doesn't care about the position.  over laps controls. (useful in Sliders)


Tabs is a good option for desing.

WebView -> WebBrowser-> Using various methods.
Clicking a link on the webView will cause it to open in webbrowser.. by calling an intent for the same,
it can be avoided by creating a WebViewClient.


ourBrow.setWebViewClient(new OurViewClient());

public class OurViewClient extends WebViewClient {
  @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

The content on the WebView can be scaled, by zoom-out.

http://www.youtube.com --> will not load properly by saying "Please enable JavaScript on your Browser"

ourBrow.getSettings().setJavaScriptEnabled(true);



        //Completely Zoomedout or not?
        ourBrow.getSettings().setLoadWithOverviewMode(true);
        //Normal view port? Normal desktop browser.
        // false -> constrained to its own dimentions.
        ourBrow.getSettings().setUseWideViewPort(true);


Hide the KeyBoard after using it.


//Hiding the keyboard after using an EditText
            InputMethodManager iMM = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            iMM.hideSoftInputFromWindow(url.getWindowToken(), 0);


Show one control at a time, and iterate over the all the controls, using Flipper.
Useful when creating flashcards. etc.


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.flipper);
        flippy = (ViewFlipper) findViewById(R.id.viewFlipper1);
        flippy.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        flippy.showNext();
    }


Use key-value pairs for storing data. --> By using fileName
someData = getSharedPreferences(fileName, 0);

use an editor to edit and save the data.

            String stringData = sharedData.getText().toString();
            Editor editor = someData.edit();
            editor.putString("sharedString", stringData);
            editor.commit();.


            // Update the variable to load the new data if exists
            someData = getSharedPreferences(fileName, 0);
            String string = someData.getString("sharedString", "Counldn't Load Data");
            dataResults.setText(string);



Think of the SharedPreferences as a folder.
key -> fileName
value -> fileContent

Use for saving simple data, string, true/false etc. not for lot of data.



        ProgressDialog



// AsyncTask -> Input, ProgressBar, Output
    public class LoadSomeStuff extends AsyncTask<String, Integer, String> {

        ProgressDialog dialog;
       
        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(InternalData.this);
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setMax(100);
            dialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
           
            for(int i=0; i<20; i++) {
                publishProgress(5);
                try {
                    Thread.sleep(88);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
           
            dialog.dismiss();
           
            try {
                FileInputStream fis = openFileInput(FILENAME);
                byte[] dataArray = new byte[fis.available()];
                while(fis.read(dataArray) != -1) {
                   
                }
                String collected = new String(dataArray);
                fis.close();
                return collected;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onProgressUpdate(Integer... progress) {
            dialog.incrementProgressBy(progress[0]);
        }

        protected void onPostExecute(String result) {
            //super.onPostExecute(result);
            dataResults.setText(result);
        }
    }





save.setVisibility(View.VISIBLE);
android:visibility="invisible"



Toast t = Toast.makeText(ExternalData.this, "File has been saved..", Toast.LENGTH_LONG);
                t.show();



// Update files for the user to use.
                MediaScannerConnection.scanFile(ExternalData.this, new String[]{file.toString()}, null, 
                        new MediaScannerConnection.OnScanCompletedListener() {
                    
                    @Override
                    public void onScanCompleted(String path, Uri uri) {
                        Toast t = Toast.makeText(ExternalData.this, "Scan Complete..", Toast.LENGTH_SHORT);
                        t.show();
                    }
                });

Wednesday, December 19, 2012

Setup git in eclipse


Open eclipse
Create New Project
a.       File -> new -> java Project
b.      Enter project name, and finish creating project
Project Name: git-demo-setup


Finish creating the project.


Now to setup with github, right click on project “Team”->”Share Project…”



Select Git.







When selected Next in above screen, check the checkbox and select the project.

Select create Repository button


Say finish



In the Git Repositories View (in eclipse)



Expand the repository.



Do the following steps.



Remote name: git-demo-setup















Say add.
Start typing master in remote branch and select master from drop down.
(Don’t check force update)






Select add.



Say finish



Open config file
Current content are:
[core]
       repositoryformatversion = 0
       filemode = false
       logallrefupdates = true
[remote "git-demo-setup"]
       url = https://github.com/sravanreddy001/git-demo-setup.git
       push = HEAD:refs/heads/master
       fetch = +refs/heads/master:refs/remotes/git-demo-setup/master

add the below lines (no new line in the end)
[branch "master"]
       remote = git-demo-setup
       merge = refs/heads/master





Try merging









If it give any error while merging,
Goto synchronize project and mark the project (or) files as “overwrite” or “merged” to get rid of that error.