Wednesday, November 16, 2016

Parsing XML response in your Android App @ Mini App / Calling WebServices

Dear All

In the previous post i had uploaded how to generate XML response from Database.
Now in this post i am going to upload an android code by which you can fetch data into a ListView from any file which is generating XML response .
These kind of files are generally termed as web services.
To see please visit a live resource on

http://services.hanselandpetal.com/feeds/flowers.xml

So how you can parse such kind of response in your Android App. Below mentioned code is little bit tricky don't get confused.
I had create
A. Layout
     a. Layout for MainActivity
     b. Layout for a single row
B. Java Code
     a. ConnManager Class to read the data from given url in a string format
     b. A class to hold information in a manner as generated by XML  - Person
     c.  A Parser class to parse data from generated string in step-a into proper format like List
          PersonXMLParser
     d. An Adapter to provide data to ListView PersonAdapter
     e. MainActivity to work as a Controller
C. Output

So i think you understand the project structure lets see the code
A. Layout code
    a.

<ListView    android:id="@android:id/list"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_below="@+id/button"

    android:layout_marginTop="10dp">

</ListView>
<ProgressBar

    android:id="@+id/progressBar1"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_centerHorizontal="true"

    android:layout_centerVertical="true" />

<Button

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="Click for Data"

    android:id="@+id/button"

    android:onClick="loadData"

    android:layout_alignParentTop="true"

    android:layout_centerHorizontal="true" />


b. Single Row
<TextView    android:layout_width="wrap_content"

    android:layout_height="40dp"

    android:text="New Text"

    android:id="@+id/name"

    android:gravity="center_vertical"

    android:layout_alignParentTop="true"

    android:layout_alignParentStart="true" />

<TextView

    android:layout_width="wrap_content"

    android:layout_height="40dp"

    android:text="New Text"

    android:id="@+id/address"

    android:gravity="center_vertical"

    android:layout_alignParentTop="true"

    android:layout_centerHorizontal="true" />


B. Java Code 
  a. ConnManager
package com.example.ravigodara.parsejsonxml;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/** * Created by Ravi Godara on 10/9/2016. */public class ConnManager {
    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()));
            String line;
            while ((line=reader.readLine())!=null) {
                sb.append(line+"\n");
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        finally{
            if(reader!=null)
            {
                try {
                    reader.close();
                } catch (IOException e) {

                    e.printStackTrace();
                    return null;
                }
            }
        }
    }
}

b. Person Class
package com.example.ravigodara.parsejsonxml;

public class Person
{
    private int my_id;
    private String fname;
    private String address;
    public int getMy_id() {
        return my_id;
    }

    public void setMy_id(int my_id) {
        this.my_id = my_id;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}

c. XML Parser class as 

package com.example.ravigodara.parsejsonxml;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

public class PersonXMLParser {
    public static List<Person> parseFeed(String content)
    {
        try        {
            boolean inDataItemTag=false;
            String currentTagName="";
            Person person=null;
            List<Person> personList=new ArrayList<>();
            XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
            XmlPullParser parser=factory.newPullParser();
            parser.setInput(new StringReader(content));
            int eventType=parser.getEventType();
            while(eventType!=XmlPullParser.END_DOCUMENT)
            {
              
                switch(eventType)
                {
                    case XmlPullParser.START_TAG:
                        currentTagName=parser.getName();
                        if(currentTagName.equals("personal"))
                        {
                            inDataItemTag=true;
                            person=new Person();
                            personList.add(person);
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if(parser.getName().equals("personal"))
                        {
                            inDataItemTag=false;
                        }
                        currentTagName = "";
                        break;

                    case XmlPullParser.TEXT:
                        if(inDataItemTag && (person != null)){

                            switch(currentTagName)
                            {
                                case "uid":
                                  person.setMy_id(Integer.parseInt(parser.getText()));
                                    break;
                                case "first_name":
                                    person.setFname(parser.getText());
                                    break;
                                case "address":
                                    person.setAddress(parser.getText());
                                    break;

                                default:
                                    break;
                            }
                        }
                        break;
                }
                eventType=parser.next();
            }
            return personList;
        }catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

}

d. Adapter as 
package com.example.ravigodara.parsejsonxml;

import android.app.Activity;
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.List;


public class PersonAdapter extends ArrayAdapter<Person> {
    private Context context;
    private List<Person> personList;


    public PersonAdapter(Context context, int resource, List<Person> objects)
     {
        super(context, resource, objects);
        this.context = context;
        this.personList = objects;
    }

    @Override

    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater)
                  context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.single_person, parent, false);
        Person person = personList.get(position);
        TextView textView1 = (TextView) view.findViewById(R.id.name);
        TextView textView2 = (TextView) view.findViewById(R.id.address);
        textView1.setText(person.getFname());
        textView2.setText(person.getAddress());

        return view;

    }
}

e. MainActivity as 

package com.example.ravigodara.parsejsonxml;

import android.app.ListActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ListActivity {
    ProgressBar pb;
    List<MyTask> tasks;
    List<Person> personList;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pb=(ProgressBar) findViewById(R.id.progressBar1);
        pb.setVisibility(View.INVISIBLE);
        tasks=new ArrayList<>();
    }
    public void loadData(View view)
    {
        requestData("http://10.0.2.2/anddb/xmlres.php");
    }
    private void requestData(String uri) {
        MyTask task=new MyTask();
        task.execute(uri);
    }
   
    private class MyTask extends AsyncTask<String, String, String> {

        @Override        protected void onPreExecute() {
            
            if(tasks.size()==0)
            {
                pb.setVisibility(View.VISIBLE);
            }
            tasks.add(this);
        }
        @Override        protected String doInBackground(String... params) {
            String content=ConnManager.getData(params[0]);
            return content;
        }
        @Override        protected void onPostExecute(String result) {
          
            personList=PersonXMLParser.parseFeed(result);
            updateDisplay();
            tasks.remove(this);
            if(tasks.size()==0)
            {
                pb.setVisibility(View.INVISIBLE);
            }

        }
        @Override        protected void onProgressUpdate(String... values) {
            //updateDisplay(values[0]);        }
    }
    protected void updateDisplay() {
      
        PersonAdapter adapter = new PersonAdapter(this,
                              R.layout.single_person, personList);
        setListAdapter(adapter);
    }
}

C. output as 




**** Don't forget t add Internet Permission in manifest file 








Generate XML Response from Data-Base

Hello All

I am uploading a code by which you can generate XML response from your database.
As you know the data can move on network in a particular format.
The two popular format are XML and JSON.
Then generated response can be parsed in any Application like Web App, Mobile App- Android or iPhone.
Most of the Market Captured Apps  are working with such kind of concepts.
Let's start

Step-1: Install Your database server on your system -n I am using XAMPP as a tool to create
             Database as well as server side script language(PHP)
Step-2: Create a database on your localhost by using phpmyadmin panel
Step-3: Create a table with some fields like i have Database named as mydb and table name is
             myinfo as below mentioned
 

Step-4: Create a php file in htdocs folder of Xampp directory
             I had created a new folder in htdocs named anddb - > xmlres.php file as

<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('mydb');

$sql = "SELECT * FROM myinfo ORDER BY id";
$res = mysql_query($sql);

$xml = new SimpleXMLElement('<info/>');

 while ($row = mysql_fetch_assoc($res))
{
    $track = $xml->addChild('personal');
    $track->addChild('uid', $row['id']);
    $track->addChild('first_name', $row['fname']);
 
    $track->addChild('address', $row['address']);

}

Header('Content-type: text/xml');
print($xml->asXML());
?>

Step-5: Run your php file on the localhost the response will be like

**** How to fetch / parse this response in Android - check in my next upload ***


Tuesday, November 15, 2016

Socket Programming in Android - Client Server Communication

Dear All

As you know socket plays an important role in the client server communication.

Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening.

In my example i had created two Apps. 
1. ServerSocket
2. ClientSocket
ServerSocket has
a. Layout
b. An interface 
c. MyServer.java class
d. MainActivity

The codes are in sequence is as 
 a. Layout
<TextView

    android:layout_width="wrap_content"

    android:layout_height="40dp"

    android:text="Client Message "

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

<Button

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="Start Server"

    android:id="@+id/button"

    android:onClick="connect"

   />
b. An interface 
package com.exam.ravi.serversocket;

public interface DataDisplay {
    void Display(String messgae);
}


c. MyServer.java class
package com.exam.ravi.serversocket;

import android.os.Handler;
import android.os.Message;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {
    Thread m_objThread;
    ServerSocket m_server;
    DataDisplay m_dataDisplay;

    public MyServer() { }
    public void setEventListener(DataDisplay dataDisplay)
    {
        m_dataDisplay = dataDisplay;
    }
    public void startListening()
    {
        m_objThread = new Thread(new Runnable() {
            @Override            public void run() {
                try                {
                    m_server = new ServerSocket(2001);
                    Socket connectedSocket = m_server.accept();
                    Message clientMessage = Message.obtain();
                    ObjectInputStream ois = new 
                         ObjectInputStream(connectedSocket.getInputStream());
                    String strMessage = (String) ois.readObject();
                    clientMessage.obj = strMessage;
                    mHandler.sendMessage(clientMessage);
                    ObjectOutputStream oos = new 
                           ObjectOutputStream(connectedSocket.getOutputStream());
                    oos.writeObject("Hi Client....");
                    ois.close();
                    oos.close();
                    m_server.close();
                }
                catch (Exception e)
                {

                    e.printStackTrace();
                }
            }
        });
        m_objThread.start();
    }
    Handler mHandler = new Handler()
    {
        @Override        public void handleMessage(Message msg) {
            m_dataDisplay.Display(msg.obj.toString());
        }
    };

}

d. MainActivity
package com.exam.ravi.serversocket;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements DataDisplay{
    TextView serverMessage;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        serverMessage = (TextView) findViewById(R.id.textClient);


    }
    public void connect(View view)
    {
        MyServer server = new MyServer();
        server.setEventListener(this);
        server.startListening();
    }
    public void Display(String message)
    {
        serverMessage.setText(" " +message);
    }
}

ClientSocket has
a. Layout
b. MainActivity
a. Layout is as 
<TextView

    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:text="Server message"
    android:id="@+id/txtser" />

<Button    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start Client "
    android:id="@+id/btnclk"
    android:onClick="start"
     />
b. MainActivity is as 
package com.exam.ravi.clientsocket;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
    TextView sermsg;
    Thread mobjThreadClient;
    Socket clientSocket;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sermsg = (TextView) findViewById(R.id.txtser);

    }
    public void start(View view)
    {
        mobjThreadClient = new Thread(new Runnable() {
            @Override            public void run() {
                try                {
                    clientSocket = new Socket("127.0.0.1",2001);
                    ObjectOutputStream oos = new 
                              ObjectOutputStream(clientSocket.getOutputStream());
                    oos.writeObject("Hellow Server... ");
                    Message serverMessage = Message.obtain();
                    ObjectInputStream ois = new 
                          ObjectInputStream(clientSocket.getInputStream());
                    String strmsg= (String ) ois.readObject();
                    serverMessage.obj=strmsg;
                    mHandler.sendMessage(serverMessage);
                    oos.close();
                    ois.close();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
        mobjThreadClient.start();
    }
    Handler mHandler = new Handler()
    {
        @Override        public void handleMessage(Message msg) {
            messageDisplay(msg.obj.toString());
        }
    };
    public void messageDisplay(String str)
    {
        sermsg.setText(" "+ str);
    }
}

Don't forget to add permission in both App
<uses-permission android:name="android.permission.INTERNET"/>

Output Will be Like 




User Defined Permission in Android


Add Security in your Android App @Customized Permission 

Hello All

As you know security  is a major concern for any kind of App.
Android provides it's own Security architecture with a set of Predefined permission.
Now the question is can you add your own defined permission in your App.
Answer is Yes
How???

To add your own permission in App you have to defined permission in the manifest file.
Then in any another app you use the defined permission to access the stuff of predefined App.

Just see the example.

I had created two Apps.

In the first app i defined the permission in manifest file as 

<permission android:name="com.example.ravigodara.permissiontestclient.mypermission"

    android:label="my_permission"

android:protectionLevel= "dangerous" /> 

Then add an Intent filter with an Action to access from outside as 
<activity android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter >
     <action android:name="com.example.ravigodara.permissiontestclient.MyAction" />
     <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

Nothing special in the layout of MainActivity only a Text Message is there.

In the second App i used defined permission by adding 

<uses-permission 
      android:name="com.example.ravigodara.permissiontestclient.mypermission"/>

The layout of second App contains a Button as 
<Button

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="New Button"

    android:id="@+id/button"

    android:layout_centerVertical="true"

    android:layout_centerHorizontal="true" /> 

And Java Code - MainActivity of second app is as 
package com.example.ravigodara.permissiontestserver;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "PerTest";
    Button button;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {

            @Override            public void onClick(View v) {
                Log.d(TAG, "Button pressed!!");
                Intent in = new Intent();
                in.setAction("com.example.ravigodara.permissiontestclient.MyAction");
                in.addCategory("android.intent.category.DEFAULT");
                startActivity(in);
            }
        });
    }
}




Handling Thread in Android

Dear All

As we know how thread plays an important role to perform multiple task simultaneously in Java.
In this example i am handling the Main Thread and performing an operation to wait for a while.
Just read the example.
A. Output will be
1. Before Button Pressed



2. After 5 sec of Button Pressed



B. xml file is as   activity_main.xml

<TextView    android:id="@+id/myTextView"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_centerHorizontal="true"

    android:layout_centerVertical="true"

    android:text="Hello_world" />
<Button        android:id="@+id/button1"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_below="@+id/myTextView"

    android:layout_centerHorizontal="true"

    android:layout_marginTop="48dp"

    android:onClick="buttonPressed"

    android:text="Click Me" />

C. Java Code  MainActivity.java

package com.example.ravigodara.singlethread;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView =(TextView)findViewById(R.id.myTextView);
    }
    public void buttonPressed(View view)
    {
        long endTime = System.currentTimeMillis() + 5*1000;
        while (System.currentTimeMillis() < endTime) {
            synchronized (this) {
                try {
                    wait(endTime - System.currentTimeMillis());
                }
                catch (Exception e) {
                }
            }
        }

        textView.setText("Button Pressed");

    }

}

Friday, November 11, 2016

Android Objective Technical Questions ( Set - A)

Dear All

I am going to upload a series of Technical Questions - Objective related to Android. These questions are very important as per placement concern.

Please put your suggestions in the comment box.


Q.1: What is Android?
                A. Operating System
            B. Mobile
            C. Programming Language
            D. None of the Above
Q.2: Who is the founder of Android?
       A. Bajarne Stroustrup
       B. Dennis Ritche
       C. Andy Rubin
       D. Reto Mier
Q.3: Google acquired Android Inc in
                A. August 17,2007
                B. August 30,2008
                C. August 17,2005
                D. None of the Above
Q.4: What is full form of OHA?
                A. Open House Alliance
                B. Open Handset Alliance
                C. Open Hand Alliance
                D. None of the Above
Q.5: First Android phone is
                A. T-Mobile G1
                B. H-Mobile G2
                C. T-Mobile G
                D. None of the Above   
Q.6: First Working Android OS is
                A. Donut
                B. Éclair
                C. Cupcake
        D. All
Q.7: Android version name started with letter G
                A. Gingerbread
                B. Greatbread
                C. Golf
                D. All
Q.8: API included with Honeycomb
                A. API11
                B. API12
                C. API13
                D. All
Q.9: API included with Ice-cream Sandwich
                A. API13
                B. API14
                C. API19
                D. None of the Above
Q.10: API included with JellyBean
                A. API16
                B. API17
                C. API18
                D. All the Above

Right Answers

 A        C        C        B        A       C       A        D           B          D 

Wednesday, November 9, 2016

iPhone - Timer App Use of Navigation Bar, ToolBar and Barbuttons

Dear All....

Hello , Today i am uploading a Timer App in which u found the use of Navigation Bar , ToolBar and Buutons on these.


navigation bar appears at the top of an app screen, below the status bar, and enables navigation through a series of hierarchical app screens. 

The toolbar on the bottom of the Home screen appears on every page. You can place any icons on the toolbar that you want. 

Navigation Bat Buttons -  The Buttons which is used to perform some actions added on Navigation Bar / ToolBar

I m using Xcode 7.3 as a IDE and Swift as a programming language.

Few steps are.....

Step - 1. Launch your Xcode
Step - 2. Create a new project with Single View App options
Step - 3. Design whatever you want to add as a UI Component on Main.storyboard
Step - 4. Add Navigation Bar , ToolBar and  Bar Buttons as shown in layout 

            4.1 : Play Button will start the Timer
            4.2 : Pause Button will stop at the Current  Value
            4.3 : Refresh Button will reset from Beginning Step - 5. Add Appropriate code in this controller file.
Step - 6 . Select Emulator as you wish and run the app.



A. Output will be like ..... 




B. Swift code is as


import UIKit

class ViewController: UIViewController  {

    var timer = NSTimer()
    
    var time = 0
    
    @IBOutlet var timeLabel: UILabel!
    func increaseTime()
    {
        time += 1
        timeLabel.text = String(time)
    }
    
    @IBAction func playButton(sender: AnyObject) {
    
       timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(increaseTimer),  userInfo: nil, repeats: true)
        //timer =  NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("increaseTime"), userInfo: nil, repeats: true) Below Swift2.2
    }
    
    
    @IBAction func stopButton(sender: AnyObject) {
    
        timer.invalidate()
        time = 0
        timeLabel.text = " 0 "
    }
    
    @IBAction func pauseBut(sender: AnyObject) {
        timer.invalidate()
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
   

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}