LIST VIEW IN ANDROID

adapter

  • Data to be inserted is first stored in object.
  • ArrayList stores references of those objects in indexed approach from 0 to (n-1).
  • Adapter contains processing  API called getView().
  • Adapter needs three arguments : Reference of Activity, Reference of list_item, Reference of data structure eg. ArrayList.
  • getView() takes the object one by one, binds the data to the list_item and also list_item to list view.

Example :

In NewsAggregator.java ,  populate arraylist with objects and  set adapter on ListView as :


listView=(ListView)findViewById(R.id.listview);
list=new ArrayList<>();

//Adding object references to ArrayList
list.add(new NewsObjects(R.drawable.tribune,"English","The Tribune","http://www.tribuneindia.com/mobi/"));
list.add(new NewsObjects(R.drawable.dainikbhaskar,"Hindi","Dainik Bhaskar","http://m.bhaskar.com"));
list.add(new NewsObjects(R.drawable.kerelaexpress,"Malayalam","Kerala Express","http://www.keralax.com"));
list.add(new NewsObjects(R.drawable.lokmatmarathi,"Marathi","Lokmat","http://www.lokmat.com"));

//Rest of the objects

adapter=new NewsAdapter(NewsAggregator.this,R.layout.list_item,list); //Initializing Adapter
listView.setAdapter(adapter); //Setting adapter on List View

NewsObjects.java


public class NewsObjects {
int icon;
String language,newspaper,url;

public NewsObjects(int icon, String language, String newspaper, String url) {
this.icon = icon;
this.language = language;
this.newspaper = newspaper;
this.url = url;
}
//getters and setters
}

NewsAdapter.java


//constructor here

//getView()

public View getView(int position, View convertView, ViewGroup parent) {
View item;

item= LayoutInflater.from(cxt).inflate(res,parent,false);
ImageView icon=(ImageView)item.findViewById(R.id.imageViewIcon);
TextView language=(TextView)item.findViewById(R.id.textViewlanguage);
TextView newspaper=(TextView)item.findViewById(R.id.textViewNewspaper);

NewsObjects ob=list.get(position);
icon.setBackgroundResource(ob.getIcon());
language.setText(ob.getLanguage());
newspaper.setText(ob.getNewspaper());

return item;

}

newsaggregator

BACKWARD PASSING OF INTENT

ActivityOne invokes ActivityTwo for result  ,let say on the click of button.

Code for ActivityOne goes as :


//Previous code

public void onClick(View v)   {     //onClick of a button ActivityTwo is started
Intent i = new Intent(ActivityOne.this,ActivityTwo.class);
startActivityForResult(i,100);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {    //This method runs when data is passed from ActivityTwo to ActivityOne
if(requestCode ==100 &&  resultCode==101){
String data = data.getStringExtra("keyData");
}

//Rest of the code
}

Now, ActivityTwo has to send data to ActivityOne when a particular event occurs , let say on Click of button.

Code of ActivityTwo goes as :


//Previous code

public void onClick(View v) {          //Intent is passed to first Activity when button is clicked
Intent data = new Intent();
data.putExtra("keyData","data string");
setResult(101,data);     // -> invokes onActivityResult of that Activity which started it
finish();
}

//Rest of the code

VIEWS IN ANDROID

WEBVIEW:

WebView is a view that can dynamically load web pages.For using webview , Go to Manifest file and add user-permission of internet as follows :


<user-permission android:name ="android.permission.INTERNET">

Example: One Activity passes the url and name of a newspaper’s website . The below given activity gets intent and WebView is initialized.


Intent data=getIntent();
String url=data.getStringExtra("keyUrl");
String newspaper=data.getStringExtra("keyNewspaper");

setTitle(newspaper);
webView.getSettings().setJavaScriptEnabled(true);

WebViewClient client=new WebViewClient();
webView.setWebViewClient(client);

webView.loadUrl(url);

CHECKBOX :

For including checkboxes in android, the class should implement OnCheckedChangedListener.  


public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int id = buttonView.getId();

switch (id){
case R.id.checkBoxOne:
//stuff for checkbox One
break;

case R.id.checkBoxTwo:
//stuff for checkbox Two
break;
}
}

RadioButton :

Implements CompundButton.onCheckedChangedListener


&nbsp;

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int id = buttonView.getId();

switch (id){

case R.id.male :

//Code for male

case .id.female :

//Code for female

}

}

Rating Bar :

Implements onRatingChangedListener.


public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
Toast.makeText(this,"Rating: "+rating,Toast.LENGTH_LONG).show();
}

Spinner :

Touching the spinner displays a dropdown menu with all other available values.Data to be shown is fed to adapter which does the binding of data to the listview.

AutoCompleteTextView :

It shows a list of completion suggestions automatically while the user is typing.

LAYOUT

View groups are Layouts.

  • Linear Layout :This layout aligns all the views in it either horizontally or vertically.

android: orientation = “horizontal” set the layout orientation to horizontal . All the views will be added horizontally.

  • Relative Layout : Displays all the child views in relative positions.
  • Table Layout : Groups views into rows and columns.

<TableRow>

//add the views

</TableRow>

  • Framelayout : Mainy used to display single view . Overlapping can be produced. Limit of framelayout is 9 views divided into particular regions.

CARDVIEW

Cardview puts the view in card. This gives embossed look to the view.

For using cardview in xml file , add the library dependencies for cardview.

CardView containsonly one child.

 

MENU

Functions for adding menu

  • onCreateOptionsMenu(Menu menu)
  • onOptionsItemSelected(MenuItem item)

Explicit way

In onCreateOptionsMenu() , add the items as :

menu.add(GroupId,itemId,order,name);

In onOptionsItemSelected() , write the following code :

int id= item.getItemId();
switch(id){

case 0:
//do the code here

case 1:
//do the code here
}

Implicit way

Create an xml file for menu. Add items in that menu resource file.

And in onCreateOptionsMenu(), write code as :


MenuInflator inflator = getMenuInflator();
inflator.inflate(R.menu.file , menu );

Inflating a view means taking the xml file and creating the actual objects so that they are actually visible on Activity screen.

INTENT

Intent is an object in android that contains data that allows various components of App to communicate.

intent

Intent can be passed by two methods :

1.Implicit Intent : This intent allows other app to open specific component from another app. This is achieved through intent filter. We specify action and category for that particular component which we want to be accessible by other apps installed in device.

2.Explicit Intent : Specify the component which has to be started. Used to invoke the component of the same App . eg.

Intent i=new Intent(ActivityOne.this, ActivityTwo.class);
i.putExtra("key",value);
startActivity(i);

Bundle : We can put data in Bundle and Bundle in Intent, and then pass data from one Activity to another.


Intent i=new Intent(ActivityOne.this , ActivityTwo.class);
Bundle b=new Bundle();
b.putString("key" , "data");
i.putExtra("keyBundle",b);

LIFE CYCLE OF AN ACTIVITY

Activities are placed in the form of backstack.Whenever, an activity is displayed its object is first created in memory.

  1.  onCreate() : state when object of an activity is created by Android system.
  2. onStart() : Activity is visible to user but user can’t interact.
  3. onResume() : When object of Activity is visible and user can interact through GUI.
  4. onPause() : When Object of activity is visible but user can’t interact.
  5. onStop() : Object of activity is not visible and user can’t interact with it.
  6. onDestroy() : Object of activity is destroyed.

 

INTRODUCTION TO ANDROID

Android is open-source Linux based OS for smartphones and tablet computers.

ANDROID ARCHITECTURE

android-architecture

  1. LINUX KERNEL : Responsible for drivers,  memory management, device management.
  2. NATIVE LIBRARIES : There are libraries including  WebKit, SQLite database , SSL libraries..
  3. ANDROID RUNTIME : DVM (Dalvik Virtual Machine) which is responsible to run android application.
  4. ANDROID FRAMEWORK : Includes Android API’s such as UI ,telephony, resources.
  5. APPLICATIONS : Applications such as home, contact, settings, games, browsers.

APPLICATION COMPONENTS

  1. Activity : Handles UI
  2. Service : Handle background processes associated with an App.
  3. Broadcast Receiver : Handles communication between Android OS and App.
  4. Content Provider : Handle data and data base management.

For Basic  Android development ,  two languages are needed.

For front end – Xml

For back end – Java

JAVA IO

The java.io package contains all the classes required for input and output operations.

IMPORTANT TERMS

Input Output Redirection : I/O stream ends change direction and placed on file , console, or printer whenever required.

Stream : Its the flow of data

Input Stream :  Input Stream is used for many things that you read from in the form of  stream of bytes.

Output Stream : Output Stream is used for many things that you write to in the form of  stream of bytes.

Reader : Similar to Input Stream but data read character by character.

Writer : Similar to Output Stream but data read character by character.

BufferedReader : This class reads text from a character-input stream, buffering characters so as to provide for the efficient reading.

 

FILE OPERATIONS

File(String pathname) : creates a new File instance by converting  pathname string into an abstract pathname. eg.


File file=new File("C:/prog/AnyName.txt");

 

getName() : returns the name of the file or directory. eg.


String name = file.getName();

 

getAbsolutePath() : returns the absolute pathname string. eg.

String path = file.getAbsolutePath();

 

exists() : checks whether the file or directory exists or not. eg.


if(file.exists()){
  //do the coding here
 }

 

isDirectory() : tests whether the file is a directory. eg.


if(file.exists()){
  if(file.isDirectory()){
    System.out.println(file.getName()+" is a directory..");
  }
 }

 

lastModified() : returns the time when the file was last modified. eg.


long time = file.lastModified();

 

mkdir() : creates single directory. eg.

 file = new File("C:/Java");
 // creates directory
  bool = file.mkdir();    

 

mkdirs() : creates recursive directories. eg.

 file = new File("C:/Folder1/Folder2/Java");
  // create directories
  bool = file.mkdirs();    

 

GENERICS AND COLLECTIONS

GENERICS

Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively.

class Points <T>{
T x,y;

public Points() {

}

public Points(T x, T y) {
super();
this.x = x;
this.y = y;
}

public T getX() {
return x;
}

public void setX(T x) {
this.x = x;
}

public T getY() {
return y;
}

public void setY(T y) {
this.y = y;
}

@Override
public String toString() {
return "Points [x=" + x + ", y=" + y + "]";
}

}

public class Generics {
public static void main(String[] args) {
//Integer
Points<Integer> ref=new Points<Integer>(12,34);
System.out.println(ref);

//Float
Points<Float> ref1=new Points<Float>();
ref1.setX(23.5F);
ref1.setY(55.4F);
System.out.println(ref1);

}
}

Output :

Points [x=12, y=34]
Points [x=23.5, y=55.4]


COLLECTIONS

Collections in java is a framework that provides an architecture to store and manipulate the group of objects.

ArrayList :

  • This class can contain duplicate elements.
  • This class maintains insertion order.

LinkedList :

  • This class can contain duplicate elements.
  • This class maintains insertion order.

HashSet :

  • uses hashtable to store the elements.
  • contains unique elements only.

List can contain duplicate elements whereas Set contains unique elements only.

HashMap :

  • A HashMap contains values based on the key.
  • It contains only unique elements.

METHODS USED IN COLLECTIONS

  • add(Object element) : insert an element in this collection.
  • addAll(Collection c) :  insert all elements of collection in the invoking collection.
  • remove(Object element) : delete an element from collection
  • removeAll(Collection c) : deletes all the elements of the collection
  • size() :total number of elements of the collection
  • clear() : removes the total no of element from the collection
  • containsAll(Collection c) :search the specified collection in this collection