Archive

Category Archives for "Android tutorials"
1

Android: Displaying data in listView fetched from a webservice

 Displaying data in listView fetched from a webservice

Description: In this tutorial, we learn how to fetch images from web service and display those images in a list view. This all processes include concepts such as URL connection, Parsing data, Panel java objects, Adapters.

Introduction:

Android mobile application is no doubt one of the most interesting fields when it comes to  application development. Often working with android application development, you will have to fetch data from an online server and display that in your app to be presented to the user. Since mobile application have limited, resources we would need a connection to online server in order fetch the necessary data that is intended to be presented in an android application.

Web services are made in programming languages such as PHP, ASP.net or other web development languages. Android application using any web service primary goal is to fetch data, and display it accordingly. Web services are no thing, but data providers this data can be text, images etc.

Let me give you an example, suppose i make a server script page, that comprises of the following code.

 

Before we start any sort of programming stuff, let’s have a look at the basic architecture that will make you familiar with how things work.

fetch data from webservice to listview

The basic architecture we will be learning in this tutorial (we make an android application that will perform the task) is shown above.

Screen Shots 

Here are screen shots that will let you know, what will be our end result once we apply all of the code mentioned in this tutorial. The first screen shot show how our home screen will look like containing a welcome message and button to fetch data. The second screen shot Fetch activity containing a list view with data that is retrieved from a web service.

Android webservice and listview

populate list view from webservice

 

Android application:

The android applications we build in this tutorial consist of simply two activities and some other java classes.

  • Home screen (MainActivity) with button to fetch data.
  • java activity (that contains list view to display fetched data from the web url)
  • Inner AyscTask class
  • Class for HTTP connection
  • Class for Data
  • Adapter Class

 

Download the complete source code here to test your self.

Home Screen (MainActivity.java)

Our home screen java class contains code that responds to the onclick event. Once the button is clicked, we will be prompted to the fetch.jav activity. Plus we have a textview that displays a welcome message.

main_activy.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"

android:background="#FFBB00">

 

<TextView android:text="Welcome to FetchDATA App" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textSize="30sp"

android:id="@+id/textView" />

 

<Button

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="New Button"

android:id="@+id/button"

android:layout_marginTop="56dp"

android:layout_below="@+id/textView"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

</RelativeLayout>

MainActivty.java

Here is the code for home screen of our application.


package com.example.khan_pti.mfetchdata;

import android.content.Intent;

import android.support.v7.app.ActionBarActivity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

public class MainActivity extends ActionBarActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button b = (Button)findViewById(R.id.button);

b.setOnClickListener( new View.OnClickListener() {

@Override

public void onClick(View view) {

startActivity(new Intent(getBaseContext(),Fetch.class));

}

});

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement

if (id == R.id.action_settings) {

return true;

}

return super.onOptionsItemSelected(item);

}

}

 

Fetch.java class

The next class in our list is Fetch.java  that contains the main functionality of our application. When the user clicks on the button on the home screen, fetch.java activity will be prompted, and our background task that is explained below will be executed. Once the data is fetched from the server from using http URL connection we simply parse the data, store in in list array, and then populate our list view with data.

fetch.xml

Here is the xml representation of the fetch.java class, you clearly see, it contains list view.


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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent" android:layout_height="match_parent">

 

<ListView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/listView"

android:layout_alignParentBottom="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

</RelativeLayout>

Fetch.java


package com.example.khan_pti.mfetchdata;

import android.app.Activity;

import android.os.AsyncTask;

import android.os.Bundle;

import android.text.method.ScrollingMovementMethod;

import android.util.Log;

import android.widget.ListView;

import android.widget.TextView;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import java.net.HttpURLConnection;

import java.util.ArrayList;

/**

* Created by khan-pti on 30/03/2015.

*/

public class Fetch extends Activity {

ArrayList<Flowers> flowersList = new ArrayList<Flowers>();

String url ="http://services.hanselandpetal.com/feeds/flowers.json";

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.fetch);

new BackTask().execute(url);

}

public class BackTask extends AsyncTask<String,String,String>{

@Override

protected void onPreExecute() {

super.onPreExecute();

}

@Override

protected String doInBackground(String... strings) {

String content =HttpULRConnect.getData(url);

return content;

}

@Override

protected void onPostExecute(String s) {

try {

JSONArray ar = new JSONArray(s);

for (int i=0; i<ar.length(); i++){

JSONObject jsonobject = ar.getJSONObject(i);

Flowers  flowers = new Flowers();

flowers.setName(jsonobject.getString("name"));

flowersList.add(flowers);

}

}

catch (JSONException e){

e.printStackTrace();

}

FlowerAdapter adapter = new FlowerAdapter(Fetch.this, R.layout.flowers_list_items, flowersList);

ListView lv = (ListView) findViewById(R.id.listView);

lv.setAdapter(adapter);

//Log.d("recived",s);

}

}

}

 

Flower_List_item.xml

Please note our list view will need another xml layout file that will specify how the items are placed in each row of the list. Since in this example we only want to mention the name of the flower, therefore we require single text view to show the name of the flowers.

 


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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent" android:layout_height="match_parent">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceMedium"

android:text="Medium Text"

android:id="@+id/textView3" />

</LinearLayout>

 

Explaination to Android AsyncTask Class:

In android programming, each activity runs on its main thread. That means the UI elements etc. run on the main thread of the activity. An android programmer should take care of this main thread , and should never freeze the main thread for so long that it is discarded by the android operating system.

What about long running tasks, how they should be performed, well to perform long running, task that last for few seconds, android provides a class that is called, Asynctsak class.

You may be thing, why don’t we use, the java threads, etc. that is because, when we deal with threads, we would not be able to access the android UI elements, to overcome this problem, and similar android has a special type of class know as AysncTask.

Android AsyncTask can be used as an inner class, and usually contains three overridden methods that are of most important.


@Override

protected void onPreExecute() {

//method is Before Starting Background thread/task

//starts progress bar

}

@Override

protected String doInBackground(String... params) {

//Background task running

&nbsp;

return "Task complete";

}

@Override

protected void onPostExecute(String result) {

//stop progress bar

//Method is used after task completed, update UI compenents

}

&nbsp;



<strong>Json Parser:</strong>

In Fetch.java class with in our inner class, onPostExecute() method the data is parsed, and then added to the flower list. Since we get the data in json array , we will need to first parse the data, in order to use it .



try {

JSONArray ar = new JSONArray(s);

for (int i=0; i&lt;ar.length(); i++){

JSONObject jsonobject = ar.getJSONObject(i);

Flowers  flowers = new Flowers();

flowers.setName(jsonobject.getString("name"));

flowersList.add(flowers);

}

}

catch (JSONException e){

e.printStackTrace();

}

Explanation to the code:

Make a new instance of JSONArray (), Passing the data received as an argument. Use loop to access each object, which can be used by instance of Flowers class and eventually we add the Flower’s object flowers to the FlowerList.

 

Flower Adapter class:

Flower Adapter class it used in order to fetch data from the Fetch.java class and inflate data into the listview the way we want. We have created our own custom Adapter class .


package com.example.khan_pti.mfetchdata;

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.ArrayAdapter;

import android.widget.TextView;

import java.util.ArrayList;

/**

* Created by khan-pti on 01/04/2015.

*/

public class FlowerAdapter extends ArrayAdapter<Flowers> {

private  ArrayList<Flowers> items;

private Context mContext;

public FlowerAdapter(Context context, int textViewResourceID, ArrayList<Flowers> items){

super(context,textViewResourceID,items);

mContext = context;

this.items = items;

}

@Override

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

View v = convertView;

Flowers flowers = items.get(position);

if(v==null){

LayoutInflater inflater =(LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

v=inflater.inflate(R.layout.flowers_list_items,null);

}

TextView title = (TextView)v.findViewById(R.id.textView3);

if (title != null) {

title.setText(flowers.getName());

}

return v;

}

}



Explanation to code:

We create our own adapter class that extends ArrayAdapter, with data type of our Flower class.

The constructor gets parameters that are passed with instance of FlowerAdapter .



public class FlowerAdapter extends ArrayAdapter<Flowers> {

private  ArrayList<Flowers> items;

private Context mContext;

public FlowerAdapter(Context context, int textViewResourceID, ArrayList<Flowers> items){

super(context,textViewResourceID,items);

mContext = context;

this.items = items;

}

getView is the method, where we inflate the data into each of the row of our listview.


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

View v = convertView;

Flowers flowers = items.get(position);

if(v==null){

LayoutInflater inflater =(LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

v=inflater.inflate(R.layout.flowers_list_items,null);

}

TextView title = (TextView)v.findViewById(R.id.textView3);

if (title != null) {

title.setText(flowers.getName());

}

return v;

}


 

Class for data model:

Now in this example we are going to make a class that will contain private members based on the the data we recive from the json URL. In our example we are getting data for flowers.

The data come with key value pairs, we need to make our containing private members for keys.I will be only including the names of the flowers to make it short, and easy for you.

In your case, what ever data you are getting you may do it accordingly.

Flowers.java


package com.example.khan_pti.mfetchdata;

/**

* Created by khan-pti on 30/03/2015.

*/

public class Flowers {

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

private String name;

}


Http URL Connection

Here we could use http client connection as well, but since android development team recommends using http URL connection, therefore we use URL connection method to connect to the server. Secondly http client is no more updated, where as http URL connection will be updated further since android development team is working on this.

HttpURL.java


package com.example.khan_pti.mfetchdata;

import android.util.Log;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class HttpULRConnect {

public static String getData(String uri){

BufferedReader reader = null;

try {

URL url = new URL(uri);

HttpURLConnection con = (HttpURLConnection) url.openConnection();

StringBuilder sb = new StringBuilder();

reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

Log.d("testhtt2","test");

String line;

while ((line= reader.readLine())!=null) {

sb.append(line+"\n");

}

Log.d("test44", sb.toString());

return sb.toString();

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

return null;

}

finally{

 

if (reader!=null) {

try {

reader.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

return null;

}

 

}

}}}

 


 

Android Manifest file:

In end here is the manifest file, don’t forget adding permission of using internet, without this your application will not work. We don’t have much to do, here accept for couple of lines added for permission, and declaring activity, in our case Fetch Activity.

 


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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.khan_pti.mfetchdata" >

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

 

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

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

</application>

 

</manifest>


 

 

 

Conclusion:

Most of the android application, uses Listview, plus json, to fetch data .Most of the application rely on online server, in order fetch data, authenticate in fact application need to be connected to internet all the time to get user the latest updates. It is therefore on the most important topic that each and every programmer should know to develop an efficient android application. In this tutorial we have simply shown a text in the listview, where this can be further enhanced by adding images , and other text views to make it more complex and more informative. One can also add progress bar that can be set to visible in the onPreExecute () method, where as can be set invisible onPostExecute (). This can be one good enhancement.

Secondly we have no mechanism , about what happen when the user clicks on the listview items, while making android application you will obviously take care of that, you will only need to implement onclickListner that is it nothing else.

From here now, you can start looking to learn fragments, how to use fragments in list, view, and fragments providing best re usage and other advanced topics that will help you have quality application programmed.

At the conclusion I hope, you have learned some thing useful in this tutorial please let me know about you thoughts.

 

how to create Fragment in android

What is fragment?

Fragment is a partial part of activity, that comprises of xml layout, and java code. Its main advantage, is the resuability of code, once the fragment is created, it can be called in different activity where needed. It works just similar to the include function, that is used in php, that mean if we want to include a code, from another webpage, we simply include that page, all the code is considered to be accessed, and present now in the currently working page.

How to create a fragments?

We can add fragment, using either xml layout, or using java , in this tutorial we will learn how can we make fragment using java code, and using xml representation.

How to create a fragment And add it to an activity in java?

1. Create a new project with name you like, with simply blank activity.
2. Secondly create a new class with name of myfragment and it should extent fragment class.
3. Create new xml layout with name of my_fragment_layout.xml .
4. Drag some elements in your xml file, may be a text view or button, what ever you like.
MainActivity.xml
Please remember to provide a seperate id to your relative layout , becuase this will be need later, in java file. As you can see below in MainActivity.java.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

android:id="@+id/my_Layout" >
</RelativeLayout>

MainActivity.java:

package com.example.fargmenttutorial;
import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragment f = new MyFragment();
FragmentManager manager =getFragmentManager();
FragmentTransaction trasaction = manager.beginTransaction();
trasaction.add(R.id.my_Layout,f, "layoutTag");
trasaction.commit();

}

}

MyFragment.java

package com.example.fargmenttutorial;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MyFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.my_fragment_layout, container,false);
}

}

 

My_fragment_layout.xml

 


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#ffbb66">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This trustingeeks.com"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

 

 

Conclusion:

So what this means is your can add different fragment to your activity , with working again and again, this is very simple , since we only add fragments, thing, what happens when you have multiple fragment in your activity and one of the item in the fragment, is click, how do we handle the inter communication between fragments and cativity, this can all be achived, lead us to more robust app development. One more thing to add fragments are very much use full, when it comes to tablet , since the space on tablet is more as compared to mobile application, there fore fragments play most important role their too.

how to create fragments in android

3

How to connect Android app to MySQL database

How to connect Android app to MySQL database:

Description: In this article we will learn  how to connect android application to MySql database and apply the few of the queries (CREATE, READ ,UPDATE,DELETE) also called CRUD with proper code and explanation.

Introduction: Many android application on Google play store uses online Database to retrieve data, to be shown to the user. This is done, due to fact that we can’t store large amount of data on our android mobile. Some android application uses sqlite database for some of android application, but the data has to be of limited size.

Many  android application make use online database to have data of their users. Although we can use different web services for our application, depending on the needs of application we are to built.

Suppose if we need to make weather application, we will simply use any web service that provide us the data of the weather , which we can display on our appplication. But sometimes it becomes  mandatory to make your online database.

Lets know break down the tutorial into some steps .

  • How to Make a free database, domain name and hosting at 00webhost.com
  • Php script of CRUD sql queries.
  • Android application user interface.
  • Android application main java file.
  • Android application manifest file.
  • Conclusion

How to make free database, domain name and hosting at  00webhost.com?

First of all we need to make a free account at 00webhost website. Register a free domain .Once you register your free domain, navigate cpanel. Next step is to create a simple database at Phpmyadmin area.

Create a database with any name.

For this tutorial we would like to make an application for displaying list of products. The products will be the different types of mobiles phones .

Database should contain the following fields:

  • ID int (11) primary key auto incremented
  • mobileName varchar(255)
  • mobileModel varchar (255)
  • mobilePrice int(11)

Once the database with above description is created, we are ready for the next step.

NOTE: Note down the name of the database, server, username, and password , we will require this data  make a connection to the database.

Php script for CRUD sql queries.

In your cpanel browse to filemanger , then to public-html and create an new file with name of “queries.php”.

You will need to write the php script that should respond to event that we trigger on our android application.

Note : Your specification to make connection to the database.

$hostname = “mysql8.000webhost.com”;
$username =”a522438_elift”;
$password =”Hamdard12″;
$db = “a522438_elift”;

Now lets first make a connection to the database and display that on our android device.

Listing#1 Product.php


<?php

$hostname = "mysql8.000webhost.com";

$username ="a5224389_elift";

$password ="Hamdard12";

$db = "a5224389_elift";

$conn = new mysqli($hostname,$username,$password,$db);

if($conn->connect_error){

$response[‘success’] =0;

$response[‘message’] =”could not connect to the database”;

print(json_encode($response));

die(print(json_encode($response)));

}

$response[success] =1;

$response[message] =”successfully connected to the database”;

print(json_encode($response));

?>

Explanation code:

In the first step we make a simple connection to the database. To notify the user we send the $response value to android applcation, that is for value 1 , we  will display the database is connected successfully , where as for the value 0 we will display the text saying that database could not be connected .

Now lets look at the java code and xml representation, we have used to get all this functionality .

Listing#2 MainActivity.java


package com.conndb;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

TextView tv;

String textview = null;
static JSONObject jObj ;
static String json = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
Button b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i2 = new Intent(MainActivity.this,menuList.class);
startActivity(i2);
}

});

Button connectdb = (Button) findViewById(R.id.button1);
connectdb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Connectingdb().execute();
}

});

}

class Connectingdb extends AsyncTask<String, String, JSONObject> {
/*Before starting background thread Show Progress Dialog

* */

boolean failure = false;
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempting connect...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected JSONObject doInBackground(String... args) {
InputStream is = null;
// Making HTTP request
try {
// check for request method
{
// request method is POST
// defaultHttpClient

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://ieeehiit.host22.com/product.php");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();}

}

catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
jObj = new JSONObject(json);
is.close();
return jObj;
}
catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
return null;
}
}

/**

* After completing background task Dismiss the progress  dialog

* **/

protected void onPostExecute(JSONObject json) {
int success = 0;
try {
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

if (success == 1)

try {

display(json.getString(TAG_MESSAGE));

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

pDialog.dismiss();

}

}

public void display(String m){

tv.setText(m);

}

}

Explaination to code:

Before we jump into explaining the code, lets first have some basic concepts of how do we perform long running operation in android .

Each application in android runs on its main thread. Main activity containing, most of the user interface widgets needs runs on the main thread.In case we want to perform operations that require few seconds(such as connectivity to online server, login in and other similar works ) will freeze the main activity thus user would not be able to interact with application.

To get rid of this problem android has a special class called AsynTask, that is special built form these kind of operation. As you can see in the code above we have used the AsyncTask.

AsynTask has one method that must be overridden that is

@Override

protected< String doInBackground(String… args) {}

Which take arguments that is multiple arguments, which are stored as an array of type String(you are not restricted to only strings).The above signature is used when you need to use same type of data types for your AsyncTask.

AsyncTask<String, String, String>

Note that while we are doInBackground() method, we cannot, touch the views. Inother words you cannot, assign values to textviews etc.

So how to notify the user , that something is happening in the background we make use of two methods

protected void onPreExecute()

It will be executed before the doInBackground method gets started.

protected void onPostExecute()

It will be executed after the doInBackground method. And it takes the argument, from the doInBackground method that can be stored in any view, such as textview as we have shown in the code.

You may also have noticed that we have also used the progress bar that starts onPreExecutes and gets hidden in the method named onPostExecte.

This is to make the user notified, and ask to wait for few seconds as our background task is going on.

Now let’s get back to code and explain what actually is happening!

To make a request to the user , we can either use , the HTTP request or we  can use the HTTP URL connection.

The above code uses HTTP method, where as most of the application, now a days uses URL connection method, which is continually maintained by the android developing team. The former method has not been maintain for quite some time.

We simple use Request and response objects to make a connection to the server in the above code.


DefaultHttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new  HttpPost("http://ieeehiit.host22.com/product.php");

HttpResponse httpResponse = httpClient.execute(httpPost);

HttpEntity httpEntity = httpResponse.getEntity();

is = httpEntity.getContent();

httpPost object behaves as a request with a http methode of type post, URL as an argument.

Response is then stored in InputStrem object “is” using httpEnity.getContent().

We simply then read line by line, the input stream, and deal with it, they way we want to deal, with it.

In our case we simply have either 1 or 0 as a response from the server, and once we know the response value we notify the user on the basis of that value.

In this version of our application we simply have a button view and text view. When clicked on button, we are shown with result weather connected or not! Besides this we have used RelativeLayout for our xml representation, which positions  the items in a respective manner

Listing#3 activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context=".MainActivity" >

 

<Button

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentLeft="true"

android:layout_alignParentTop="true"

android:layout_marginLeft="64dp"

android:layout_marginTop="100dp"

android:text="check conection" />

 

<TextView

android:id = "@+id/textView1"

android:layout_width = "match_parent"

android:layout_height = "wrap_content"

android:layout_alignParentTop = "true"

android:layout_centerHorizontal = "true"

android:layout_marginTop ="53dp"

android:text="TextView" />

</RelativeLayout>

OUTPUT:

android tutorial to connect to database online

Fig : 1 Displaying the output for database connection .

Now we will modify both our php Script and UI interface so that we apply the read sql query to fetch data from the database and display it on the android application.

 

Implementing Read query on Mysql database using android:

Lets first look at the modification that  we have to make in order to implement read query.

 

Listing #4 Php Script Version2:


<?php

$hostname = "mysql8.000webhost.com";

$username ="a5224389_elift";

$password ="Hamdard123";

$db = "a5224389_elift";

$conn = new mysqli($hostname,$username,$password,$db);

if($conn->connect_error){

$response ="could not connect to the database";

die(print(json_encode($response)));}

$q ="Select * from product";

$result = $conn->query($q);

while($row = $result->fetch_assoc()){

$output= $row;

}

print(json_encode($output));

$conn->close();

 

?>

Explanation to the code:

The data displayed on the screen of android application is fetched as json(which is a data format same like XML but is light weight ). Json data can of two types , Json Objects and json Arrays .

To display the json on android screen you will first need to parse the data, for which you will need to first analyse whether your data is coming as json objects or json Arrays .

[ ] brackets are signs of json objects where as {} brackets are the signs of objects.

 

Coming back to the code of Php script, we have simply used the select query, and then printed the data as json.

 

$q =”Select * from product”;

$result = $conn->query($q);

while($row = $result->fetch_assoc()){

$output= $row;}

print(json_encode($output));

 

 

 

Now lets look at the changes that we have made in our mainActivity.java file in order to display this data.

Listing #5 mainActivity java version 2


public class MainActivity extends Activity {
TextView tv;
String textview = null;
static JSONObject jObj ;
static String json = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
Button b2 = (Button) findViewById(R.id.button1);

b2.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

// TODO Auto-generated method stub

Intent i2 = new Intent(MainActivity.this,menuList.class);
startActivity(i2);

}

});
Button connectdb = (Button) findViewById(R.id.button1);
connectdb.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Connectingdb().execute();
}

});
}

class Connectingdb extends AsyncTask<String, String, JSONObject> {
/**

* Before starting background thread Show Progress Dialog

* */

boolean failure = false;
private ProgressDialog pDialog;

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempting connect...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();

}
@Override
protected JSONObject doInBackground(String... args) {
InputStream is = null;

// Making HTTP request

try {
// check for request method

{

// request method is POST

// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://ieeehiit.host22.com/product.php");
HttpResponse httpResponse =             httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

}
} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

try {

BufferedReader reader = new BufferedReader(new InputStreamReader(

is, "iso-8859-1"), 8);

StringBuilder sb = new StringBuilder();

String line = null;

while ((line = reader.readLine()) != null) {

sb.append(line + "\n");

}

json = sb.toString();
jObj = new JSONObject(json);
is.close();
return jObj;
} catch (Exception e) {

Log.e("Buffer Error", "Error converting result " + e.toString());
return null;

}
}

/**

* After completing background task Dismiss the progress dialog

* **/

protected void onPostExecute(JSONObject json) {

try {
int mobid = json.getInt("ID");
String mobilename = json.getString("mobileName");
String mobileModel = json.getString("mobileModel");
int mobilePrice = json.getInt("mobileprice");

display("mobile Id= "+mobid+"\nmobileName = "+mobilename +"\n mobile model = "+mobileModel +"\n mobile price = "+mobilePrice+"\n>>>>>>>>>>>>>>>\n");

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}
pDialog.dismiss();
}
}
public void display(String m){
tv.setText(m);
}
}

Explanation to the code:

Most the code above is similar to our previous code, whe just made some changes.
To get the exact data , we are looking for

static JSONObject jObj ;
is being used.

Remeber that, since we have used , our own php script, the data is in json, objects we are only showing one recode right now on our android application. This is just to make you familiar with usage. Most often while dealing with web-services you will be having your data as jsonArray , That is more efficient , you can play around with data as you want. I could have use some libraries to show all of the recodes on screen.


int mobid = json.getInt("ID");
String mobilename = json.getString("mobileName");
String mobileModel = json.getString("mobileModel");
int mobilePrice = json.getInt("mobileprice");
display("mobile Id= "+mobid+"\nmobileName = "+mobilename +"\n mobile model = "+mobileModel +"\n mobile price = "+mobilePrice+"\n&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n");


After Passing the JSONObject from the doInBackground method, the data is stored in relative string, using get methods of the jsonclass.which is then passed to display method to be appended to the textView.

We do have made some of the changes in the XML file also.
<h2>Listing #6 activity_main.xml</h2>


&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" &gt;

&lt;ScrollView
android:id="@+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="37dp" &gt;

&lt;LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" &gt;

&lt;/LinearLayout&gt;

&lt;/ScrollView&gt;

&lt;TextView

android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignLeft="@+id/button1"
android:layout_alignRight="@+id/button2"
android:layout_below="@+id/button1"
android:layout_marginTop="24dp"
android:text="TextView" /&gt;

&lt;Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Read cammad" /&gt;

&lt;Button

android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="Next activity " /&gt;

&lt;/RelativeLayout&gt;

OUTPUT:

android tutorial  how to connect to databse

Figure #2 Displaying data fetched from the database .

Conclusion:

We dicussed how to connect with database, and get notified on our andorid application.
AysnTask class was discussed in detail.
We have also used Select query to fetch data from the mysql data base. We learned how to display data using json objects.
Hope you have got some of the idea , on how to deal with data bases , using php, mysql and android. Besides this I would recommend you to have a look, different  web-services . There are various web service which can be used to make android application, to bring ease to the human life. All of the web service almost have the same concept, as we have discussed, in fact it would be more easy for you to deal with that. You only need to follow their documentation, for applying different queries, fetching data etc.

All of the web services now a days provide their data as json, and xml which you can easily use for your android application.

2

Create free app with app creator

Create free app with app creator:

createmyfreeapp: In today’s world of information technology , humans have brought almost every thing into a tiny small but smart device. Android , IOS being the most popular OS running on these devices. Today every organization , business need their own custom application, so that data is kept to the finger tips of managers.This helps to analyse data.Building application can cost you very money. But today i will be bringing you one of the web application called CreatYourFreeApp  which will let you make different sort of applications for different categories.

create free app

 

These includes

  • Business applications,
  • Entertainment applications
  • Event applications
  • Education and much more.

Create free app with our app maker through through easy steps , Login , Desing, and Publish. Your application will be placed on google paly store thus letting you download, distribute your application with all your employees and the people you need to use your application.

Secondly the you can design you application according your wishes, you can add headers, splash screens and other important data to your application such as about us, social channels they way you wish. you donot need any sort of coding your free app creator will make you an amazing application with in few minutes .

Beside free version, we have different sort of premium features for your application that you can buy and enhance your capabilities of application that you have created through free app maker application , with your designed instruction.

I highly recommend you if you have any of business organization, these free app creator will surly help you boost-up your business and take your business to next level of which you have every time dreamed of.

So now create your application without codding , with costing any sort of money providing you only designed app according your own design. you can get you application both for android and IOS.

Android drop down List:Example

Android drop down List:In this tutorial we will make Android drop down List without using xml. Basically all the work is done using the java programming. We can make Android drop down List simply by using xml, But you can also create using a Java implementation to have full control .

So first of you will need to create a new application with any name you like , and then you simply need have a look at the coding below .

Android drop down List:Example


class menuList extends ListActivity {

//remember to extend your class extends ListActivity

String listvalues[] ={ "item1", "item2","item3"};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setListAdapter(new ArrayAdapter(menuList.this, android.R.layout.simple_dropdown_item_1line, listvalues));

// we use a methode setListAdapter() methode that takes an arrayAdapter that //takes context and , dropdwonlist constant , and listvalues

}

@Override

protected void onListItemClick(ListView l, View v, int position, long id) {

super.onListItemClick(l, v, position, id);

// you can perform opertion on each item clicked here!

}

}

OutPutAndroid drop down List

 

 

When to Drop down list:

It can be used to list down different item, or activities of  your android application.Besides this you can use drop down list while parsing the data and displaying images with some description on a list.Basically it can be used at so many places depending on your application fuctionality .

Once you learn this you can simply use the same features at different application, most of the application now adays contains drop down list menus , and the cool thing is android.R.Layout provides you different styles of menu which you can use according to your needs.

 

Conclusion:

In this short tutorial you just learned how to create  a simple drop down list menu, soon we will be updated the second portion we we can perform different action when each of the item is clicked.

 

Android progress bar understanding

Android progress bar

It is good practice to show the users w the progress of some processes using android progressbars. To keep the application more user friendly android progress bars are often used. suppose you are downloading game from Google play store. Your downloading is shown to you with an android progress bar with some sort values giving an idea of a process in progress. Same is the case with uploading a file, android progress bar is used to show the progress of uploading.

How to Android progress bar?

To create android progress bar you have to create instance of progressDialog class.

ProgressDialog progress = new ProgressDialog(this);

Now you can set some properties of this dialog.


progress.setMessage("Downloading Music 🙂 ");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);

second line of above code shows the shape of android progress bar. Android progress bar has two types

  • STYLE_HORIZONTAL

android progress bar

  • STYLE_SPINNER

android progress bar

progressDialog class Methods used for

android progress bar

Following methods are used for android progress bar.


getMax()

This method returns the maximum value of android progress bar.


incrementProgressBy(int a)

These method increments the android progress bar by value passed as a argument.


setIndeterminate(Boolean det/indet)

This method in android progress bar set the progress indicater as indeterminate or determinate.


setMax(int maximum)

This method in android progress bar set the maximum value of android progress bar.


show(Context context, CharSequence title, CharSequence message)

This is static method in android progress bar show the progress dialog.

Android progress bar examples

Spinner progress bar example

MainActivity.java


package com.example.progressbar;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

private ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = new ProgressDialog(this);
}

public void open(View view)
{
progress.setMessage("Downloading.....");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.show();

final int total = 100;
final Thread t = new Thread(){

@Override
public void run() {
int jumpTime = 0;
while(jumpTime<total)
{
try {
sleep(2000);
jumpTime+=5;
progress.setProgress(jumpTime);
} catch (Exception e) {
}
}
}

};
t.start();
}
}

 Activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:text="MUSIC ON MASTFM.COM"
android:textSize="25sp"/>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="94dp"
android:text="Download A"
android:onClick="open" />
</RelativeLayout>

 Android progress bar manifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.progressbar"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.progressbar.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

android progress bar

 

android progress bar

Horizontal progress bar example

 MainActivity.java


package com.example.progressbar;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

private ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = new ProgressDialog(this);
}

public void open(View view)
{
progress.setMessage("Downloading.....");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.show();

final int total = 100;
final Thread t = new Thread(){

@Override
public void run() {
// TODO Auto-generated method stub
int jumpTime = 0;
while(jumpTime<total)
{
try {
sleep(2000);
jumpTime+=5;
progress.setProgress(jumpTime);
} catch (Exception e) {
// TODO: handle exception
}
}

}

};
t.start();
}
}

android progress bar

NOTE:

The xml and manifest file for above both program will be same. Only android progress bar styles are changed in mainActivity.java.

 

Android voice recorder code

1

android voice recorder android coding

android voice recorder

You can capture audio / record voice in android voice recorder. Android has built-in microphone. You can store it, play it in your android phones.  Android provide many ways for android voice recording. But mainly used class is MediaRecorder class for audio and video.

Create the object of MediaRecorder class

android voice recorder


MediaRecorder  media = new MediaRecorder();  

Perform the following methods for MediaRecorder  to set the source, encoding format of audio/video , output and  and output file


media.setAudioSource(MediaRecorder.AudioSource.MIC);

media.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

media.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);

media.setOutputFile(outputFile);

Methods of MediaRecorder

In this android voice recorder application you have to call some of the following methods of MediaRecorder for android voice recorder.

prepare();

this method prepare the android voice recorder process.

start();

this method starts the android voice recorder process.

stop();

this method stop the android voice recorder process.

setOututFile();

this method set path for audio to be stored in android voice recorder process.

setOutputFormat();

this method set ouput file format for android voice recorder process.

setAudioSource();

this method set the audio source for the android voice recorder process.

setVideoSource();

this method set the video source for the android voice recorder process.

Example of android voice recorder

MainActivity.java


package com.example.recorder;

import java.io.IOException;
import android.*;

public class MainActivity extends Activity {

private MediaRecorder media;
private String outputFile = null;
private Button start,stop,play;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button)findViewById(R.id.button1);
stop = (Button)findViewById(R.id.button2);
play = (Button)findViewById(R.id.button3);

stop.setEnabled(false);
play.setEnabled(false);
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/recording.3gp";;

// android voice recorder

media = new MediaRecorder();
media.setAudioSource(MediaRecorder.AudioSource.MIC);
media.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
media.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
media.setOutputFile(outputFile);

}

public void start(View view){
try {
media.prepare();
media.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
start.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "WOW!...Recording is started", Toast.LENGTH_LONG).show();

}

// android voice recorder

public void stop(View view){
media.stop();
media.release();
media = null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recorded successfully",
Toast.LENGTH_LONG).show();
}

public void play(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException, IOException{

MediaPlayer m = new MediaPlayer();
m.setDataSource(outputFile);
m.prepare();
m.start();
Toast.makeText(getApplicationContext(), "WOW!.....Playing", Toast.LENGTH_LONG).show();

}
}

android voice recorder activity_main.xml

android voice recorder

if you run above  android program it will not run and gives error. The question is why?

Because you have to take permission for using resources. So you must add permissions. Here we will use two permissions. One is for storing our file in external storage. For this you have to add

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

The another one permission for android voice recorder to record audio. So you have to add

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

 mainfest.xml of android voice recorder

android voice recorder

After all the above steps, this android voice recorder program can be run on AVD or your phone. This can be done by click on “run” option.

android voice recorder

 

By pressing start button on this android voice recorder application. Recording will be started.android voice recorder

By pressing stop button on this android voice recorder application. Recording will be stopped. and save in external storage on your android phones.

android voice recorder

 

Only play record button is enabled. By pressing this button, your recorded audio will be playing.

android voice recorder

Android activity lifecycle

Android activity lifecycle: To know about what  activity  is?  you can  check out my previous tutorial about learn about android activity. In this tutorial we will disscuss the lifecycle of android activity , callback methods, stackback, and an example program to understan every thing about android activity lifecycle.

android activity life cycle.

What happens when an application is lunched on android phone?

android activity lifecycle methods

android activity lifecycle methods

When ever an application in android is started, there are three

 

methods,that arecalled to lunch an application on your android phone.

  • onCreat method,
  • onStart method
  • and onResume method.

After these three methods are called you android application
is in a state that is   called running state .
What happens when we click back/home button on the screen while the android application is running?

Two methods are called  onPause method and onStop method . During your onPause methode , your application save the data that may be needed the app, and then it  stops when onstop() is called.

concept of android activity

android activity life cycle example

What will happen if we click back to our app?

Suppose  we have our application in running mode, and we suddenly clicked on home screen , what will happen if we click back to our app, well , in this case, again, three methods will be called,

  • onCreate
  • onRestart
  • onResume
    activity lifecycle methods in android

    activity lifecycle methods in android

Note: please note here restart is called, since we have our application already on backstact(memory where application stays , since user may probbably use that application again).

When is ondestroy method called?

It can be called, when we want compeltely remove the object of the application, it works the same as we call destructor in c++.

It can be hard coded, such clicking on exit button, to close the application , and remove it completely, or it is called when there is no space for this application, and its periorty is less then other application for the user, the android OS will then remove it from the backstack .

android acitivty lifecycle on destroy method

android acitivty lifecycle on destroy method

What happens when Android Screen orientation is changed?

When android screen orientation is changed, that mean if you switch from landscape mode to potrait mod, or viceversa in this case, every thing is destroyed first , and again, oncreat, on start, and onresume methods are called.

you can check this in the image below.

To learn how to change the screen orientation of android screen.

android activity lifecycle methode on screen orientation.

android activity lifecycle methode on screen orientation.

Now We will make an application that will prove that , what ever is printed above is true, and how actuall all this works.

Listing:#1 Activity lifecycle MainActivity.java


package com.example.androidactivitylifecycle;

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

 

public class MainActivity extends Activity {
public static final String TAG="ActivityLifeCycle";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Log.d(TAG, "Oncreate called");
}

@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.d(TAG, "Oncreate called");
}

@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.d(TAG, "Oncreate called");
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d(TAG, "OnResume called");
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.d(TAG, "OnRestart called");
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.d(TAG, "OnStop called");
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.d(TAG, "onDestroy called");
}

}

 

Listing#2 Android activity Lifecycle activit_main.xml

Well donot , need, it in this application, it was just to test , android activity life cycle.

How to Test the result of android lifecycle mehtods.

Just onpen you logcat and see the result, in logcate while performing the above operation, such as launching the app, then go to home screen while app is running, then screen orientation etc.

hope you have learnt some thing valueable here. follow us on facebook to learn more.

3

Android login example with mysql database

Android login example with mysql database: To day we will make android login application by using mysql database. Before i start coding, let me first tell you how the system work, and how android login system works with mysql database.

  • create a java file login.java and its user interface class login.xml.
  • create a database at 00webhost, for free, and also place the php mysql script file in file explored at public-html directory .
  • When we will run our android app, it will call a specific, url,(the php file path we have placed on server ), with some user login data such as username and password,  when the url is called , the server will run a php script , and through the result in jason formate.
  • our android application will recive that jason, and give the user a notifcation weather he is successfully loged in or not.

 

create my free app

How to connect android app to mysql database:

Step1: Make Mysql database for android login example:

Make an account in 00webhost, creat a domain, go to cpanel, select phpmyadmin, and creat a database with some name.

i will not be explaining here each step , on how to create database, but it shoudl have three fields, username, password, and id .

Step2: Make PHP script to connect Mysql database for android login example:

Listing#1 Login.php


<?php
mysql_connect("mysql8.000webhost.com","a5224389_elift","Hamdard123");
$db= mysql_select_db("a5224389_elift");
$password=$_POST["password"];
$username=$_POST["username"];
$total="lat ".$password. " lng ".$username;

// write data from my android app to a text file
file_put_contents('myTextFile.txt',$total);

//$sql1=mysql_query("select * from register where phone_number = '$number' and tracking_id= '$password' ");
//if ($sql1) {
// }
//else{
if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['password'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "Please Enter Both first Username and Password.";

//die will kill the page and not execute any code below, it will also
//display the parameter... in this case the JSON data our Android
//app will parse
die(json_encode($response));
}
$query = " SELECT * FROM login WHERE phone_number = '$username'and tracking_id='$password'";

$sql1=mysql_query($query);
$row = mysql_fetch_array($sql1);
if (!empty($row)) {
$response["success"] = 1;
$response["message"] = "Present, this username is already in use";
die(json_encode($response));
}
else{

$response["success"] = 0;
$response["message"] = "Please Enter Both hhh Username and Password.";
die(json_encode($response));
}
}
else{

$response["success"] = 0;
$response["message"] = "Please Enter Both Lastttt Username and Password.";
die(json_encode($response));
}
//$sql=mysql_query("select * from register where phone_number = $number ");
//while($row=mysql_fetch_assoc($sql))
//$output[]=$row;

//print(json_encode($output));// this will print the output in json
mysql_close();
?>

 

Listing#2login.java Android login example with mysql database


public class Login extends Activity implements OnClickListener{

private EditText user, pass;
private Button mSubmit, mRegister;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://ieeehiit.host22.com/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
mSubmit = (Button)findViewById(R.id.login);
mRegister = (Button)findViewById(R.id.button2);
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);

}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.button2:
//Intent i = new Intent("com.elift.app.REGISTER");
Intent i = new Intent("com.elift.app.REGISTER");
startActivity(i);
break;

default:
break;
}
}

class AttemptLogin extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));

Log.d("request!", "starting");

JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);

// check your log for json response
Log.d("Login attempt", json.toString());

// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Options.PHONE=username;
Intent ii = new Intent(Login.this,Options.class);//here Otions.class is the activity where we will move once login is authenticated.
finish();
startActivity(ii);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);

}
} catch (JSONException e) {
e.printStackTrace();
}

return null;

}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {

pDialog.dismiss();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}

}

}
}

 

As you can see in the aboue code we have make http request using the jason class.

Listing #2 Jason.java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {
static InputStream is = null;
static JSONObject jObj ;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(final String url) {

// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {

// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;

// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}

// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// Try to parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// Return the JSON Object.
return jObj;

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {

// Making HTTP request
try {

// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}

}

Listing3 login.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/username"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/username"
android:layout_weight="12.02"
android:src="@drawable/arrowstars" />

<Button
android:id="@+id/login"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/password"
android:layout_alignRight="@+id/password"
android:layout_below="@+id/password"
android:background="@drawable/log" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/login"
android:layout_alignRight="@+id/login"
android:layout_below="@+id/login"
android:background="@drawable/reg" />

<EditText
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/password"
android:layout_below="@+id/imageView1"
android:ems="10"
android:focusable="true"
android:hint="Enter Phone number"
android:imeOptions="actionNext"
android:inputType="number" />

<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/username"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Enter tracking id"
android:imeOptions="actionDone"
android:inputType="number" />

</RelativeLayout>

Here i have used some of the images as my buttons so you people please take care of that , either remove that are replace that with some sort of suitable size images.

 

Android mysql login example

Hope you people got some idea about android login with mysql example tutorial.

android services example

android services example :

In this article we will simply elaborate android service with example code given below .Android service is used for long running operation, such as downloading files, connecting to a newtwork , playing music in background, or updating data on server after specific intervals .

For all these long running operation we use android services, Why do we use this , because to take off load of the main activity and to create a separate thread of our long running ,Secondly if we don not do this, our application may crash and the gui may become freeze , in some situation where we need login etc .

More detail will be provided soon for now just see the code , and enjoy !

Android service which we have used in the example uses two methods

Android Services Lifecycle

Listing:-1 xml code for Android Services


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:text="stop service" />

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="start service" />

</RelativeLayout>

 

Make a new clas with name of ourservice and extent that from the service main class as shown in the example below!

 

Listing:-2 Ourservice.class


package com.simpleservices;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class Ourservice extends Service {

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(this, "service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy(){
Toast.makeText(this, "service started", Toast.LENGTH_LONG).show();
super.onDestroy();

}

}

Now here comes java mainActivity class that contain the code of calling the start and stop service methods


package com.simpleservices;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
Button start = (Button) findViewById(R.id.button1);
Button stop = (Button) findViewById(R.id.button2);
start.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(new Intent(getBaseContext(),Ourservice.class));
}
});

stop.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(new Intent(getBaseContext(),Ourservice.class));
}
});
return true;
}

}

dont forget to add service in the  mainfiest file as a child tag of the application tag.


<service android:name=".Ourservice.class"></service>

This was all from the tutorial will add more steps as soon as i get time, android service will be explained in a nice manner!